less_go

package
v0.4.2 Latest Latest
Warning

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

Go to latest
Published: Feb 26, 2026 License: Apache-2.0 Imports: 27 Imported by: 0

README

less.go

A complete Go port of less.js - the popular CSS preprocessor. This implementation maintains 1:1 functionality with less.js v4.2.2 while following Go idioms and conventions.

Status

Initial Release (v0.1.0)

  • 191/191 integration tests passing (100%)
  • 100 perfect CSS matches with less.js output
  • 91 error handling tests correctly failing as expected
  • 3,012 unit tests passing

Installation

go get github.com/toakleaf/less.go/less

Quick Start

Basic Compilation
package main

import (
    "fmt"
    "log"

    less "github.com/toakleaf/less.go/less"
)

func main() {
    source := `
        @primary: #4a90d9;

        .button {
            background: @primary;
            color: white;
            &:hover {
                background: darken(@primary, 10%);
            }
        }
    `

    result, err := less.Compile(source, nil)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(result.CSS)
}

Output:

.button {
  background: #4a90d9;
  color: white;
}
.button:hover {
  background: #3275b9;
}
Compile from File
result, err := less.CompileFile("styles.less", &less.CompileOptions{
    Compress: true,
})
if err != nil {
    log.Fatal(err)
}
fmt.Println(result.CSS)
With Options
result, err := less.Compile(source, &less.CompileOptions{
    Filename:    "styles.less",
    Compress:    true,
    StrictUnits: true,
    Math:        less.Math.ParensDivision,
    Paths:       []string{"./imports", "./node_modules"},
    GlobalVars: map[string]any{
        "theme-color": "#ff6600",
    },
})

API Reference

Compile Function
func Compile(input string, options *CompileOptions) (*CompileResult, error)

The main entry point for compiling LESS source code to CSS.

CompileFile Function
func CompileFile(filename string, options *CompileOptions) (*CompileResult, error)

Convenience function to read and compile a LESS file.

CompileResult
type CompileResult struct {
    CSS     string   // Compiled CSS output
    Map     string   // Source map (if enabled)
    Imports []string // List of imported files
}
CompileOptions
Option Type Description
Paths []string Additional include paths for @import resolution
Filename string File name for error messages and source maps
Compress bool Enable CSS minification
StrictUnits bool Enable strict unit checking for math operations
Math MathType Math evaluation mode
RewriteUrls RewriteUrlsType URL rewriting behavior
Rootpath string Base path for URL rewriting
UrlArgs string Query string to append to URLs
GlobalVars map[string]any Variables injected before compilation
ModifyVars map[string]any Variables injected after (override existing)
EnableJavaScriptPlugins bool Enable JavaScript plugin support via Node.js
JavascriptEnabled bool Enable inline JavaScript evaluation
Math Modes
less.Math.Always         // Always evaluate math expressions
less.Math.ParensDivision // Require parens for division (default)
less.Math.Parens         // Only evaluate math in parentheses
URL Rewriting Modes
less.RewriteUrls.Off   // No URL rewriting
less.RewriteUrls.Local // Rewrite local URLs only
less.RewriteUrls.All   // Rewrite all URLs

Feature Parity with less.js

less.go implements 100% feature parity with less.js v4.2.2:

Core Features
  • Variables and variable interpolation
  • Nested rules and selectors
  • Mixins (parametric, guards, closures, recursion)
  • Namespacing
  • Extend functionality
  • Import system (including npm module resolution)
  • Detached rulesets
  • CSS guards
  • Property merge (+ and +_)
Built-in Functions

All 60+ built-in functions are implemented:

Category Functions
Color lighten, darken, saturate, desaturate, fade, fadein, fadeout, spin, mix, tint, shade, contrast, hue, saturation, lightness, alpha, etc.
Math ceil, floor, sqrt, abs, sin, cos, tan, asin, acos, atan, pi, pow, mod, min, max, round, percentage
String e, escape, replace, %, upper, lower
Type isnumber, isstring, iscolor, iskeyword, isurl, ispixel, ispercentage, isem, isunit, isruleset
List length, extract, range, each
Misc color, image-width, image-height, data-uri, svg-gradient, get-unit, unit, convert, if, boolean
Blending multiply, screen, overlay, softlight, hardlight, difference, exclusion, average, negation
At-Rules
  • @media (with query bubbling and merging)
  • @keyframes / @-webkit-keyframes
  • @supports
  • @font-face
  • @container (container queries)
  • @document
  • @page
  • @charset
  • @namespace
Media Queries
  • Full media query support
  • Query bubbling out of nested rulesets
  • Media query merging with detached rulesets
  • Nested media query handling

Plugin System

less.go provides full JavaScript plugin compatibility through a Node.js runtime bridge.

Enabling Plugins
result, err := less.Compile(source, &less.CompileOptions{
    EnableJavaScriptPlugins: true,
})
Plugin Types
  1. Custom Functions - Add custom LESS functions
  2. Visitors - Transform the AST during compilation
  3. Pre-processors - Transform source before parsing
  4. Post-processors - Transform CSS after compilation
  5. File Managers - Custom import resolution
Using Plugins in LESS
@plugin "my-plugin";

.example {
    color: my-custom-function();
}
Writing JavaScript Plugins
module.exports = {
    install: function(less, pluginManager, functions) {
        // Register custom function
        functions.add('pi', function() {
            return less.dimension(Math.PI);
        });

        // Register visitor
        pluginManager.addVisitor(new MyVisitor());

        // Register processors
        pluginManager.addPreProcessor(new MyPreProcessor(), 1000);
        pluginManager.addPostProcessor(new MyPostProcessor(), 1000);
    },

    minVersion: [2, 0, 0]
};
Plugin Architecture
┌─────────────────────────────────────────────────────────┐
│                      Go Compiler                        │
│  ┌──────────────┐    ┌──────────────┐    ┌──────────┐ │
│  │    Parser    │───>│  Evaluator   │───>│  ToCSS   │ │
│  └──────────────┘    └──────────────┘    └──────────┘ │
│          │                  │                  │        │
│          ▼                  ▼                  ▼        │
│  ┌─────────────────────────────────────────────────┐   │
│  │              Plugin Manager                      │   │
│  │  • Visitors  • Pre/Post Processors  • Functions │   │
│  └─────────────────────────────────────────────────┘   │
│                         │                              │
└─────────────────────────│──────────────────────────────┘
                          │ IPC (JSON/stdin-stdout)
                          ▼
┌─────────────────────────────────────────────────────────┐
│                  Node.js Runtime                        │
│  ┌──────────────────────────────────────────────────┐  │
│  │                  plugin-host.js                   │  │
│  │  • Plugin loading via require()                   │  │
│  │  • Function execution                             │  │
│  │  • Visitor callbacks                              │  │
│  └──────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────┘

Go-Specific Features

These features are unique to the Go implementation:

1. Type-Safe API

Unlike the JavaScript version's dynamic options, less.go provides strongly-typed configuration:

options := &less.CompileOptions{
    Math:        less.Math.ParensDivision,  // Type-safe enum
    RewriteUrls: less.RewriteUrls.Local,    // Type-safe enum
    Compress:    true,
}
2. Lazy Plugin Bridge

The Node.js runtime is only started when plugins are actually used:

// Node.js NOT started - no @plugin directives in source
result, err := less.Compile(source, &less.CompileOptions{
    EnableJavaScriptPlugins: true,
})

// Node.js started only when @plugin is encountered during parsing
3. IPC Mode Configuration

Control how the Go compiler communicates with the Node.js plugin runtime:

Mode Description Best For
JSON (default) JSON over stdin/stdout Many small function calls
SHM Shared memory with binary protocol Large AST transfers

Environment variable override:

LESS_JS_IPC_MODE=json  # Default, 70% faster for typical usage
LESS_JS_IPC_MODE=shm   # Better for large data transfers

Per-plugin configuration:

module.exports = {
    install: function(less, pm, functions) { ... },
    ipcMode: 'json'  // or 'shm'
};
4. Context-Free Functions

Plugin functions can be marked as context-free for better performance:

// Context-free functions skip scope serialization
// Great for pure functions like math operations
opts = append(opts, WithContextFree())
5. Structured Errors
type LessError struct {
    Type     string   // "Syntax", "Argument", etc.
    Message  string   // Error description
    Filename string   // File where error occurred
    Line     *int     // Line number (1-based)
    Column   int      // Column number
    Extract  []string // Context lines
}
6. Memory Optimization

Object pooling via sync.Pool for frequently allocated types:

  • Rulesets
  • Expressions
  • Selectors
  • Plugin scopes
  • Math contexts

Performance

Comparison with less.js
Metric less.js less.go Notes
Cold start ~993µs/file ~931µs/file Go ~6% faster
Warm (JIT) ~428µs/file ~883µs/file JS JIT advantage
Memory/file - 0.56 MB With 10k allocations
Benchmarking
# Suite-mode benchmark (realistic workload)
pnpm bench:compare:suite

# Per-file comparison
pnpm bench:compare

# Go-only benchmarks
pnpm bench:go:suite    # Suite mode
pnpm bench:go          # Per-file warm
pnpm bench:go:cold     # Per-file cold

# JavaScript benchmarks
pnpm bench:js
Bootstrap 4 Compilation

Bootstrap 4's full LESS source compiles in approximately 1.2 seconds.

Environment Variables

Variable Description
LESS_GO_DEBUG=1 Enhanced debugging output
LESS_GO_QUIET=1 Suppress output, show summary only
LESS_GO_DIFF=1 Show CSS diffs for test failures
LESS_GO_TRACE=1 Show evaluation trace
LESS_GO_JSON=1 Output results as JSON
LESS_JS_IPC_MODE Plugin IPC mode: json or shm

Testing

# Run all integration tests
pnpm test:go

# Run unit tests
pnpm test:go:unit

# Quick summary
LESS_GO_QUIET=1 pnpm test:go 2>&1 | tail -100

# Debug specific test
LESS_GO_DEBUG=1 go test -v -run TestIntegrationSuite/<suite>/<testname>

Examples

Variables and Nesting
@base-color: #4a90d9;
@spacing: 16px;

.card {
    padding: @spacing;
    background: white;

    .header {
        color: @base-color;
        border-bottom: 1px solid lighten(@base-color, 30%);
    }

    .body {
        padding: @spacing / 2;
    }
}
Mixins with Guards
.text-color(@bg) when (lightness(@bg) >= 50%) {
    color: black;
}

.text-color(@bg) when (lightness(@bg) < 50%) {
    color: white;
}

.dark-theme {
    @bg: #333;
    background: @bg;
    .text-color(@bg);
}
Extend
.button {
    display: inline-block;
    padding: 10px 20px;
    border-radius: 4px;
}

.primary-button {
    &:extend(.button);
    background: blue;
    color: white;
}
Loops with each()
@colors: red, green, blue;

each(@colors, {
    .color-@{value} {
        color: @value;
    }
});
Detached Rulesets
@mobile: ~"(max-width: 768px)";

@card-styles: {
    padding: 20px;
    background: white;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
};

.card {
    @card-styles();

    @media @mobile {
        padding: 10px;
    }
}
Using Plugins
@plugin "less-plugin-functions";

.example {
    // Use custom function from plugin
    color: my-custom-color(#ff0000, 50%);
}

License

Apache License 2.0 - See LICENSE

Contributing

See CONTRIBUTING.md for guidelines.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	MediaSyntax     = MediaSyntaxOptions{QueryInParens: true}
	ContainerSyntax = ContainerSyntaxOptions{QueryInParens: true}
)
View Source
var (
	Math        = struct{ Always, ParensDivision, Parens MathType }{MathAlways, MathParensDivision, MathParens}
	RewriteUrls = struct{ Off, Local, All RewriteUrlsType }{RewriteUrlsOff, RewriteUrlsLocal, RewriteUrlsAll}
)
View Source
var (
	KeywordTrue  = NewKeyword("true")
	KeywordFalse = NewKeyword("false")
)
View Source
var AtRuleSyntaxContainerSyntaxOptions = ContainerSyntaxOptionsType{
	QueryInParens: true,
}
View Source
var AtRuleSyntaxMediaSyntaxOptions = MediaSyntaxOptionsType{
	QueryInParens: true,
}
View Source
var Colors = map[string]string{}/* 148 elements not displayed */

Default export equivalent

View Source
var DefaultLogger = NewLogger()
View Source
var DefaultRegistry = makeRegistry(nil)
View Source
var MathFunctions = map[string]any{
	"ceil":  Ceil,
	"floor": Floor,
	"sqrt":  Sqrt,
	"abs":   Abs,
	"tan":   Tan,
	"sin":   Sin,
	"cos":   Cos,
	"atan":  Atan,
	"asin":  Asin,
	"acos":  Acos,
	"round": Round,
}

MathFunctions provides all the mathematical functions that were in math.js

View Source
var NoSpaceCombinators = map[string]bool{
	"":  true,
	" ": true,
	"|": true,
}
View Source
var NumberFunctions = map[string]interface{}{
	"min":        Min,
	"max":        Max,
	"convert":    Convert,
	"pi":         Pi,
	"mod":        Mod,
	"pow":        Pow,
	"percentage": Percentage,
}

NumberFunctions provides all the number-related functions

View Source
var StringFunctions = map[string]interface{}{
	"e":       E,
	"escape":  Escape,
	"replace": Replace,
	"%":       Format,
}

StringFunctions provides all the string-related functions

View Source
var StyleFunctions = map[string]interface{}{
	"style": Style,
}

StyleFunctions provides all the style-related functions

View Source
var SvgFunctions = map[string]interface{}{
	"svg-gradient": SvgGradient,
}

SvgFunctions provides all the svg-related functions

View Source
var UnitConversionsAngle = map[string]float64{
	"rad":  1 / (2 * math.Pi),
	"deg":  1 / 360.0,
	"grad": 1 / 400.0,
	"turn": 1,
}
View Source
var UnitConversionsDuration = map[string]float64{
	"s":  1,
	"ms": 0.001,
}
View Source
var UnitConversionsLength = map[string]float64{
	"m":  1,
	"cm": 0.01,
	"mm": 0.001,
	"in": 0.0254,
	"px": 0.0254 / 96,
	"pt": 0.0254 / 72,
	"pc": 0.0254 / 72 * 12,
}

Functions

func AddListener

func AddListener(listener any)

func Average

func Average(cb, cs float64) float64

func Bind

func Bind(renderFactoryFunc func(string, ...any) any, context ContextInterface, environment any, parseTreeConstructor func(any, any) any) func(string, ...any) any

Bind creates a bound render function that matches JavaScript's render.bind(context) behavior

func Chunker

func Chunker(input string, fail func(msg string, pos int)) []string

func ClearInternTable

func ClearInternTable()

ClearInternTable clears the intern table. This should only be used in testing or when you want to release all interned strings.

func Clone

func Clone(obj map[string]any) map[string]any

Clone creates a shallow copy of a map

func ColorARGB

func ColorARGB(color any) any

ColorARGB returns the color in ARGB hex format

func ColorAlpha

func ColorAlpha(color any) any

ColorAlpha extracts the alpha channel

func ColorBlue

func ColorBlue(color any) any

ColorBlue extracts the blue channel

func ColorContrast

func ColorContrast(color, dark, light, threshold any) any

ColorContrast chooses a contrasting color

func ColorDarken

func ColorDarken(color, amount any, method ...any) any

ColorDarken decreases lightness

func ColorDesaturate

func ColorDesaturate(color, amount any, method ...any) any

ColorDesaturate decreases saturation

func ColorFade

func ColorFade(color, amount any) any

ColorFade sets opacity to a specific value

func ColorFadeIn

func ColorFadeIn(color, amount any, method ...any) any

ColorFadeIn increases opacity

func ColorFadeOut

func ColorFadeOut(color, amount any, method ...any) any

ColorFadeOut decreases opacity

func ColorFunction

func ColorFunction(colorStr any) any

ColorFunction parses a color from a hex string or keyword

func ColorGrayscale

func ColorGrayscale(color any) any

ColorGrayscale is an alias for greyscale

func ColorGreen

func ColorGreen(color any) any

ColorGreen extracts the green channel

func ColorGreyscale

func ColorGreyscale(color any) any

ColorGreyscale converts to grayscale

func ColorHSL

func ColorHSL(h, s, l any) any

ColorHSL creates a color from HSL values

func ColorHSLA

func ColorHSLA(h, s, l, a any) any

ColorHSLA creates a color from HSLA values

func ColorHSV

func ColorHSV(h, s, v any) any

ColorHSV creates a color from HSV values

func ColorHSVA

func ColorHSVA(h, s, v, a any) any

ColorHSVA creates a color from HSVA values

func ColorHSVHue

func ColorHSVHue(color any) any

ColorHSVHue extracts the hue (HSV)

func ColorHSVSaturation

func ColorHSVSaturation(color any) any

ColorHSVSaturation extracts the saturation (HSV)

func ColorHSVValue

func ColorHSVValue(color any) any

ColorHSVValue extracts the value (HSV)

func ColorHue

func ColorHue(color any) any

ColorHue extracts the hue (HSL)

func ColorLighten

func ColorLighten(color, amount any, method ...any) any

ColorLighten increases lightness

func ColorLightness

func ColorLightness(color any) any

ColorLightness extracts the lightness (HSL)

func ColorLuma

func ColorLuma(color any) any

ColorLuma calculates the luma value

func ColorLuminance

func ColorLuminance(color any) any

ColorLuminance calculates the luminance value using the standard formula

func ColorMix

func ColorMix(color1, color2, weight any) any

ColorMix mixes two colors

func ColorRGB

func ColorRGB(r, g, b any) any

ColorRGB creates a color from RGB values

func ColorRGBA

func ColorRGBA(r, g, b, a any) any

ColorRGBA creates a color from RGBA values

func ColorRed

func ColorRed(color any) any

ColorRed extracts the red channel

func ColorSaturate

func ColorSaturate(color, amount any, method ...any) any

ColorSaturate increases saturation

func ColorSaturation

func ColorSaturation(color any) any

ColorSaturation extracts the saturation (HSL)

func ColorShade

func ColorShade(color, amount any) any

ColorShade mixes with black

func ColorSpin

func ColorSpin(color, amount any) any

ColorSpin rotates the hue

func ColorTint

func ColorTint(color, amount any) any

ColorTint mixes with white

func Compare

func Compare(a, b *Node) int

Compare compares two nodes

func CopyArray

func CopyArray(arr []any) []any

Should just use go's build in copy function instead of this when possible

func CopyOptions

func CopyOptions(obj1, obj2 map[string]any) map[string]any

CopyOptions processes and copies options with special handling for math and rewriteUrls

func CreateLessContextWithPlugins

func CreateLessContextWithPlugins(options map[string]any) (*LessContext, *NodeJSPluginBridge, error)

CreateLessContextWithPlugins creates a LessContext configured to use Node.js plugins. This is a convenience function for enabling plugin support in the parsing pipeline.

func CreateParseWithContext

func CreateParseWithContext(environment any, parseTree any, importManagerFactory func(any, *Parse, map[string]any) *ImportManager) func(*LessContext, string, map[string]any, ParseCallbackFunc) any

CreateParseWithContext creates a parse function that can be called with a specific context This is closer to how the JavaScript version works with 'this' context

func CreateRender

func CreateRender(environment any, parseTreeConstructor func(any, any) any) func(string, ...any) any

CreateRender creates a render function that matches JavaScript's export default function(environment, ParseTree)

func DataURI

func DataURI(context map[string]any, mimetypeNode, filePathNode any) any

func Debug

func Debug(msg any)

func DebugInfo

func DebugInfo(context map[string]any, node any, separator string) string

func DefaultStylize

func DefaultStylize(str string, style string) string

func DefaultValue

func DefaultValue[T any]() T

DefaultValue returns a default value for common types when operations would fail

func Defaults

func Defaults(obj1, obj2 map[string]any) map[string]any

Defaults merges default properties from obj1 into obj2

func Difference

func Difference(cb, cs float64) float64

func Each

func Each(list any, rs any) any

func EachWithContext

func EachWithContext(list any, rs any, ctx *Context) any

func Error

func Error(msg any)

func Exclusion

func Exclusion(cb, cs float64) float64

func Extract

func Extract(values any, indexNode any) any

func Factory

func Factory(environment map[string]any, fileManagers []any) map[string]any

func FlattenArray

func FlattenArray(arr []any, result ...[]any) []any

func GetBooleanFunctions

func GetBooleanFunctions() map[string]any

func GetColorBlendingFunctions

func GetColorBlendingFunctions() map[string]any

func GetColorFunctions

func GetColorFunctions() map[string]any

GetColorFunctions returns the color function registry

func GetContextMapFromPool added in v0.4.0

func GetContextMapFromPool() map[string]any

GetContextMapFromPool gets a map from the pool and clears it for reuse. The returned map has capacity 16 but length 0.

func GetDataURIFunctions

func GetDataURIFunctions() map[string]any

func GetDebugInfo

func GetDebugInfo(context map[string]any, ruleset *Ruleset, separator string) string

func GetFrameSliceFromPool

func GetFrameSliceFromPool() []any

GetFrameSliceFromPool gets a slice from the pool and prepares it for use. The returned slice has length 0 but may have capacity from previous use.

func GetItemsFromNode

func GetItemsFromNode(node any) []any

func GetListFunctions

func GetListFunctions() map[string]any

func GetTypeIndexForNodeType

func GetTypeIndexForNodeType(nodeType string) int

GetTypeIndexForNodeType returns the TypeIndex for a given node type string. Used by node constructors to set the TypeIndex field.

func GetWrappedBooleanFunctions

func GetWrappedBooleanFunctions() map[string]interface{}

GetWrappedBooleanFunctions returns boolean functions wrapped for registry. The map is pre-computed at init time and cached for efficiency.

func GetWrappedColorBlendingFunctions

func GetWrappedColorBlendingFunctions() map[string]interface{}

GetWrappedColorBlendingFunctions returns color blending functions wrapped for registry. The map is pre-computed at init time and cached for efficiency.

func GetWrappedColorFunctions

func GetWrappedColorFunctions() map[string]interface{}

GetWrappedColorFunctions returns color functions wrapped for registry. The map is pre-computed at init time and cached for efficiency.

func GetWrappedDataURIFunctions

func GetWrappedDataURIFunctions() map[string]interface{}

GetWrappedDataURIFunctions returns data-uri functions wrapped for registry. The map is pre-computed at init time and cached for efficiency.

func GetWrappedListFunctions

func GetWrappedListFunctions() map[string]interface{}

func GetWrappedMathFunctions

func GetWrappedMathFunctions() map[string]interface{}

GetWrappedMathFunctions returns math functions wrapped for registry. The map is pre-computed at init time and cached for efficiency.

func GetWrappedNumberFunctions

func GetWrappedNumberFunctions() map[string]interface{}

GetWrappedNumberFunctions returns number functions wrapped for registry. The map is pre-computed at init time and cached for efficiency.

func GetWrappedStringFunctions

func GetWrappedStringFunctions() map[string]interface{}

GetWrappedStringFunctions returns string functions wrapped with FunctionDefinition interface. The map is pre-computed at init time and cached for efficiency.

func GetWrappedStyleFunctions

func GetWrappedStyleFunctions() map[string]interface{}

GetWrappedStyleFunctions returns style functions for registry

func GetWrappedSvgFunctions

func GetWrappedSvgFunctions() map[string]interface{}

GetWrappedSvgFunctions returns svg functions wrapped with FunctionDefinition interface. The map is pre-computed at init time and cached for efficiency.

func GetWrappedTypesFunctions

func GetWrappedTypesFunctions() map[string]interface{}

GetWrappedTypesFunctions returns type functions wrapped in FunctionDefinition adapters. The map is pre-computed at init time and cached for efficiency.

func Hardlight

func Hardlight(cb, cs float64) float64

func If

func If(context *Context, condition any, trueValue any, falseValue any) any

If takes unevaluated nodes for lazy evaluation

func ImageHeight

func ImageHeight(context map[string]any, filePathNode any) any

func ImageSize

func ImageSize(context map[string]any, filePathNode any) any

func ImageWidth

func ImageWidth(context map[string]any, filePathNode any) any

func Info

func Info(msg any)

func Intern

func Intern(s string) string

Intern returns a canonical version of the string. If the string has been interned before, the previously interned version is returned. This ensures that all occurrences of the same string value share the same memory.

This function is thread-safe and uses a read-write lock for optimal concurrent read performance.

func InternBytes

func InternBytes(b []byte) string

InternBytes interns a string created from a byte slice. This is useful when parsing to avoid creating multiple string copies from the same byte slice content.

func InternedCount

func InternedCount() int

InternedCount returns the number of interned strings. Useful for debugging and monitoring memory usage.

func IsMathParensDivision

func IsMathParensDivision(context any) bool

func IsNullOrUndefined

func IsNullOrUndefined(val any) bool

func Max

func Max(args ...interface{}) (interface{}, error)

func Merge

func Merge(obj1, obj2 map[string]any) map[string]any

func Min

func Min(args ...interface{}) (interface{}, error)

func Multiply

func Multiply(cb, cs float64) float64

func Negation

func Negation(cb, cs float64) float64

func NewImportManager

func NewImportManager(environment ImportManagerEnvironment) func(less any, context map[string]any, rootFileInfo *FileInfo) *ImportManager

func NumericCompare

func NumericCompare(a, b float64) int

NumericCompare compares two numbers

func NumericCompareStrings

func NumericCompareStrings(a, b string) int

NumericCompareStrings compares two string values numerically if possible, otherwise lexically

func Overlay

func Overlay(cb, cs float64) float64

func PutEvalToPool

func PutEvalToPool(e *Eval)

PutEvalToPool returns an *Eval to the pool. The context should not be used after calling this function.

func PutFrameSliceToPool

func PutFrameSliceToPool(s []any)

PutFrameSliceToPool returns a slice to the pool. The slice should not be used after calling this function.

func PutVariableResultMap

func PutVariableResultMap(m map[string]any)

PutVariableResultMap returns a variable result map to the pool. Callers of Ruleset.Variable() should call this when done with the result.

func RecoverableOperation

func RecoverableOperation[T any](operation func() T) (result T, err error)

RecoverableOperation runs an operation with panic recovery Returns the result and any error that occurred (including recovered panics)

func RegisterColorFunctions

func RegisterColorFunctions(registry *Registry)

RegisterColorFunctions registers all color functions with the given registry

func RegisterSvgFunctions

func RegisterSvgFunctions(registry *Registry)

RegisterSvgFunctions registers svg functions with the given registry

func RegisterTestFunctions

func RegisterTestFunctions(registry *Registry)

RegisterTestFunctions adds the custom test functions used in integration tests These functions are defined in the JavaScript test setup in less-test.js

func ReleaseCSSVisitorUtils

func ReleaseCSSVisitorUtils(u *CSSVisitorUtils)

ReleaseCSSVisitorUtils returns a CSSVisitorUtils to the pool

func ReleaseContextMap added in v0.4.0

func ReleaseContextMap(m map[string]any)

ReleaseContextMap returns a map to the pool. The map should not be used after calling this function. Pass nil safely - it will be ignored.

func ReleaseDeclaration

func ReleaseDeclaration(d *Declaration)

func ReleaseElement

func ReleaseElement(e *Element)

func ReleaseExpression

func ReleaseExpression(e *Expression)

func ReleaseExtendFinderVisitor

func ReleaseExtendFinderVisitor(v *ExtendFinderVisitor)

ReleaseExtendFinderVisitor returns an ExtendFinderVisitor to the pool

func ReleaseJoinSelectorVisitor

func ReleaseJoinSelectorVisitor(v *JoinSelectorVisitor)

ReleaseJoinSelectorVisitor returns a JoinSelectorVisitor to the pool

func ReleaseNode

func ReleaseNode(n *Node)

func ReleaseProcessExtendsVisitor

func ReleaseProcessExtendsVisitor(v *ProcessExtendsVisitor)

ReleaseProcessExtendsVisitor returns a ProcessExtendsVisitor to the pool

func ReleaseRuleset

func ReleaseRuleset(r *Ruleset)

func ReleaseSelector

func ReleaseSelector(s *Selector)

func ReleaseSetTreeVisibilityVisitor

func ReleaseSetTreeVisibilityVisitor(v *SetTreeVisibilityVisitor)

ReleaseSetTreeVisibilityVisitor returns a SetTreeVisibilityVisitor to the pool

func ReleaseToCSSVisitor

func ReleaseToCSSVisitor(v *ToCSSVisitor)

ReleaseToCSSVisitor returns a ToCSSVisitor to the pool

func ReleaseTree added in v0.4.0

func ReleaseTree(root any)

ReleaseTree recursively releases all pooled nodes in an AST tree. This should be called after ToCSS is complete and the tree is no longer needed. It uses a seen map to avoid double-releasing shared nodes.

func ReleaseUnit

func ReleaseUnit(u *Unit)

func RemoveListener

func RemoveListener(listener any)

func ResetExtendID

func ResetExtendID()

func SafeArrayAccess

func SafeArrayAccess(arr any, index int) (any, bool)

SafeArrayAccess safely accesses an array-like interface{}

func SafeEval

func SafeEval(value any, context any) any

SafeEval safely calls Eval on a value, returning the original value if eval fails

func SafeFramesAccess

func SafeFramesAccess(context any) ([]any, bool)

SafeFramesAccess safely accesses frames from context

func SafeGenCSS

func SafeGenCSS(value any, context any, output *CSSOutput)

SafeGenCSS safely calls GenCSS on a value, doing nothing if it fails

func SafeMapAccess

func SafeMapAccess[K comparable, V any](m map[K]V, key K) (V, bool)

SafeMapAccess safely accesses a map value Returns the value and true if successful, or zero value and false if key doesn't exist

func SafeNilCheck

func SafeNilCheck(value any) bool

SafeNilCheck checks if a value is nil using reflection for interface types

func SafeParseFloat

func SafeParseFloat(s string) (float64, bool)

SafeParseFloat safely parses a string to float64, returning 0 if parsing fails

func SafeSliceAccess

func SafeSliceAccess[T any](slice []T, index int) (T, bool)

SafeSliceAccess safely accesses a slice with generic type

func SafeSliceIndex

func SafeSliceIndex(slice []any, index int) (any, bool)

SafeSliceIndex safely accesses a slice at the given index Returns the value and true if successful, or nil and false if out of bounds

func SafeStringAccess

func SafeStringAccess(value any) string

SafeStringAccess safely accesses a string that might be from different sources

func SafeStringConcat

func SafeStringConcat(values ...any) string

SafeStringConcat safely concatenates strings, handling nil values

func SafeStringIndex

func SafeStringIndex(s string, index int) (byte, bool)

SafeStringIndex safely accesses a string at the given index Returns the character and true if successful, or 0 and false if out of bounds

func SafeStringSlice

func SafeStringSlice(s string, start, end int) (string, bool)

SafeStringSlice safely slices a string with bounds checking Returns the slice and true if successful, or empty string and false if out of bounds

func SafeToCSS

func SafeToCSS(value any, context any) string

SafeToCSS safely calls ToCSS on a value, returning empty string if fails

func SafeTypeAssertion

func SafeTypeAssertion[T any](value any) (T, bool)

SafeTypeAssertion safely performs a type assertion Returns the value and true if successful, or zero value and false if assertion fails

func Screen

func Screen(cb, cs float64) float64

func Self

func Self(n any) any

func SerializeVars

func SerializeVars(vars map[string]any) string

SerializeVars serializes variables from a map to Less format Go 1.21+ preserves insertion order for string keys like JavaScript objects

func SetParserLogger

func SetParserLogger(l ParserLogger)

SetParserLogger sets the global parser logger instance

func Softlight

func Softlight(cb, cs float64) float64

func SpaceSeparatedValues

func SpaceSeparatedValues(expr ...any) any

func TransformTree

func TransformTree(root any, options map[string]any) any

TransformTree transforms the root AST node using various visitors This is a direct port of the JavaScript transform-tree.js default export function

func TryParseDimensionString

func TryParseDimensionString(str string) any

TryParseDimensionString attempts to parse a string like "10px" into a *Dimension Returns nil if parsing fails

func WarmPluginCache

func WarmPluginCache(root any, bridge *NodeJSPluginBridge, evalContext any) (int, error)

WarmPluginCache collects plugin function calls from the AST and pre-warms the result cache with a batch IPC call.

Parameters:

  • root: The root AST node (typically a *Ruleset)
  • bridge: The NodeJSPluginBridge with the runtime and registered functions
  • evalContext: The evaluation context (required for variable lookup)

Returns the number of cache entries warmed and any error.

func WarmPluginCacheFromLazyBridge

func WarmPluginCacheFromLazyBridge(root any, lazyBridge *LazyNodeJSPluginBridge, evalContext any) (int, error)

WarmPluginCacheFromLazyBridge is like WarmPluginCache but takes a LazyNodeJSPluginBridge. It only warms the cache if the bridge is already initialized (i.e., plugins have been loaded).

func Warn

func Warn(msg any)

Types

type APIContext

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

func (*APIContext) GetOptions

func (ac *APIContext) GetOptions() map[string]any

func (*APIContext) Parse

func (ac *APIContext) Parse(input string, options map[string]any, callback func(error, any, any, map[string]any))

type AbstractFileManager

type AbstractFileManager struct{}

func NewAbstractFileManager

func NewAbstractFileManager() *AbstractFileManager

func (*AbstractFileManager) AlwaysMakePathsAbsolute

func (afm *AbstractFileManager) AlwaysMakePathsAbsolute() bool

func (*AbstractFileManager) ExtractURLParts

func (afm *AbstractFileManager) ExtractURLParts(url, baseURL string) (*URLParts, error)

func (*AbstractFileManager) GetPath

func (afm *AbstractFileManager) GetPath(filename string) string

func (*AbstractFileManager) IsPathAbsolute

func (afm *AbstractFileManager) IsPathAbsolute(filename string) bool

func (*AbstractFileManager) Join

func (afm *AbstractFileManager) Join(basePath, laterPath string) string

func (*AbstractFileManager) PathDiff

func (afm *AbstractFileManager) PathDiff(url, baseURL string) string

func (*AbstractFileManager) SupportsSync

func (afm *AbstractFileManager) SupportsSync() bool

func (*AbstractFileManager) TryAppendExtension

func (afm *AbstractFileManager) TryAppendExtension(path, ext string) string

func (*AbstractFileManager) TryAppendLessExtension

func (afm *AbstractFileManager) TryAppendLessExtension(path string) string

type AcceptableNode

type AcceptableNode interface {
	Accept(visitor any)
}

AcceptableNode interface for nodes that accept visitors

type AcceptorNode

type AcceptorNode interface {
	Accept(visitor any)
}

type AdditionalData

type AdditionalData struct {
	GlobalVars        map[string]any
	ModifyVars        map[string]any
	DisablePluginRule bool
	Banner            string
}

AdditionalData represents additional data that can be passed to the parser

func NewAdditionalData

func NewAdditionalData() *AdditionalData

NewAdditionalData creates a new AdditionalData with initialized maps

type Anonymous

type Anonymous struct {
	*Node
	Value       any
	Index       int
	FileInfo    map[string]any
	MapLines    bool
	RulesetLike bool
	AllowRoot   bool
}

func Escape

func Escape(str interface{}) (*Anonymous, error)

Escape URI-encodes a string and replaces specific characters (matches JS encodeURI + specific replacements)

func NewAnonymous

func NewAnonymous(value any, index int, fileInfo map[string]any, mapLines bool, rulesetLike bool, visibilityInfo map[string]any) *Anonymous

func (*Anonymous) Compare

func (a *Anonymous) Compare(other any) any

func (*Anonymous) CopyVisibilityInfo

func (a *Anonymous) CopyVisibilityInfo(info map[string]any)

func (*Anonymous) Eval

func (a *Anonymous) Eval(context any) (any, error)

func (*Anonymous) GenCSS

func (a *Anonymous) GenCSS(context any, output *CSSOutput)

func (*Anonymous) GetType

func (a *Anonymous) GetType() string

func (*Anonymous) GetTypeIndex

func (a *Anonymous) GetTypeIndex() int

func (*Anonymous) GetValue

func (a *Anonymous) GetValue() any

func (*Anonymous) IsRulesetLike

func (a *Anonymous) IsRulesetLike() bool

func (*Anonymous) IsVisible

func (a *Anonymous) IsVisible() bool

func (*Anonymous) Operate

func (a *Anonymous) Operate(context any, op string, other any) any

Operate allows Anonymous values (like variables @z: 11) to participate in math expressions

func (*Anonymous) ToCSS

func (a *Anonymous) ToCSS(context any) string

type ArrayLikeNode

type ArrayLikeNode interface {
	Len() int
	Get(i int) any
}

ArrayLikeNode represents nodes that behave like arrays (have splice method)

type Assignment

type Assignment struct {
	*Node
	Key   any
	Value any
}

func NewAssignment

func NewAssignment(key, value any) *Assignment

func (*Assignment) Accept

func (a *Assignment) Accept(visitor any)

func (*Assignment) Eval

func (a *Assignment) Eval(context any) (any, error)

func (*Assignment) GenCSS

func (a *Assignment) GenCSS(context any, output *CSSOutput)

func (*Assignment) GetType

func (a *Assignment) GetType() string

func (*Assignment) Type

func (a *Assignment) Type() string

type AtRule

type AtRule struct {
	*Node
	Name         string
	Value        any
	Rules        []any
	Declarations []any // Used for simple blocks (like @starting-style with only declarations)
	SimpleBlock  bool  // True when at-rule contains only declarations (CSS native nesting)
	IsRooted     bool
	AllowRoot    bool
	DebugInfo    any
	AllExtends   []*Extend // For storing extends found by ExtendFinderVisitor
}

func NewAtRule

func NewAtRule(name string, value any, rules any, index int, currentFileInfo map[string]any, debugInfo any, isRooted bool, visibilityInfo map[string]any) *AtRule

func (*AtRule) Accept

func (a *AtRule) Accept(visitor any)

func (*AtRule) BubbleSelectors

func (a *AtRule) BubbleSelectors(selectors any)

func (*AtRule) Eval

func (a *AtRule) Eval(context any) (any, error)

func (*AtRule) EvalNested

func (a *AtRule) EvalNested(context any) any

func (*AtRule) EvalTop

func (a *AtRule) EvalTop(context any) any

func (*AtRule) Find

func (a *AtRule) Find(selector any, self any, filter func(any) bool) []any

func (*AtRule) GenCSS

func (a *AtRule) GenCSS(context any, output *CSSOutput)

func (*AtRule) GetAllExtends

func (a *AtRule) GetAllExtends() []*Extend

func (*AtRule) GetDebugInfo

func (a *AtRule) GetDebugInfo() any

func (*AtRule) GetIsRooted

func (a *AtRule) GetIsRooted() bool

func (*AtRule) GetName

func (a *AtRule) GetName() string

func (*AtRule) GetRules

func (a *AtRule) GetRules() []any

func (*AtRule) GetType

func (a *AtRule) GetType() string

func (*AtRule) IsCharset

func (a *AtRule) IsCharset() bool

func (*AtRule) IsRulesetLike

func (a *AtRule) IsRulesetLike() any

func (*AtRule) OutputRuleset

func (a *AtRule) OutputRuleset(context any, output *CSSOutput, rules []any)

func (*AtRule) Permute

func (a *AtRule) Permute(arr []any) any

func (*AtRule) Rulesets

func (a *AtRule) Rulesets() []any

func (*AtRule) SetAllExtends

func (a *AtRule) SetAllExtends(extends []*Extend)

func (*AtRule) SetRules

func (a *AtRule) SetRules(rules []any)

func (*AtRule) ToCSS

func (a *AtRule) ToCSS(context any) string

func (*AtRule) Type

func (a *AtRule) Type() string

func (*AtRule) Variable

func (a *AtRule) Variable(name string) any

type AtRuleRule

type AtRuleRule interface {
	SetRoot(value any)
}

type Attribute

type Attribute struct {
	*Node
	Key   any
	Op    string
	Value any
	Cif   string
}

func NewAttribute

func NewAttribute(key any, op string, value any, cif string) *Attribute

func (*Attribute) Eval

func (a *Attribute) Eval(context any) (any, error)

func (*Attribute) GenCSS

func (a *Attribute) GenCSS(context any, output *CSSOutput)

func (*Attribute) GetType

func (a *Attribute) GetType() string

func (*Attribute) ToCSS

func (a *Attribute) ToCSS(context any) string

func (*Attribute) Type

func (a *Attribute) Type() string

type BaseURLParseError

type BaseURLParseError struct {
	BaseURL string
}

func (*BaseURLParseError) Error

func (e *BaseURLParseError) Error() string

type BlendMode

type BlendMode func(cb, cs float64) float64

type CSSGenerator

type CSSGenerator interface {
	GenCSS(context any, output *CSSOutput)
}

CSSGenerator interface for nodes that can generate CSS

type CSSOutput

type CSSOutput struct {
	Add     func(any, any, any)
	IsEmpty func() bool
}

CSSOutput represents the output structure for CSS generation

type CSSVisitorUtils

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

CSSVisitorUtils provides utility functions for CSS visitor

func GetCSSVisitorUtils

func GetCSSVisitorUtils(context any) *CSSVisitorUtils

GetCSSVisitorUtils retrieves a CSSVisitorUtils from the pool

func NewCSSVisitorUtils

func NewCSSVisitorUtils(context any) *CSSVisitorUtils

NewCSSVisitorUtils creates a new CSSVisitorUtils instance

func (*CSSVisitorUtils) ContainsSilentNonBlockedChild

func (u *CSSVisitorUtils) ContainsSilentNonBlockedChild(bodyRules []any) bool

ContainsSilentNonBlockedChild checks if body rules contain silent non-blocked children

func (*CSSVisitorUtils) HasVisibleSelector

func (u *CSSVisitorUtils) HasVisibleSelector(rulesetNode any) bool

HasVisibleSelector checks if ruleset node has visible selectors

func (*CSSVisitorUtils) IsEmpty

func (u *CSSVisitorUtils) IsEmpty(owner any) bool

IsEmpty checks if owner is empty

func (*CSSVisitorUtils) IsVisibleRuleset

func (u *CSSVisitorUtils) IsVisibleRuleset(rulesetNode any) bool

IsVisibleRuleset checks if a ruleset is visible

func (*CSSVisitorUtils) KeepOnlyVisibleChilds

func (u *CSSVisitorUtils) KeepOnlyVisibleChilds(owner any)

KeepOnlyVisibleChilds filters out invisible children from owner

func (*CSSVisitorUtils) Reset

func (u *CSSVisitorUtils) Reset(context any)

Reset resets the CSSVisitorUtils for reuse from the pool. The visitor's methodLookup map is preserved (it's expensive to rebuild).

func (*CSSVisitorUtils) ResolveVisibility

func (u *CSSVisitorUtils) ResolveVisibility(node any) any

ResolveVisibility resolves visibility for a node

func (*CSSVisitorUtils) ResolveVisibilityMedia

func (u *CSSVisitorUtils) ResolveVisibilityMedia(node any) any

ResolveVisibilityMedia resolves visibility for Media nodes. Media nodes are special because VisitRuleset extracts nested rulesets and places them as direct children of Media (m.Rules[1...]), not as grandchildren through the wrapper ruleset (m.Rules[0]). This function filters all direct children of Media, not just m.Rules[0].Rules.

type CSSable

type CSSable interface {
	ToCSS(any) string
}

type Call

type Call struct {
	*Node
	Name string
	Args []any
	Calc bool

	CallerFactory FunctionCallerFactory // Factory for creating FunctionCaller instances
	// contains filtered or unexported fields
}

func NewCall

func NewCall(name string, args []any, index int, currentFileInfo map[string]any) *Call

func (*Call) Accept

func (c *Call) Accept(visitor any)

func (*Call) Eval

func (c *Call) Eval(context any) (any, error)

func (*Call) FileInfo

func (c *Call) FileInfo() map[string]any

func (*Call) GenCSS

func (c *Call) GenCSS(context any, output *CSSOutput)

func (*Call) GetIndex

func (c *Call) GetIndex() int

func (*Call) GetName

func (c *Call) GetName() string

func (*Call) GetType

func (c *Call) GetType() string

type CallbackFunc

type CallbackFunc func(error, any)

CallbackFunc represents a callback function that receives an error and result

type Color

type Color struct {
	*Node
	RGB   []float64
	Alpha float64
	Value string
}

func ColorBlend

func ColorBlend(mode BlendMode, color1, color2 *Color) *Color

func ColorBlendAverage

func ColorBlendAverage(color1, color2 *Color) *Color

func ColorBlendDifference

func ColorBlendDifference(color1, color2 *Color) *Color

func ColorBlendExclusion

func ColorBlendExclusion(color1, color2 *Color) *Color

func ColorBlendHardlight

func ColorBlendHardlight(color1, color2 *Color) *Color

func ColorBlendMultiply

func ColorBlendMultiply(color1, color2 *Color) *Color

func ColorBlendNegation

func ColorBlendNegation(color1, color2 *Color) *Color

func ColorBlendOverlay

func ColorBlendOverlay(color1, color2 *Color) *Color

func ColorBlendScreen

func ColorBlendScreen(color1, color2 *Color) *Color

func ColorBlendSoftlight

func ColorBlendSoftlight(color1, color2 *Color) *Color

func FromKeyword

func FromKeyword(keyword string) *Color

func NewColor

func NewColor(rgb any, alpha float64, originalForm string) *Color

func (*Color) Compare

func (c *Color) Compare(other *Color) int

func (*Color) Eval

func (c *Color) Eval(context any) any

func (*Color) GenCSS

func (c *Color) GenCSS(context any, output *CSSOutput)

func (*Color) GetAllowRoot

func (c *Color) GetAllowRoot() bool

func (*Color) GetAlpha

func (c *Color) GetAlpha() float64

func (*Color) GetColorValue

func (c *Color) GetColorValue() string

func (*Color) GetRGB

func (c *Color) GetRGB() []float64

func (*Color) GetType

func (c *Color) GetType() string

func (*Color) Luma

func (c *Color) Luma() float64

func (*Color) OperateColor

func (c *Color) OperateColor(context any, op string, other *Color) *Color

func (*Color) ToARGB

func (c *Color) ToARGB() string

func (*Color) ToCSS

func (c *Color) ToCSS(context any) string

func (*Color) ToHSL

func (c *Color) ToHSL() HSL

func (*Color) ToHSV

func (c *Color) ToHSV() HSV

func (*Color) ToRGB

func (c *Color) ToRGB() string

type ColorFunctionDefinition

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

ColorFunctionDefinition wraps a color function to implement FunctionDefinition

func (*ColorFunctionDefinition) Call

func (c *ColorFunctionDefinition) Call(args ...any) (any, error)

func (*ColorFunctionDefinition) CallCtx

func (c *ColorFunctionDefinition) CallCtx(ctx *Context, args ...any) (any, error)

func (*ColorFunctionDefinition) NeedsEvalArgs

func (c *ColorFunctionDefinition) NeedsEvalArgs() bool

type ColorFunctionWrapper

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

ColorFunctionWrapper wraps color functions to implement FunctionDefinition

func (*ColorFunctionWrapper) Call

func (w *ColorFunctionWrapper) Call(args ...any) (any, error)

func (*ColorFunctionWrapper) CallCtx

func (w *ColorFunctionWrapper) CallCtx(ctx *Context, args ...any) (any, error)

func (*ColorFunctionWrapper) NeedsEvalArgs

func (w *ColorFunctionWrapper) NeedsEvalArgs() bool

type Combinator

type Combinator struct {
	*Node
	Value             string
	EmptyOrWhitespace bool
}

func NewCombinator

func NewCombinator(value string) *Combinator

func (*Combinator) GenCSS

func (c *Combinator) GenCSS(context any, output *CSSOutput)

func (*Combinator) GetType

func (c *Combinator) GetType() string

func (*Combinator) Type

func (c *Combinator) Type() string

type Comment

type Comment struct {
	*Node
	Value         string
	IsLineComment bool
	AllowRoot     bool
	DebugInfo     map[string]any
}

func NewComment

func NewComment(value string, isLineComment bool, index int, currentFileInfo map[string]any) *Comment

func (*Comment) Accept

func (c *Comment) Accept(visitor any)

func (*Comment) Eval

func (c *Comment) Eval(context any) any

func (*Comment) GenCSS

func (c *Comment) GenCSS(context any, output *CSSOutput)

func (*Comment) GetDebugInfo

func (c *Comment) GetDebugInfo() map[string]any

func (*Comment) GetType

func (c *Comment) GetType() string

func (*Comment) IsSilent

func (c *Comment) IsSilent(context any) bool

func (*Comment) IsVisible

func (c *Comment) IsVisible() bool

func (*Comment) SetParent

func (c *Comment) SetParent(node any, parent *Node)

type Compareable

type Compareable interface {
	Compare(*Node) int
}

Compareable interface defines the Compare method

type CompileOptions

type CompileOptions struct {
	// Paths are additional include paths for @import resolution
	Paths []string

	// Filename is the name of the file being compiled (used for error messages and source maps)
	Filename string

	// Compress enables CSS minification
	Compress bool

	// StrictUnits controls unit checking for math operations
	StrictUnits bool

	// Math controls how math operations are evaluated
	// Use Math.Always, Math.ParensDivision, or Math.Parens
	Math MathType

	// RewriteUrls controls URL rewriting behavior
	RewriteUrls RewriteUrlsType

	// Rootpath is the base path for URL rewriting
	Rootpath string

	// UrlArgs is a query string to append to URLs
	UrlArgs string

	// EnableJavaScriptPlugins enables support for JavaScript plugins via Node.js
	// When true, the compiler will start a Node.js runtime to handle @plugin directives
	EnableJavaScriptPlugins bool

	// JavascriptEnabled enables inline JavaScript evaluation in LESS files
	// When true, `expression` syntax can be used for JavaScript expressions
	// Note: This also requires EnableJavaScriptPlugins to be true for the runtime
	JavascriptEnabled bool

	// Plugins specifies plugins to load before compilation
	// When plugins are specified, EnableJavaScriptPlugins is automatically enabled
	Plugins []PluginSpec

	// GlobalVars are variables to inject before compilation
	GlobalVars map[string]any

	// ModifyVars are variables to inject after compilation (override existing variables)
	ModifyVars map[string]any

	// SourceMap enables source map generation
	SourceMap bool

	// SourceMapOptions contains detailed source map configuration
	SourceMapOptions *SourceMapOptions
}

type CompileResult

type CompileResult struct {
	CSS     string   `json:"css"`
	Map     string   `json:"map,omitempty"`
	Imports []string `json:"imports,omitempty"`
}

func Compile

func Compile(input string, options *CompileOptions) (*CompileResult, error)

Compile compiles LESS source code to CSS. This is the main entry point for the less.go compiler.

When EnableJavaScriptPlugins is true, the function will: - Create a lazy Node.js runtime that only starts if @plugin directives are encountered - Properly shut down the Node.js process when compilation completes

Example usage:

result, err := less_go.Compile(lessSource, &less_go.CompileOptions{
    Filename: "styles.less",
    Compress: true,
    EnableJavaScriptPlugins: true,
})
if err != nil {
    log.Fatal(err)
}
fmt.Println(result.CSS)

func CompileFile

func CompileFile(filename string, options *CompileOptions) (*CompileResult, error)

CompileFile compiles a LESS file to CSS. This reads the file and compiles it with appropriate options set for file-based compilation.

Example usage:

result, err := less_go.CompileFile("styles.less", &less_go.CompileOptions{
    Compress: true,
    EnableJavaScriptPlugins: true,
})

type ConcretePromise

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

func NewPromise

func NewPromise() *ConcretePromise

func (*ConcretePromise) Reject

func (p *ConcretePromise) Reject(err error)

func (*ConcretePromise) Resolve

func (p *ConcretePromise) Resolve(file *LoadedFile)

func (*ConcretePromise) Then

func (p *ConcretePromise) Then(onSuccess func(*LoadedFile), onError func(error))

type Condition

type Condition struct {
	*Node
	Op     string
	Lvalue any
	Rvalue any
	Index  int
	Negate bool
}

func NewCondition

func NewCondition(op string, l, r any, i int, negate bool) *Condition

func (*Condition) Accept

func (c *Condition) Accept(visitor any)

func (*Condition) Eval

func (c *Condition) Eval(context any) any

func (*Condition) EvalBool

func (c *Condition) EvalBool(context any) bool

func (*Condition) GetType

func (c *Condition) GetType() string

type Container

type Container struct {
	*AtRule
	Features *Value
	Rules    []any
}

func NewContainer

func NewContainer(value any, features any, index int, currentFileInfo map[string]any, visibilityInfo map[string]any) (*Container, error)

func (*Container) Accept

func (c *Container) Accept(visitor any)

Accept must be overridden because Container.Rules shadows AtRule.Rules

func (*Container) BubbleSelectors

func (c *Container) BubbleSelectors(selectors any)

func (*Container) Eval

func (c *Container) Eval(context any) (any, error)

func (*Container) EvalNested

func (c *Container) EvalNested(context any) any

func (*Container) EvalTop

func (c *Container) EvalTop(context any) any

func (*Container) GenCSS

func (c *Container) GenCSS(context any, output *CSSOutput)

func (*Container) GetRules

func (c *Container) GetRules() []any

func (*Container) GetType

func (c *Container) GetType() string

func (*Container) GetTypeIndex

func (c *Container) GetTypeIndex() int

func (*Container) Permute

func (c *Container) Permute(arr []any) any

func (*Container) Type

func (c *Container) Type() string

type ContainerSyntaxOptions

type ContainerSyntaxOptions struct {
	QueryInParens bool
}

type ContainerSyntaxOptionsType

type ContainerSyntaxOptionsType struct {
	QueryInParens bool
}

type Context

type Context struct {
	Frames []*Frame
}

Context represents the evaluation context. This is a simplified representation; more fields might be needed.

func (*Context) GetFrames

func (c *Context) GetFrames() []ParserFrame

GetFrames implements the interface expected by Variable.Eval It delegates to the underlying EvalContext if available

type ContextInterface

type ContextInterface interface {
	Parse(string, map[string]any, func(error, any, any, map[string]any))
	GetOptions() map[string]any
}

ContextInterface represents the context that the render function operates on This matches JavaScript's 'this' object that has parse method and options property

type DataURIFunctionWrapper

type DataURIFunctionWrapper struct{}

func (*DataURIFunctionWrapper) Call

func (w *DataURIFunctionWrapper) Call(args ...any) (any, error)

func (*DataURIFunctionWrapper) CallCtx

func (w *DataURIFunctionWrapper) CallCtx(ctx *Context, args ...any) (any, error)

func (*DataURIFunctionWrapper) NeedsEvalArgs

func (w *DataURIFunctionWrapper) NeedsEvalArgs() bool

type Declaration

type Declaration struct {
	*Node

	Value *Value
	// contains filtered or unexported fields
}

func GetDeclarationFromPool

func GetDeclarationFromPool() *Declaration

func NewDeclaration

func NewDeclaration(name any, value any, important any, merge any, index int, fileInfo map[string]any, inline bool, variable any) (*Declaration, error)

Uses sync.Pool to reuse Declaration objects.

func (*Declaration) Accept

func (d *Declaration) Accept(visitor any)

func (*Declaration) Eval

func (d *Declaration) Eval(context any) (any, error)

func (*Declaration) GenCSS

func (d *Declaration) GenCSS(context any, output *CSSOutput)

func (*Declaration) GenCSSSourceMap added in v0.1.4

func (d *Declaration) GenCSSSourceMap(context map[string]any, output *SourceMapOutput)

GenCSSSourceMap implements the SourceMapNode interface

func (*Declaration) GetImportant

func (d *Declaration) GetImportant() bool

func (*Declaration) GetMerge

func (d *Declaration) GetMerge() any

func (*Declaration) GetName

func (d *Declaration) GetName() string

func (*Declaration) GetType

func (d *Declaration) GetType() string

func (*Declaration) GetTypeIndex

func (d *Declaration) GetTypeIndex() int

func (*Declaration) GetValue

func (d *Declaration) GetValue() any

func (*Declaration) GetVariable

func (d *Declaration) GetVariable() bool

func (*Declaration) MakeImportant

func (d *Declaration) MakeImportant() any

func (*Declaration) MergeType

func (d *Declaration) MergeType() string

func (*Declaration) Release

func (d *Declaration) Release()

func (*Declaration) SetImportant

func (d *Declaration) SetImportant(important bool)

func (*Declaration) SetValue

func (d *Declaration) SetValue(value any)

func (*Declaration) ToCSS

func (d *Declaration) ToCSS(context any) string

type DefaultFunc

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

func NewDefaultFunc

func NewDefaultFunc() *DefaultFunc

func (*DefaultFunc) Error

func (d *DefaultFunc) Error(e any)

func (*DefaultFunc) Eval

func (d *DefaultFunc) Eval() any

func (*DefaultFunc) Reset

func (d *DefaultFunc) Reset()

func (*DefaultFunc) Value

func (d *DefaultFunc) Value(v any)

type DefaultFunctionCallerFactory

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

func NewDefaultFunctionCallerFactory

func NewDefaultFunctionCallerFactory(registry *Registry) *DefaultFunctionCallerFactory

func (*DefaultFunctionCallerFactory) NewFunctionCaller

func (f *DefaultFunctionCallerFactory) NewFunctionCaller(name string, context EvalContext, index int, fileInfo map[string]any) (ParserFunctionCaller, error)

type DefaultFunctionDefinition

type DefaultFunctionDefinition struct {
}

DefaultFunctionDefinition implements the default() function for mixin guards

func (*DefaultFunctionDefinition) Call

func (d *DefaultFunctionDefinition) Call(args ...any) (any, error)

Call implements the default() function

func (*DefaultFunctionDefinition) CallCtx

func (d *DefaultFunctionDefinition) CallCtx(ctx *Context, args ...any) (any, error)

CallCtx implements the default() function with context

func (*DefaultFunctionDefinition) NeedsEvalArgs

func (d *DefaultFunctionDefinition) NeedsEvalArgs() bool

NeedsEvalArgs returns false since default() takes no arguments

type DefaultFunctions

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

DefaultFunctions provides a basic implementation of Functions

func (*DefaultFunctions) GetFunctionRegistry

func (d *DefaultFunctions) GetFunctionRegistry() any

type DefaultParserFunctionCaller

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

func (*DefaultParserFunctionCaller) Call

func (c *DefaultParserFunctionCaller) Call(args []any) (any, error)

func (*DefaultParserFunctionCaller) IsValid

func (c *DefaultParserFunctionCaller) IsValid() bool

type DefaultPluginLoader

type DefaultPluginLoader struct{}

DefaultPluginLoader provides a basic implementation of PluginLoader

func (*DefaultPluginLoader) EvalPlugin

func (d *DefaultPluginLoader) EvalPlugin(contents string, newEnv *Parse, importManager any, pluginArgs map[string]any, newFileInfo any) any

func (*DefaultPluginLoader) LoadPlugin

func (d *DefaultPluginLoader) LoadPlugin(path, currentDirectory string, context map[string]any, environment any, fileManager any) any

func (*DefaultPluginLoader) LoadPluginSync

func (d *DefaultPluginLoader) LoadPluginSync(path, currentDirectory string, context map[string]any, environment any, fileManager any) any

type DeferredPluginInfo

type DeferredPluginInfo struct {
	Path             string
	CurrentDirectory string
	PluginArgs       map[string]any
	FullPath         string
}

DeferredPluginInfo holds information for loading plugins at the correct scope depth during evaluation rather than globally during import.

type DetachedRuleset

type DetachedRuleset struct {
	*Node
	// contains filtered or unexported fields
}

func NewDetachedRuleset

func NewDetachedRuleset(ruleset any, frames []any) *DetachedRuleset

func (*DetachedRuleset) Accept

func (dr *DetachedRuleset) Accept(visitor any)

func (*DetachedRuleset) CallEval

func (dr *DetachedRuleset) CallEval(context any) any

func (*DetachedRuleset) Eval

func (dr *DetachedRuleset) Eval(context any) any

func (*DetachedRuleset) EvalFirst

func (dr *DetachedRuleset) EvalFirst() bool

func (*DetachedRuleset) GetRuleset

func (dr *DetachedRuleset) GetRuleset() any

func (*DetachedRuleset) GetType

func (dr *DetachedRuleset) GetType() string

func (*DetachedRuleset) GetTypeIndex

func (dr *DetachedRuleset) GetTypeIndex() int

func (*DetachedRuleset) HasRuleset

func (dr *DetachedRuleset) HasRuleset() bool

func (*DetachedRuleset) Type

func (dr *DetachedRuleset) Type() string

type Dimension

type Dimension struct {
	*Node
	Value float64
	Unit  *Unit
}

func Abs

func Abs(n *Dimension) (*Dimension, error)

func Acos

func Acos(n *Dimension) (*Dimension, error)

func Asin

func Asin(n *Dimension) (*Dimension, error)

func Atan

func Atan(n *Dimension) (*Dimension, error)

func Ceil

func Ceil(n *Dimension) (*Dimension, error)

func Convert

func Convert(val *Dimension, unit *Dimension) (*Dimension, error)

func Cos

func Cos(n *Dimension) (*Dimension, error)

func Floor

func Floor(n *Dimension) (*Dimension, error)

func Length

func Length(values any) *Dimension

func MathHelper

func MathHelper(fn func(float64) float64, unit *Unit, n any) (*Dimension, error)

MathHelper applies a mathematical function to a dimension value. If unit is nil, uses the dimension's unit; otherwise unifies and uses the provided unit.

func Mod

func Mod(a *Dimension, b *Dimension) (*Dimension, error)

func NewDimension

func NewDimension(value any, unit any) (*Dimension, error)

func NewDimensionFrom

func NewDimensionFrom(value float64, unit *Unit) *Dimension

Returns nil if the value is NaN.

func Percentage

func Percentage(n *Dimension) (*Dimension, error)

func Pi

func Pi() (*Dimension, error)

func Pow

func Pow(x interface{}, y interface{}) (*Dimension, error)

func Round

func Round(n *Dimension, f *Dimension) (*Dimension, error)

func Sin

func Sin(n *Dimension) (*Dimension, error)

func Sqrt

func Sqrt(n *Dimension) (*Dimension, error)

func Tan

func Tan(n *Dimension) (*Dimension, error)

func (*Dimension) Accept

func (d *Dimension) Accept(visitor any)

func (*Dimension) Compare

func (d *Dimension) Compare(other any) *int

func (*Dimension) ConvertTo

func (d *Dimension) ConvertTo(conversions any) *Dimension

func (*Dimension) Eval

func (d *Dimension) Eval(context any) (any, error)

func (*Dimension) GenCSS

func (d *Dimension) GenCSS(context any, output *CSSOutput)

func (*Dimension) GetType

func (d *Dimension) GetType() string

func (*Dimension) GetUnit

func (d *Dimension) GetUnit() any

func (*Dimension) GetValue

func (d *Dimension) GetValue() float64

func (*Dimension) Operate

func (d *Dimension) Operate(context any, op string, other *Dimension) *Dimension

func (*Dimension) OperateArithmetic

func (d *Dimension) OperateArithmetic(context any, op string, a, b float64) float64

func (*Dimension) ToCSS

func (d *Dimension) ToCSS(context any) string

func (*Dimension) ToColor

func (d *Dimension) ToColor() *Color

func (*Dimension) Unify

func (d *Dimension) Unify() *Dimension

type DirectDispatchVisitor

type DirectDispatchVisitor interface {
	VisitNode(node any, visitArgs *VisitArgs) (result any, handled bool)
	VisitNodeOut(node any) bool
}

DirectDispatchVisitor interface for direct dispatch without reflection Implementations can optionally implement this for better performance

type EachFunctionDef

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

func (*EachFunctionDef) Call

func (e *EachFunctionDef) Call(args ...any) (any, error)

func (*EachFunctionDef) CallCtx

func (e *EachFunctionDef) CallCtx(ctx *Context, args ...any) (any, error)

func (*EachFunctionDef) NeedsEvalArgs

func (e *EachFunctionDef) NeedsEvalArgs() bool

type Element

type Element struct {
	*Node
	Combinator *Combinator
	Value      any
	IsVariable bool
}

func GetElementFromPool

func GetElementFromPool() *Element

func NewElement

func NewElement(combinator any, value any, isVariable bool, index int, currentFileInfo map[string]any, visibilityInfo map[string]any) *Element

func (*Element) Accept

func (e *Element) Accept(visitor any)

func (*Element) Clone

func (e *Element) Clone() *Element

func (*Element) Eval

func (e *Element) Eval(context any) (any, error)

func (*Element) GenCSS

func (e *Element) GenCSS(context any, output *CSSOutput)

func (*Element) GetType

func (e *Element) GetType() string

func (*Element) Release

func (e *Element) Release()

func (*Element) ToCSS

func (e *Element) ToCSS(context any) string

func (*Element) Type

func (e *Element) Type() string

type EndState

type EndState struct {
	IsFinished                   bool
	Furthest                     int
	FurthestPossibleErrorMessage string
	FurthestReachedEnd           bool
	FurthestChar                 byte
}

type EntityParsers

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

EntityParsers contains entity-related parsing methods

func (*EntityParsers) Arguments

func (e *EntityParsers) Arguments(prevArgs []any) []any

Arguments parses function arguments

func (*EntityParsers) Assignment

func (e *EntityParsers) Assignment() any

Assignment parses assignments

func (*EntityParsers) Call

func (e *EntityParsers) Call() any

Call parses function calls - rgb(255, 0, 255)

func (*EntityParsers) Color

func (e *EntityParsers) Color() any

Color parses hexadecimal colors - #4F3C2F

func (*EntityParsers) ColorKeyword

func (e *EntityParsers) ColorKeyword() any

ColorKeyword parses color keywords

func (*EntityParsers) CustomFuncCall

func (e *EntityParsers) CustomFuncCall(name string) map[string]any

CustomFuncCall handles custom function calls

func (*EntityParsers) DeclarationCall

func (e *EntityParsers) DeclarationCall() any

DeclarationCall parses declaration-like function calls This is used in media features where we can have syntax like: supports(display: grid)

func (*EntityParsers) Dimension

func (e *EntityParsers) Dimension() any

Dimension parses dimensions (numbers with units) - 0.5em 95%

func (*EntityParsers) JavaScript

func (e *EntityParsers) JavaScript() any

JavaScript parses JavaScript evaluation - `window.location.href`

func (*EntityParsers) Keyword

func (e *EntityParsers) Keyword() any

Keyword parses keywords - black border-collapse

func (*EntityParsers) Literal

func (e *EntityParsers) Literal() any

Literal parses literal entities

func (*EntityParsers) MixinLookup

func (e *EntityParsers) MixinLookup() any

MixinLookup parses mixin lookups

func (*EntityParsers) Property

func (e *EntityParsers) Property() any

Property parses property accessors - $color

func (*EntityParsers) PropertyCurly

func (e *EntityParsers) PropertyCurly() any

PropertyCurly parses property entity using protective {} e.g. ${prop}

func (*EntityParsers) Quoted

func (e *EntityParsers) Quoted(forceEscaped bool) any

Quoted parses quoted strings - "milky way" 'he\'s the one!'

func (*EntityParsers) URL

func (e *EntityParsers) URL() any

URL parses url() tokens

func (*EntityParsers) UnicodeDescriptor

func (e *EntityParsers) UnicodeDescriptor() any

UnicodeDescriptor parses unicode descriptors - U+0?? or U+00A1-00A9

func (*EntityParsers) Variable

func (e *EntityParsers) Variable() any

Variable parses variable entities - @fink

func (*EntityParsers) VariableCurly

func (e *EntityParsers) VariableCurly() any

VariableCurly parses variable entity using protective {} e.g. @{var}

type EnvironmentEnvironment

type EnvironmentEnvironment struct {
	FileManagers          []EnvironmentFileManager
	EncodeBase64          func() string
	MimeLookup            func() string
	CharsetLookup         func() string
	GetSourceMapGenerator func() any
	// contains filtered or unexported fields
}

func NewEnvironment

func NewEnvironment(externalEnvironment map[string]any, fileManagers []EnvironmentFileManager) *EnvironmentEnvironment

func (*EnvironmentEnvironment) AddFileManager

func (e *EnvironmentEnvironment) AddFileManager(fileManager EnvironmentFileManager)

func (*EnvironmentEnvironment) ClearFileManagers

func (e *EnvironmentEnvironment) ClearFileManagers()

func (*EnvironmentEnvironment) GetFileManager

func (e *EnvironmentEnvironment) GetFileManager(filename string, currentDirectory *string, options map[string]any, environment map[string]any, isSync bool) EnvironmentFileManager

type EnvironmentFileManager

type EnvironmentFileManager interface {
	Supports(filename, currentDirectory string, options map[string]any, environment map[string]any) bool
	SupportsSync(filename, currentDirectory string, options map[string]any, environment map[string]any) bool
}

type EnvironmentPluginManager

type EnvironmentPluginManager interface {
	GetFileManagers() []EnvironmentFileManager
}

type ErrorDetails

type ErrorDetails struct {
	Message  string
	Stack    string
	Filename string
	Index    any // Can be int or nil
	Call     any // Can be int or nil
	Type     string
}

type Eval

type Eval struct {
	Paths             []string
	Compress          bool
	Math              MathType
	StrictUnits       bool
	SourceMap         bool
	ImportMultiple    bool
	UrlArgs           string
	JavascriptEnabled bool
	PluginManager     any
	ImportantScope    []ImportantScopeEntry // Typed struct replaces []map[string]any
	RewriteUrls       RewriteUrlsType
	NumPrecision      int

	Frames []any

	CalcStack        []bool
	ParensStack      []bool
	InCalc           bool
	MathOn           bool
	DefaultFunc      *DefaultFunc
	FunctionRegistry *Registry
	MediaBlocks      []any
	MediaPath        []any

	PluginBridge     *NodeJSPluginBridge
	LazyPluginBridge *LazyNodeJSPluginBridge // Lazy bridge for deferred initialization
	// contains filtered or unexported fields
}

Eval is the primary evaluation context for Less compilation. OPTIMIZATION: Uses typed fields instead of map[string]any to eliminate reflection overhead.

func GetEvalFromPool

func GetEvalFromPool(source *Eval, frames []any) *Eval

GetEvalFromPool gets an *Eval from the pool and initializes it from a source context. The returned context should be returned via PutEvalToPool when done.

func NewEval

func NewEval(options map[string]any, frames []any) *Eval

func NewEvalFromEval

func NewEvalFromEval(parent *Eval, frames []any) *Eval

func (*Eval) CallPluginFunction

func (e *Eval) CallPluginFunction(name string, args ...any) (any, error)

func (*Eval) CopyEvalToMap

func (e *Eval) CopyEvalToMap(target map[string]any, includeMediaContext bool)

func (*Eval) CopyWithFrames

func (e *Eval) CopyWithFrames(frames []any) *Eval

CopyWithFrames creates a shallow copy of the Eval context with new frames. OPTIMIZATION: This is more efficient than CopyEvalToMap for internal use.

func (*Eval) EnterCalc

func (e *Eval) EnterCalc()

func (*Eval) EnterPluginScope

func (e *Eval) EnterPluginScope() any

func (*Eval) ExitCalc

func (e *Eval) ExitCalc()

func (*Eval) ExitPluginScope

func (e *Eval) ExitPluginScope()

func (*Eval) GetDefaultFunc

func (e *Eval) GetDefaultFunc() *DefaultFunc

func (*Eval) GetFrames

func (e *Eval) GetFrames() []ParserFrame

func (*Eval) GetFramesAny

func (e *Eval) GetFramesAny() []any

func (*Eval) GetImportantFromCurrentScope

func (e *Eval) GetImportantFromCurrentScope() string

GetImportantFromCurrentScope gets the important value from the current scope.

func (*Eval) GetImportantScope

func (e *Eval) GetImportantScope() []map[string]bool

func (*Eval) GetImportantScopeAny

func (e *Eval) GetImportantScopeAny() []map[string]any

GetImportantScopeAny converts ImportantScope to []map[string]any for backward compatibility. OPTIMIZATION: This is only called when converting to map contexts; direct struct access is preferred.

func (*Eval) HasPluginFunction

func (e *Eval) HasPluginFunction(name string) bool

func (*Eval) InParenthesis

func (e *Eval) InParenthesis()

func (*Eval) IsInCalc

func (e *Eval) IsInCalc() bool

func (*Eval) IsMathOn

func (e *Eval) IsMathOn() bool

func (*Eval) IsMathOnWithOp

func (e *Eval) IsMathOnWithOp(op string) bool

func (*Eval) LookupPluginFunction

func (e *Eval) LookupPluginFunction(name string) (any, bool)

func (*Eval) NewMixinEvalContext

func (e *Eval) NewMixinEvalContext(frames []any) *Eval

NewMixinEvalContext creates a new *Eval context for mixin evaluation. OPTIMIZATION: Directly creates *Eval instead of map[string]any, avoiding reflection. The new context shares the parent's configuration but has new frames and fresh media context.

func (*Eval) NormalizePath

func (e *Eval) NormalizePath(path string) string

func (*Eval) OutOfParenthesis

func (e *Eval) OutOfParenthesis()

func (*Eval) PathRequiresRewrite

func (e *Eval) PathRequiresRewrite(path string) bool

func (*Eval) PopImportantScope

func (e *Eval) PopImportantScope() ImportantScopeEntry

PopImportantScope removes the top scope entry from the important scope stack.

func (*Eval) PushImportantScope

func (e *Eval) PushImportantScope()

PushImportantScope adds a new empty scope entry to the important scope stack. OPTIMIZATION: Direct struct manipulation instead of map allocation.

func (*Eval) RewritePath

func (e *Eval) RewritePath(path, rootpath string) string

func (*Eval) RewritePathForImport

func (e *Eval) RewritePathForImport(path, rootpath string) string

func (*Eval) SetImportantInCurrentScope

func (e *Eval) SetImportantInCurrentScope(important string)

SetImportantInCurrentScope sets the important value in the current scope.

func (*Eval) SetMathOn

func (e *Eval) SetMathOn(mathOn bool)

func (*Eval) ToMap

func (e *Eval) ToMap() map[string]any

type EvalContext

type EvalContext interface {
	IsMathOn() bool
	SetMathOn(bool)
	IsInCalc() bool
	EnterCalc()
	ExitCalc()
	GetFrames() []ParserFrame
	GetImportantScope() []map[string]bool
	GetDefaultFunc() *DefaultFunc
}

type Evaluator

type Evaluator interface {
	Eval(context any) (any, error)
}

Evaluator interface for nodes that can be evaluated

type ExamplePlugin

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

ExamplePlugin demonstrates a Go-based Less plugin

func NewExamplePlugin

func NewExamplePlugin() *ExamplePlugin

NewExamplePlugin creates a new example plugin

func (*ExamplePlugin) EvalPlugin

func (p *ExamplePlugin) EvalPlugin() interface{}

EvalPlugin returns the plugin evaluator

func (*ExamplePlugin) GetMinVersion

func (p *ExamplePlugin) GetMinVersion() string

GetMinVersion returns the minimum Less version required

func (*ExamplePlugin) Install

func (p *ExamplePlugin) Install(functions map[string]any, tree map[string]any) error

Install installs the plugin functions into the function registry

func (*ExamplePlugin) Use

func (p *ExamplePlugin) Use() (map[string]any, error)

Use returns the plugin's exports

type ExamplePluginEvaluator

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

ExamplePluginEvaluator handles plugin evaluation

func (*ExamplePluginEvaluator) Eval

func (e *ExamplePluginEvaluator) Eval(node any) (any, error)

Eval evaluates a node in the plugin context

type ExamplePostProcessor

type ExamplePostProcessor struct{}

ExamplePostProcessor demonstrates a post-processor plugin

func (*ExamplePostProcessor) Process

func (p *ExamplePostProcessor) Process(css string, extra map[string]any) string

Process processes the CSS output after generation

type ExamplePreProcessor

type ExamplePreProcessor struct{}

ExamplePreProcessor demonstrates a pre-processor plugin

func (*ExamplePreProcessor) Process

func (p *ExamplePreProcessor) Process(input string, extra map[string]any) string

Process processes the input before parsing

type Expression

type Expression struct {
	*Node
	Value      []any
	NoSpacing  bool
	Parens     bool
	ParensInOp bool
}

func GetExpressionFromPool

func GetExpressionFromPool() *Expression

func NewExpression

func NewExpression(value []any, noSpacing bool) (*Expression, error)

func Range

func Range(start, end, step any) *Expression

func (*Expression) Accept

func (e *Expression) Accept(visitor any)

func (*Expression) Eval

func (e *Expression) Eval(context any) (any, error)

func (*Expression) GenCSS

func (e *Expression) GenCSS(context any, output *CSSOutput)

func (*Expression) GetParens

func (e *Expression) GetParens() bool

func (*Expression) GetParensInOp

func (e *Expression) GetParensInOp() bool

func (*Expression) GetType

func (e *Expression) GetType() string

func (*Expression) GetValue

func (e *Expression) GetValue() []any

func (*Expression) Release

func (e *Expression) Release()

func (*Expression) ThrowAwayComments

func (e *Expression) ThrowAwayComments()

func (*Expression) ToCSS

func (e *Expression) ToCSS(context any) string

type Extend

type Extend struct {
	*Node
	Selector      any
	Option        string
	ObjectId      int
	ParentIds     []int
	AllowRoot     bool
	AllowBefore   bool
	AllowAfter    bool
	SelfSelectors []any
	// Fields added for visitor support
	Ruleset                       *Ruleset
	FirstExtendOnThisSelectorPath bool
	HasFoundMatches               bool
}

func NewExtend

func NewExtend(selector any, option string, index int, currentFileInfo map[string]any, visibilityInfo map[string]any) *Extend

func (*Extend) Accept

func (e *Extend) Accept(visitor any)

func (*Extend) Clone

func (e *Extend) Clone(context any) *Extend

func (*Extend) Eval

func (e *Extend) Eval(context any) (*Extend, error)

func (*Extend) FindSelfSelectors

func (e *Extend) FindSelfSelectors(selectors []any)

func (*Extend) GenCSS

func (e *Extend) GenCSS(context any, output *CSSOutput)

func (*Extend) GetType

func (e *Extend) GetType() string

func (*Extend) IsVisible

func (e *Extend) IsVisible() bool

func (*Extend) Type

func (e *Extend) Type() string

type ExtendFinderVisitor

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

func GetExtendFinderVisitor

func GetExtendFinderVisitor() *ExtendFinderVisitor

GetExtendFinderVisitor retrieves an ExtendFinderVisitor from the pool

func NewExtendFinderVisitor

func NewExtendFinderVisitor() *ExtendFinderVisitor

func (*ExtendFinderVisitor) IsReplacing

func (efv *ExtendFinderVisitor) IsReplacing() bool

IsReplacing returns false as ExtendFinderVisitor is not a replacing visitor

func (*ExtendFinderVisitor) Reset

func (efv *ExtendFinderVisitor) Reset()

Reset resets the ExtendFinderVisitor for reuse from the pool. The visitor's methodLookup map is preserved (it's expensive to rebuild).

func (*ExtendFinderVisitor) Run

func (efv *ExtendFinderVisitor) Run(root any) any

func (*ExtendFinderVisitor) VisitAtRule

func (efv *ExtendFinderVisitor) VisitAtRule(atRuleNode any, visitArgs *VisitArgs)

func (*ExtendFinderVisitor) VisitAtRuleOut

func (efv *ExtendFinderVisitor) VisitAtRuleOut(atRuleNode any)

func (*ExtendFinderVisitor) VisitDeclaration

func (efv *ExtendFinderVisitor) VisitDeclaration(declNode any, visitArgs *VisitArgs)

func (*ExtendFinderVisitor) VisitMedia

func (efv *ExtendFinderVisitor) VisitMedia(mediaNode any, visitArgs *VisitArgs)

func (*ExtendFinderVisitor) VisitMediaOut

func (efv *ExtendFinderVisitor) VisitMediaOut(mediaNode any)

func (*ExtendFinderVisitor) VisitMixinDefinition

func (efv *ExtendFinderVisitor) VisitMixinDefinition(mixinDefinitionNode any, visitArgs *VisitArgs)

func (*ExtendFinderVisitor) VisitNode

func (efv *ExtendFinderVisitor) VisitNode(node any, visitArgs *VisitArgs) (any, bool)

VisitNode implements direct dispatch without reflection for better performance

func (*ExtendFinderVisitor) VisitNodeOut

func (efv *ExtendFinderVisitor) VisitNodeOut(node any) bool

VisitNodeOut implements direct dispatch for visitOut methods

func (*ExtendFinderVisitor) VisitRuleset

func (efv *ExtendFinderVisitor) VisitRuleset(rulesetNode any, visitArgs *VisitArgs)

func (*ExtendFinderVisitor) VisitRulesetOut

func (efv *ExtendFinderVisitor) VisitRulesetOut(rulesetNode any)

type FileCache

type FileCache struct {
	Root    any            `json:"root"`
	Options map[string]any `json:"options"`
}

type FileInfo

type FileInfo struct {
	RewriteUrls      bool   `json:"rewriteUrls"`
	Filename         string `json:"filename"`
	Rootpath         string `json:"rootpath"`
	CurrentDirectory string `json:"currentDirectory"`
	RootFilename     string `json:"rootFilename"`
	EntryPath        string `json:"entryPath"`
	Reference        bool   `json:"reference"`
}

FileInfo contains information about a file being processed Mirrors the JavaScript FileInfo structure:

'rewriteUrls' - option - whether to adjust URL's to be relative
'filename' - full resolved filename of current file
'rootpath' - path to append to normal URLs for this node
'currentDirectory' - path to the current file, absolute
'rootFilename' - filename of the base file
'entryPath' - absolute path to the entry file
'reference' - whether the file should not be output and only output parts that are referenced

type FileManager

type FileManager interface {
	LoadFileSync(path, currentDirectory string, context map[string]any, environment ImportManagerEnvironment) *LoadedFile
	LoadFile(path, currentDirectory string, context map[string]any, environment ImportManagerEnvironment, callback func(error, *LoadedFile)) any
	GetPath(filename string) string
	Join(path1, path2 string) string
	PathDiff(currentDirectory, entryPath string) string
	IsPathAbsolute(path string) bool
	AlwaysMakePathsAbsolute() bool
}

type FileSystemFileManager

type FileSystemFileManager struct {
	AbstractFileManager
}

FileSystemFileManager implements a real file manager that loads files from disk

func NewFileSystemFileManager

func NewFileSystemFileManager() *FileSystemFileManager

NewFileSystemFileManager creates a new FileSystemFileManager

func (*FileSystemFileManager) AlwaysMakePathsAbsolute

func (fm *FileSystemFileManager) AlwaysMakePathsAbsolute() bool

AlwaysMakePathsAbsolute returns false (we don't always make paths absolute)

func (*FileSystemFileManager) CanonicalizeFilename

func (fm *FileSystemFileManager) CanonicalizeFilename(filename string) string

CanonicalizeFilename canonicalizes a filename

func (*FileSystemFileManager) ConvertToFileUrl

func (fm *FileSystemFileManager) ConvertToFileUrl(filename string, url string, options map[string]any) string

ConvertToFileUrl converts a filename to a file URL

func (*FileSystemFileManager) GetPath

func (fm *FileSystemFileManager) GetPath(filename string) string

GetPath returns the directory of a filename

func (*FileSystemFileManager) IsPathAbsolute

func (fm *FileSystemFileManager) IsPathAbsolute(filename string) bool

IsPathAbsolute checks if a path is absolute

func (*FileSystemFileManager) Join

func (fm *FileSystemFileManager) Join(basePath, relativePath string) string

Join joins two paths

func (*FileSystemFileManager) LoadFile

func (fm *FileSystemFileManager) LoadFile(filename, currentDirectory string, context map[string]any, environment ImportManagerEnvironment, callback func(error, *LoadedFile)) any

LoadFile loads a file asynchronously (but we implement it synchronously for now)

func (*FileSystemFileManager) LoadFileSync

func (fm *FileSystemFileManager) LoadFileSync(filename, currentDirectory string, context map[string]any, environment ImportManagerEnvironment) *LoadedFile

LoadFileSync loads a file synchronously

func (*FileSystemFileManager) PathDiff

func (fm *FileSystemFileManager) PathDiff(url, baseUrl string) string

PathDiff returns the relative path between two directories This matches the JavaScript AbstractFileManager.pathDiff behavior: - Always uses forward slashes (/) - Adds trailing slash for directories - Input paths should be directories ending with /

func (*FileSystemFileManager) Supports

func (fm *FileSystemFileManager) Supports(filename, currentDirectory string, options map[string]any, environment map[string]any) bool

Supports returns true for all files (this manager handles any file)

func (*FileSystemFileManager) SupportsSync

func (fm *FileSystemFileManager) SupportsSync(filename, currentDirectory string, options map[string]any, environment map[string]any) bool

SupportsSync returns true (we support synchronous loading)

type FlexibleFunctionDef

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

func (*FlexibleFunctionDef) Call

func (f *FlexibleFunctionDef) Call(args ...any) (any, error)

func (*FlexibleFunctionDef) CallCtx

func (f *FlexibleFunctionDef) CallCtx(ctx *Context, args ...any) (any, error)

func (*FlexibleFunctionDef) NeedsEvalArgs

func (f *FlexibleFunctionDef) NeedsEvalArgs() bool

type Frame

type Frame struct {
	FunctionRegistry FunctionRegistry

	EvalContext     EvalContext    // Reference to the evaluation context
	CurrentFileInfo map[string]any // Current file information for this frame
	// contains filtered or unexported fields
}

Frame represents a scope frame.

func (*Frame) SetVariable

func (f *Frame) SetVariable(name string, value any)

SetVariable sets a variable in the frame

func (*Frame) Variable

func (f *Frame) Variable(name string) any

Variable gets a variable from the frame

type FunctionCallerFactory

type FunctionCallerFactory interface {
	NewFunctionCaller(name string, context EvalContext, index int, fileInfo map[string]any) (ParserFunctionCaller, error)
}

type FunctionDefinition

type FunctionDefinition interface {
	// Call handles functions where args are evaluated (evalArgs=true, default)
	Call(args ...any) (any, error)
	// CallCtx handles functions where args are not evaluated (evalArgs=false)
	CallCtx(ctx *Context, args ...any) (any, error)
	// NeedsEvalArgs returns true if arguments should be evaluated before calling.
	NeedsEvalArgs() bool
}

FunctionDefinition defines a Less function.

type FunctionRegistry

type FunctionRegistry interface {
	Get(name string) FunctionDefinition
}

FunctionRegistry provides access to registered functions.

type Functions

type Functions interface {
	GetFunctionRegistry() any
}

Functions interface represents the functions registry

type HSL

type HSL struct {
	H float64
	S float64
	L float64
	A float64
}

type HSV

type HSV struct {
	H float64
	S float64
	V float64
	A float64
}

type IfFunctionDef

type IfFunctionDef struct{}

func (*IfFunctionDef) Call

func (f *IfFunctionDef) Call(args ...any) (any, error)

func (*IfFunctionDef) CallCtx

func (f *IfFunctionDef) CallCtx(ctx *Context, args ...any) (any, error)

func (*IfFunctionDef) NeedsEvalArgs

func (f *IfFunctionDef) NeedsEvalArgs() bool

type ImageHeightFunctionWrapper

type ImageHeightFunctionWrapper struct{}

func (*ImageHeightFunctionWrapper) Call

func (w *ImageHeightFunctionWrapper) Call(args ...any) (any, error)

func (*ImageHeightFunctionWrapper) CallCtx

func (w *ImageHeightFunctionWrapper) CallCtx(ctx *Context, args ...any) (any, error)

func (*ImageHeightFunctionWrapper) NeedsEvalArgs

func (w *ImageHeightFunctionWrapper) NeedsEvalArgs() bool

type ImageSizeFunctionWrapper

type ImageSizeFunctionWrapper struct{}

func (*ImageSizeFunctionWrapper) Call

func (w *ImageSizeFunctionWrapper) Call(args ...any) (any, error)

func (*ImageSizeFunctionWrapper) CallCtx

func (w *ImageSizeFunctionWrapper) CallCtx(ctx *Context, args ...any) (any, error)

func (*ImageSizeFunctionWrapper) NeedsEvalArgs

func (w *ImageSizeFunctionWrapper) NeedsEvalArgs() bool

type ImageWidthFunctionWrapper

type ImageWidthFunctionWrapper struct{}

func (*ImageWidthFunctionWrapper) Call

func (w *ImageWidthFunctionWrapper) Call(args ...any) (any, error)

func (*ImageWidthFunctionWrapper) CallCtx

func (w *ImageWidthFunctionWrapper) CallCtx(ctx *Context, args ...any) (any, error)

func (*ImageWidthFunctionWrapper) NeedsEvalArgs

func (w *ImageWidthFunctionWrapper) NeedsEvalArgs() bool

type Implementation

type Implementation interface {
	IsReplacing() bool
}

type Import

type Import struct {
	*Node
	// contains filtered or unexported fields
}

Import represents a CSS @import node. Files are pushed to an import queue on creation with a callback that fires when the file has been fetched and parsed.

func NewImport

func NewImport(path any, features any, options map[string]any, index int, currentFileInfo map[string]any, visibilityInfo map[string]any) *Import

func (*Import) Accept

func (i *Import) Accept(visitor any)

func (*Import) DoEval

func (i *Import) DoEval(context any) (any, error)

func (*Import) Eval

func (i *Import) Eval(context any) (any, error)

func (*Import) EvalForImport

func (i *Import) EvalForImport(context any) *Import

func (*Import) EvalPath

func (i *Import) EvalPath(context any) any

func (*Import) FileInfo

func (i *Import) FileInfo() map[string]any

func (*Import) GenCSS

func (i *Import) GenCSS(context any, output *CSSOutput)

func (*Import) GetIndex

func (i *Import) GetIndex() int

func (*Import) GetPath

func (i *Import) GetPath() any

func (*Import) GetRoot added in v0.4.0

func (i *Import) GetRoot() interface {
	Variables() map[string]any
	Variable(string) any
}

GetRoot returns the root ruleset of this import for variable hoisting. This is needed for variable lookup to traverse into imported files.

func (*Import) GetType

func (i *Import) GetType() string

func (*Import) GetTypeIndex

func (i *Import) GetTypeIndex() int

GetTypeIndex returns the type index for visitor pattern

func (*Import) IsVariableImport

func (i *Import) IsVariableImport() bool

func (*Import) IsVisible

func (i *Import) IsVisible() bool

type ImportItem

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

type ImportManager

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

func (*ImportManager) Contents

func (im *ImportManager) Contents() map[string]string

func (*ImportManager) ContentsIgnoredChars added in v0.1.4

func (im *ImportManager) ContentsIgnoredChars() map[string]int

ContentsIgnoredChars returns the number of characters to ignore at the start of each file This is used for source maps when global vars or banners are injected

func (*ImportManager) Files

func (im *ImportManager) Files() map[string]*FileCache

func (*ImportManager) Push

func (im *ImportManager) Push(path string, tryAppendExtension bool, currentFileInfo *FileInfo, importOptions *ImportOptions, callback ParseCallback)

func (*ImportManager) RootFilename

func (im *ImportManager) RootFilename() string

type ImportManagerEnvironment

type ImportManagerEnvironment interface {
	GetFileManager(path, currentDirectory string, context map[string]any, environment ImportManagerEnvironment) FileManager
}

type ImportOptions

type ImportOptions struct {
	Optional   bool           `json:"optional"`
	Inline     bool           `json:"inline"`
	IsPlugin   bool           `json:"isPlugin"`
	PluginArgs map[string]any `json:"pluginArgs"`
	Reference  bool           `json:"reference"`
	Multiple   bool           `json:"multiple"`
}

type ImportSequencer

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

func NewImportSequencer

func NewImportSequencer(onSequencerEmpty func()) *ImportSequencer

func (*ImportSequencer) AddImport

func (is *ImportSequencer) AddImport(callback func(...any)) func(...any)

func (*ImportSequencer) AddVariableImport

func (is *ImportSequencer) AddVariableImport(callback func())

func (*ImportSequencer) TryRun

func (is *ImportSequencer) TryRun()

type ImportVisitor

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

func NewImportVisitor

func NewImportVisitor(importer any, finish func(error)) *ImportVisitor

func (*ImportVisitor) IsReplacing

func (iv *ImportVisitor) IsReplacing() bool

func (*ImportVisitor) Run

func (iv *ImportVisitor) Run(root any)

func (*ImportVisitor) VisitAtRule

func (iv *ImportVisitor) VisitAtRule(atRuleNode any, visitArgs *VisitArgs)

func (*ImportVisitor) VisitAtRuleOut

func (iv *ImportVisitor) VisitAtRuleOut(atRuleNode any)

func (*ImportVisitor) VisitDeclaration

func (iv *ImportVisitor) VisitDeclaration(declNode any, visitArgs *VisitArgs)

func (*ImportVisitor) VisitDeclarationOut

func (iv *ImportVisitor) VisitDeclarationOut(declNode any)

func (*ImportVisitor) VisitImport

func (iv *ImportVisitor) VisitImport(importNode any, visitArgs *VisitArgs)

func (*ImportVisitor) VisitMedia

func (iv *ImportVisitor) VisitMedia(mediaNode any, visitArgs *VisitArgs)

func (*ImportVisitor) VisitMediaOut

func (iv *ImportVisitor) VisitMediaOut(mediaNode any)

func (*ImportVisitor) VisitMixinDefinition

func (iv *ImportVisitor) VisitMixinDefinition(mixinDefinitionNode any, visitArgs *VisitArgs)

func (*ImportVisitor) VisitMixinDefinitionOut

func (iv *ImportVisitor) VisitMixinDefinitionOut(mixinDefinitionNode any)

func (*ImportVisitor) VisitNode

func (iv *ImportVisitor) VisitNode(node any, visitArgs *VisitArgs) (any, bool)

func (*ImportVisitor) VisitNodeOut

func (iv *ImportVisitor) VisitNodeOut(node any) bool

func (*ImportVisitor) VisitRuleset

func (iv *ImportVisitor) VisitRuleset(rulesetNode any, visitArgs *VisitArgs)

func (*ImportVisitor) VisitRulesetOut

func (iv *ImportVisitor) VisitRulesetOut(rulesetNode any)

type ImportantScopeEntry

type ImportantScopeEntry struct {
	Important string // The " !important" suffix value when set
}

ImportantScopeEntry represents a single entry in the !important scope stack. This replaces map[string]any with a typed struct to eliminate reflection overhead.

type Imports

type Imports struct {
	Contents             map[string]string
	ContentsIgnoredChars map[string]int
}

type IsDefinedFunctionDef

type IsDefinedFunctionDef struct{}

func (*IsDefinedFunctionDef) Call

func (f *IsDefinedFunctionDef) Call(args ...any) (any, error)

func (*IsDefinedFunctionDef) CallCtx

func (f *IsDefinedFunctionDef) CallCtx(ctx *Context, args ...any) (any, error)

func (*IsDefinedFunctionDef) NeedsEvalArgs

func (f *IsDefinedFunctionDef) NeedsEvalArgs() bool

type JSArrayResult

type JSArrayResult struct {
	Value string
}

type JSEmptyResult

type JSEmptyResult struct{}

type JSVisitorAdapter

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

JSVisitorAdapter adapts a runtime.JSVisitor to work with the PluginManager's visitor system. It implements the interfaces expected by transform_tree.go.

NOTE: This is part of an EXPERIMENTAL binary buffer visitor approach that is NOT currently used in production. The actual visitor execution uses the JSON pathway via NodeJSPluginBridge.RunPreEvalVisitorsJSON(). See the comment on applyReplacements() for more details.

func NewJSVisitorAdapter

func NewJSVisitorAdapter(visitor *runtime.JSVisitor, rt *runtime.NodeJSRuntime) *JSVisitorAdapter

NewJSVisitorAdapter creates a new adapter for a JavaScript visitor.

func (*JSVisitorAdapter) IsPreEvalVisitor

func (a *JSVisitorAdapter) IsPreEvalVisitor() bool

IsPreEvalVisitor returns true if this is a pre-evaluation visitor. This matches the interface expected by transform_tree.go.

func (*JSVisitorAdapter) IsPreVisitor

func (a *JSVisitorAdapter) IsPreVisitor() bool

IsPreVisitor returns false - JS visitors are not "pre" visitors in the sense of going before built-in visitors. They follow the pre-eval/post-eval pattern.

func (*JSVisitorAdapter) IsReplacing

func (a *JSVisitorAdapter) IsReplacing() bool

IsReplacing returns true if this visitor can replace nodes.

func (*JSVisitorAdapter) Run

func (a *JSVisitorAdapter) Run(root any) any

Run executes the JavaScript visitor on the AST root. It serializes the AST, sends it to Node.js, runs the visitor, and applies any replacements to the Go AST.

type JSVisitorRegistry

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

JSVisitorRegistry manages JavaScript visitors registered by plugins. It integrates with the PluginManager to provide visitors to transform_tree.

NOTE: This is part of an EXPERIMENTAL binary buffer visitor approach that is NOT currently used in production. See JSVisitorAdapter for details.

func NewJSVisitorRegistry

func NewJSVisitorRegistry(rt *runtime.NodeJSRuntime) *JSVisitorRegistry

NewJSVisitorRegistry creates a new registry for JavaScript visitors.

func (*JSVisitorRegistry) GetAdapters

func (r *JSVisitorRegistry) GetAdapters() []*JSVisitorAdapter

GetAdapters returns all visitor adapters.

func (*JSVisitorRegistry) GetPostEvalAdapters

func (r *JSVisitorRegistry) GetPostEvalAdapters() []*JSVisitorAdapter

GetPostEvalAdapters returns only post-evaluation visitor adapters.

func (*JSVisitorRegistry) GetPreEvalAdapters

func (r *JSVisitorRegistry) GetPreEvalAdapters() []*JSVisitorAdapter

GetPreEvalAdapters returns only pre-evaluation visitor adapters.

func (*JSVisitorRegistry) RefreshFromNodeJS

func (r *JSVisitorRegistry) RefreshFromNodeJS() error

RefreshFromNodeJS fetches the current list of registered visitors from Node.js and creates adapters for them.

func (*JSVisitorRegistry) RegisterWithPluginManager

func (r *JSVisitorRegistry) RegisterWithPluginManager(pm *PluginManager)

RegisterWithPluginManager adds all visitor adapters to the PluginManager. This allows them to be picked up by transform_tree.go's visitor loop.

type JavaScript

type JavaScript struct {
	*JsEvalNode
	// contains filtered or unexported fields
}

func NewJavaScript

func NewJavaScript(string string, escaped bool, index int, currentFileInfo map[string]any) *JavaScript

func (*JavaScript) Eval

func (j *JavaScript) Eval(context any) (any, error)

func (*JavaScript) FileInfo

func (j *JavaScript) FileInfo() map[string]any

func (*JavaScript) GetIndex

func (j *JavaScript) GetIndex() int

func (*JavaScript) GetType

func (j *JavaScript) GetType() string

func (*JavaScript) Type

func (j *JavaScript) Type() string

type JoinSelectorVisitor

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

func GetJoinSelectorVisitor

func GetJoinSelectorVisitor() *JoinSelectorVisitor

GetJoinSelectorVisitor retrieves a JoinSelectorVisitor from the pool

func NewJoinSelectorVisitor

func NewJoinSelectorVisitor() *JoinSelectorVisitor

func (*JoinSelectorVisitor) IsReplacing

func (jsv *JoinSelectorVisitor) IsReplacing() bool

func (*JoinSelectorVisitor) Reset

func (jsv *JoinSelectorVisitor) Reset()

Reset resets the JoinSelectorVisitor for reuse from the pool. The visitor's methodLookup map is preserved (it's expensive to rebuild).

func (*JoinSelectorVisitor) Run

func (jsv *JoinSelectorVisitor) Run(root any) any

func (*JoinSelectorVisitor) VisitAtRule

func (jsv *JoinSelectorVisitor) VisitAtRule(atRuleNode any, visitArgs *VisitArgs) any

Matches JavaScript join-selector-visitor.js visitAtRule: atRuleNode.rules[0].root = (atRuleNode.isRooted || context.length === 0 || null);

func (*JoinSelectorVisitor) VisitContainer

func (jsv *JoinSelectorVisitor) VisitContainer(containerNode any, visitArgs *VisitArgs) any

func (*JoinSelectorVisitor) VisitDeclaration

func (jsv *JoinSelectorVisitor) VisitDeclaration(declNode any, visitArgs *VisitArgs) any

func (*JoinSelectorVisitor) VisitMedia

func (jsv *JoinSelectorVisitor) VisitMedia(mediaNode any, visitArgs *VisitArgs) any

func (*JoinSelectorVisitor) VisitMixinDefinition

func (jsv *JoinSelectorVisitor) VisitMixinDefinition(mixinDefinitionNode any, visitArgs *VisitArgs) any

func (*JoinSelectorVisitor) VisitNode

func (jsv *JoinSelectorVisitor) VisitNode(node any, visitArgs *VisitArgs) (any, bool)

func (*JoinSelectorVisitor) VisitNodeOut

func (jsv *JoinSelectorVisitor) VisitNodeOut(node any) bool

func (*JoinSelectorVisitor) VisitRuleset

func (jsv *JoinSelectorVisitor) VisitRuleset(rulesetNode any, visitArgs *VisitArgs) any

func (*JoinSelectorVisitor) VisitRulesetOut

func (jsv *JoinSelectorVisitor) VisitRulesetOut(rulesetNode any)

type JsEvalNode

type JsEvalNode struct {
	*Node
}

func NewJsEvalNode

func NewJsEvalNode() *JsEvalNode

func (*JsEvalNode) EvaluateJavaScript

func (j *JsEvalNode) EvaluateJavaScript(expression string, context any) (any, error)

func (*JsEvalNode) GetType

func (j *JsEvalNode) GetType() string

func (*JsEvalNode) Type

func (j *JsEvalNode) Type() string

type Keyword

type Keyword struct {
	*Node
	// contains filtered or unexported fields
}

func Boolean

func Boolean(condition any) *Keyword

func IsDefined

func IsDefined(context *Context, variable any) *Keyword

func NewKeyword

func NewKeyword(value string) *Keyword

func (*Keyword) Eval

func (k *Keyword) Eval(context any) (any, error)

func (*Keyword) GenCSS

func (k *Keyword) GenCSS(context any, output *CSSOutput)

func (*Keyword) GetType

func (k *Keyword) GetType() string

func (*Keyword) GetValue

func (k *Keyword) GetValue() string

func (*Keyword) ToCSS

func (k *Keyword) ToCSS(context any) string

func (*Keyword) Type

func (k *Keyword) Type() string

type LazyNodeJSPluginBridge

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

LazyNodeJSPluginBridge provides lazy initialization of the NodeJS plugin bridge, avoiding the overhead of spawning Node.js for compilations that don't use plugins.

func NewLazyNodeJSPluginBridge

func NewLazyNodeJSPluginBridge() *LazyNodeJSPluginBridge

func (*LazyNodeJSPluginBridge) CallFunction

func (lb *LazyNodeJSPluginBridge) CallFunction(name string, args ...any) (any, error)

func (*LazyNodeJSPluginBridge) CallFunctionWithContext

func (lb *LazyNodeJSPluginBridge) CallFunctionWithContext(name string, evalContext runtime.EvalContextProvider, args ...any) (any, error)

func (*LazyNodeJSPluginBridge) Close

func (lb *LazyNodeJSPluginBridge) Close() error

func (*LazyNodeJSPluginBridge) EnterScope

func (lb *LazyNodeJSPluginBridge) EnterScope() *runtime.PluginScope

func (*LazyNodeJSPluginBridge) EvalPlugin

func (lb *LazyNodeJSPluginBridge) EvalPlugin(contents string, newEnv *Parse, importManager any, pluginArgs map[string]any, newFileInfo any) any

func (*LazyNodeJSPluginBridge) ExitScope

func (lb *LazyNodeJSPluginBridge) ExitScope() *runtime.PluginScope

func (*LazyNodeJSPluginBridge) GetBridge

func (lb *LazyNodeJSPluginBridge) GetBridge() (*NodeJSPluginBridge, error)

func (*LazyNodeJSPluginBridge) GetPostEvalVisitors

func (lb *LazyNodeJSPluginBridge) GetPostEvalVisitors() []*runtime.JSVisitor

func (*LazyNodeJSPluginBridge) GetPostProcessors

func (lb *LazyNodeJSPluginBridge) GetPostProcessors() []*runtime.JSPostProcessor

func (*LazyNodeJSPluginBridge) GetPreEvalVisitors

func (lb *LazyNodeJSPluginBridge) GetPreEvalVisitors() []*runtime.JSVisitor

func (*LazyNodeJSPluginBridge) GetPreProcessors

func (lb *LazyNodeJSPluginBridge) GetPreProcessors() []*runtime.JSPreProcessor

func (*LazyNodeJSPluginBridge) GetProcessorManager

func (lb *LazyNodeJSPluginBridge) GetProcessorManager() *runtime.ProcessorManager

func (*LazyNodeJSPluginBridge) GetRuntime

func (lb *LazyNodeJSPluginBridge) GetRuntime() *runtime.NodeJSRuntime

func (*LazyNodeJSPluginBridge) GetScope

func (lb *LazyNodeJSPluginBridge) GetScope() *runtime.PluginScope

func (*LazyNodeJSPluginBridge) GetVisitors

func (lb *LazyNodeJSPluginBridge) GetVisitors() []*runtime.JSVisitor

func (*LazyNodeJSPluginBridge) HasFunction

func (lb *LazyNodeJSPluginBridge) HasFunction(name string) bool

func (*LazyNodeJSPluginBridge) IsInitialized

func (lb *LazyNodeJSPluginBridge) IsInitialized() bool

func (*LazyNodeJSPluginBridge) LoadPlugin

func (lb *LazyNodeJSPluginBridge) LoadPlugin(path, currentDirectory string, context map[string]any, environment any, fileManager any) any

func (*LazyNodeJSPluginBridge) LoadPluginSync

func (lb *LazyNodeJSPluginBridge) LoadPluginSync(path, currentDirectory string, context map[string]any, environment any, fileManager any) any

func (*LazyNodeJSPluginBridge) LookupFunction

func (lb *LazyNodeJSPluginBridge) LookupFunction(name string) (*runtime.JSFunctionDefinition, bool)

func (*LazyNodeJSPluginBridge) RunPostProcessors

func (lb *LazyNodeJSPluginBridge) RunPostProcessors(css string, options map[string]any) (string, error)

func (*LazyNodeJSPluginBridge) RunPreProcessors

func (lb *LazyNodeJSPluginBridge) RunPreProcessors(input string, options map[string]any) (string, error)

func (*LazyNodeJSPluginBridge) WasUsed

func (lb *LazyNodeJSPluginBridge) WasUsed() bool

type LessContext

type LessContext struct {
	Options       map[string]any
	ImportManager *ImportManager
	PluginLoader  PluginLoaderFactory
	Functions     Functions
	// PluginBridge provides lazy access to the Node.js plugin system.
	// It is initialized on first use and should be closed after compilation.
	PluginBridge *LazyNodeJSPluginBridge
}

LessContext represents the "this" context that contains options and importManager

func NewLessContext

func NewLessContext(options map[string]any) *LessContext

NewLessContext creates a new LessContext

func NewLessContextWithPlugins

func NewLessContextWithPlugins(options map[string]any) (*LessContext, func() error)

NewLessContextWithPlugins creates a LessContext with JavaScript plugin support. The context includes a lazy plugin bridge that only starts Node.js when plugins are used. The returned cleanup function should be called after compilation to shut down Node.js.

func (*LessContext) GetFunctions

func (lc *LessContext) GetFunctions() Functions

GetFunctions implements LessInterface

func (*LessContext) GetPluginLoader

func (lc *LessContext) GetPluginLoader() PluginLoaderFactory

GetPluginLoader implements LessInterface

type LessError

type LessError struct {
	Type        string
	Message     string
	Stack       string
	Filename    string
	Index       any
	Line        *int
	Column      int
	CallLine    *int
	CallExtract string
	Extract     []string
	// contains filtered or unexported fields
}

func NewLessError

func NewLessError(e ErrorDetails, fileContentMap map[string]string, currentFilename string) *LessError

func (*LessError) ColumnNumber

func (le *LessError) ColumnNumber() int

func (*LessError) Error

func (le *LessError) Error() string

func (*LessError) ErrorType

func (le *LessError) ErrorType() string

func (*LessError) GetErrorType

func (le *LessError) GetErrorType() string

func (*LessError) HasLineColumn

func (le *LessError) HasLineColumn() bool

func (*LessError) LineNumber

func (le *LessError) LineNumber() int

func (*LessError) ToString

func (le *LessError) ToString(options *ToStringOptions) string

type LessInterface

type LessInterface interface {
	GetPluginLoader() PluginLoaderFactory
	GetFunctions() Functions
}

LessInterface represents the minimal interface needed by PluginManager

type LoadedFile

type LoadedFile struct {
	Filename string `json:"filename"`
	Contents string `json:"contents"`
	Message  string `json:"message,omitempty"`
}

type Location

type Location struct {
	Line   *int
	Column int
}

Location represents a position in the input stream

func GetLocation

func GetLocation(index any, inputStream string) Location

GetLocation returns the line and column for a given index in the input stream

type LogListener

type LogListener interface {
	Error(msg any)
	Warn(msg any)
	Info(msg any)
	Debug(msg any)
}

type LogListenerPartial

type LogListenerPartial map[string]func(msg any)

type Logger

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

func NewLogger

func NewLogger() *Logger

func (*Logger) AddListener

func (l *Logger) AddListener(listener any)

func (*Logger) Debug

func (l *Logger) Debug(msg any)

func (*Logger) Error

func (l *Logger) Error(msg any)

func (*Logger) GetListeners

func (l *Logger) GetListeners() []any

func (*Logger) Info

func (l *Logger) Info(msg any)

func (*Logger) RemoveListener

func (l *Logger) RemoveListener(listener any)

func (*Logger) Warn

func (l *Logger) Warn(msg any)

type MapEvalContext

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

func (*MapEvalContext) EnterCalc

func (m *MapEvalContext) EnterCalc()

func (*MapEvalContext) ExitCalc

func (m *MapEvalContext) ExitCalc()

func (*MapEvalContext) GetDefaultFunc

func (m *MapEvalContext) GetDefaultFunc() *DefaultFunc

func (*MapEvalContext) GetFrames

func (m *MapEvalContext) GetFrames() []ParserFrame

func (*MapEvalContext) GetImportantScope

func (m *MapEvalContext) GetImportantScope() []map[string]bool

func (*MapEvalContext) IsInCalc

func (m *MapEvalContext) IsInCalc() bool

func (*MapEvalContext) IsMathOn

func (m *MapEvalContext) IsMathOn() bool

func (*MapEvalContext) SetMathOn

func (m *MapEvalContext) SetMathOn(enabled bool)

type MathFunctionWrapper

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

MathFunctionWrapper wraps math functions to implement FunctionDefinition interface

func (*MathFunctionWrapper) Call

func (w *MathFunctionWrapper) Call(args ...any) (any, error)

func (*MathFunctionWrapper) CallCtx

func (w *MathFunctionWrapper) CallCtx(ctx *Context, args ...any) (any, error)

func (*MathFunctionWrapper) NeedsEvalArgs

func (w *MathFunctionWrapper) NeedsEvalArgs() bool

type MathHelperError

type MathHelperError struct {
	Type    string
	Message string
}

MathHelperError represents an argument error

func (*MathHelperError) Error

func (e *MathHelperError) Error() string

type MathType

type MathType int
const (
	MathAlways MathType = iota
	MathParensDivision
	MathParens
)

type Media

type Media struct {
	*AtRule
	Features  any
	Rules     []any
	DebugInfo any
}

Media represents a media query node in the Less AST

func NewMedia

func NewMedia(value any, features any, index int, currentFileInfo map[string]any, visibilityInfo map[string]any) *Media

NewMedia creates a new Media instance

func (*Media) Accept

func (m *Media) Accept(visitor any)

Accept visits the node with a visitor (implementing NestableAtRulePrototype)

func (*Media) BubbleSelectors

func (m *Media) BubbleSelectors(selectors any)

BubbleSelectors bubbles selectors up the tree (implementing NestableAtRulePrototype) This function wraps the media's inner ruleset with the parent selectors. It can be called multiple times from different parent rulesets, each adding another layer of wrapping to build up the full selector path. For example, with .first { .second { .third { @media {...} } } }: - First call wraps with .third selectors - Second call wraps with .second selectors (around the .third wrapper) - Third call wraps with .first selectors (around the .second wrapper) This builds up to .first .second .third when selectors are joined.

func (*Media) Eval

func (m *Media) Eval(context any) (any, error)

Eval evaluates the media rule - matching JavaScript implementation closely

func (*Media) EvalNested

func (m *Media) EvalNested(context any) any

EvalNested evaluates the media rule in a nested context (implementing NestableAtRulePrototype)

func (*Media) EvalTop

func (m *Media) EvalTop(context any) any

EvalTop evaluates the media rule at the top level (implementing NestableAtRulePrototype)

func (*Media) GenCSS

func (m *Media) GenCSS(context any, output *CSSOutput)

GenCSS generates CSS representation

func (*Media) GetRules

func (m *Media) GetRules() []any

GetRules returns the rules for this media query

func (*Media) GetType

func (m *Media) GetType() string

GetType returns the type of the node

func (*Media) GetTypeIndex

func (m *Media) GetTypeIndex() int

GetTypeIndex returns the type index for visitor pattern

func (*Media) IsRulesetLike

func (m *Media) IsRulesetLike() bool

IsRulesetLike returns true (implementing NestableAtRulePrototype)

func (*Media) Permute

func (m *Media) Permute(arr []any) any

Permute creates permutations of the given array (implementing NestableAtRulePrototype)

func (*Media) Type

func (m *Media) Type() string

Type returns the type of the node (for compatibility)

type MediaRule

type MediaRule interface {
	SetRoot(root bool)
}

type MediaSyntaxOptions

type MediaSyntaxOptions struct {
	QueryInParens bool
}

type MediaSyntaxOptionsType

type MediaSyntaxOptionsType struct {
	QueryInParens bool
}

type MixinCall

type MixinCall struct {
	*Node
	Selector  *Selector
	Arguments []any
	Important bool
	AllowRoot bool
}

MixinCall represents a mixin call node in the Less AST

func NewMixinCall

func NewMixinCall(elements any, args []any, index int, currentFileInfo map[string]any, important bool) (*MixinCall, error)

NewMixinCall creates a new MixinCall instance

func (*MixinCall) Accept

func (mc *MixinCall) Accept(visitor any)

Accept visits the mixin call with a visitor

func (*MixinCall) Eval

func (mc *MixinCall) Eval(context any) ([]any, error)

Eval evaluates the mixin call

func (*MixinCall) Format

func (mc *MixinCall) Format(args []any) string

Format formats the mixin call for display

func (*MixinCall) GetType

func (mc *MixinCall) GetType() string

GetType returns the node type

func (*MixinCall) Type

func (mc *MixinCall) Type() string

Type returns the node type (for compatibility)

type MixinCallError

type MixinCallError struct {
	Type     string
	Message  string
	Index    int
	Filename string
	Stack    string
}

MixinCallError represents a Less error for mixin calls

func (*MixinCallError) Error

func (e *MixinCallError) Error() string

type MixinDefinition

type MixinDefinition struct {
	*Ruleset
	Name               string
	Params             []any
	Condition          any
	Variadic           bool
	Arity              int
	Lookups            map[string][]any
	Required           int
	OptionalParameters []string
	Frames             []any
}

MixinDefinition represents a mixin definition node in the Less AST

func NewMixinDefinition

func NewMixinDefinition(name string, params []any, rules []any, condition any, variadic bool, frames []any, visibilityInfo map[string]any) (*MixinDefinition, error)

NewMixinDefinition creates a new MixinDefinition instance

func (*MixinDefinition) Accept

func (md *MixinDefinition) Accept(visitor any)

Accept visits the mixin definition with a visitor

func (*MixinDefinition) Eval

func (md *MixinDefinition) Eval(context any) (*MixinDefinition, error)

Eval evaluates the mixin definition

func (*MixinDefinition) EvalCall

func (md *MixinDefinition) EvalCall(context any, args []any, important bool) (*Ruleset, error)

EvalCall evaluates a mixin call

func (*MixinDefinition) EvalFirst

func (md *MixinDefinition) EvalFirst() bool

EvalFirst indicates this node should be evaluated first

func (*MixinDefinition) EvalParams

func (md *MixinDefinition) EvalParams(context any, mixinEnv any, args []any, evaldArguments []any) (*Ruleset, error)

EvalParams evaluates mixin parameters and creates parameter frame

func (*MixinDefinition) GenCSS

func (md *MixinDefinition) GenCSS(context any, output *CSSOutput)

GenCSS for MixinDefinition - mixin definitions should not output any CSS

func (*MixinDefinition) GetType

func (md *MixinDefinition) GetType() string

GetType returns the type of the node

func (*MixinDefinition) IsRuleset

func (md *MixinDefinition) IsRuleset() bool

IsRuleset returns true (MixinDefinition inherits from Ruleset in JavaScript)

func (*MixinDefinition) MakeImportant

func (md *MixinDefinition) MakeImportant() any

MakeImportant creates a new MixinDefinition with important rules

func (*MixinDefinition) MatchArgs

func (md *MixinDefinition) MatchArgs(args []any, context any) bool

MatchArgs checks if the mixin arguments match

func (*MixinDefinition) MatchCondition

func (md *MixinDefinition) MatchCondition(args []any, context any) bool

MatchCondition checks if the mixin condition matches

func (*MixinDefinition) Type

func (md *MixinDefinition) Type() string

Type returns the type of the node (for compatibility)

type MixinParsers

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

MixinParsers contains mixin-related parsing methods

func (*MixinParsers) Args

func (m *MixinParsers) Args(isCall bool) map[string]any

Args parses mixin arguments

func (*MixinParsers) Call

func (m *MixinParsers) Call(inValue bool, getLookup bool) any

Call parses mixin calls

func (*MixinParsers) Definition

func (m *MixinParsers) Definition() any

Definition parses mixin definitions

func (*MixinParsers) Elements

func (m *MixinParsers) Elements() []*Element

Elements parses mixin elements

func (*MixinParsers) LookupValue

func (m *MixinParsers) LookupValue() *string

LookupValue parses lookup values like [ruleProperty] Returns nil if parsing fails, or a pointer to the matched string if successful

func (*MixinParsers) RuleLookups

func (m *MixinParsers) RuleLookups() []string

RuleLookups parses rule lookups like [ruleProperty]

type NamespaceValue

type NamespaceValue struct {
	*Node
	// contains filtered or unexported fields
}

NamespaceValue represents a namespace value node in the Less AST

func NewNamespaceValue

func NewNamespaceValue(ruleCall any, lookups []string, index int, fileInfo map[string]any) *NamespaceValue

NewNamespaceValue creates a new NamespaceValue instance

func (*NamespaceValue) Eval

func (nv *NamespaceValue) Eval(context any) (any, error)

Eval evaluates the namespace value

func (*NamespaceValue) FileInfo

func (nv *NamespaceValue) FileInfo() map[string]any

FileInfo returns the node's file information

func (*NamespaceValue) GenCSS

func (nv *NamespaceValue) GenCSS(context any, output *CSSOutput)

Note: LessError is now defined in less_error.go with full implementation GenCSS generates CSS by first evaluating the namespace value This ensures errors are properly propagated during CSS generation

func (*NamespaceValue) GetIndex

func (nv *NamespaceValue) GetIndex() int

GetIndex returns the node's index

func (*NamespaceValue) GetType

func (nv *NamespaceValue) GetType() string

GetType returns the node type

func (*NamespaceValue) Type

func (nv *NamespaceValue) Type() string

Type returns the node type (for compatibility)

type Negative

type Negative struct {
	*Node
	Value any
}

Negative represents a negative node in the Less AST

func NewNegative

func NewNegative(node any) *Negative

NewNegative creates a new Negative instance

func (*Negative) Eval

func (n *Negative) Eval(context any) any

func (*Negative) GenCSS

func (n *Negative) GenCSS(context any, output *CSSOutput)

GenCSS generates CSS representation

func (*Negative) GetType

func (n *Negative) GetType() string

GetType returns the type of the node for visitor pattern consistency

func (*Negative) Type

func (n *Negative) Type() string

Type returns the type of the node

type NestableAtRulePrototype

type NestableAtRulePrototype struct {
	*Node
	Type     string
	Features any
	Rules    []any
}

NestableAtRulePrototype represents the prototype functionality for nestable at-rules

func NewNestableAtRulePrototype

func NewNestableAtRulePrototype() *NestableAtRulePrototype

NewNestableAtRulePrototype creates a new NestableAtRulePrototype instance

func (*NestableAtRulePrototype) Accept

func (n *NestableAtRulePrototype) Accept(visitor any)

Accept visits the node with a visitor

func (*NestableAtRulePrototype) BubbleSelectors

func (n *NestableAtRulePrototype) BubbleSelectors(selectors []*Selector)

BubbleSelectors bubbles selectors up the tree

func (*NestableAtRulePrototype) EvalNested

func (n *NestableAtRulePrototype) EvalNested(context any) any

EvalNested evaluates the at-rule in a nested context

func (*NestableAtRulePrototype) EvalTop

func (n *NestableAtRulePrototype) EvalTop(context any) any

EvalTop evaluates the at-rule at the top level

func (*NestableAtRulePrototype) IsRulesetLike

func (n *NestableAtRulePrototype) IsRulesetLike() bool

IsRulesetLike returns true indicating this behaves like a ruleset

func (*NestableAtRulePrototype) Permute

func (n *NestableAtRulePrototype) Permute(arr []any) any

Permute creates permutations of the given array

type Node

type Node struct {
	Parent           *Node
	VisibilityBlocks *int
	NodeVisible      *bool
	RootNode         *Node
	Parsed           any
	Value            any
	Index            int

	Parens     bool
	ParensInOp bool
	TypeIndex  int // Index for visitor pattern lookup
	// contains filtered or unexported fields
}

Node represents a base node in the Less AST

func GetNodeFromPool

func GetNodeFromPool() *Node

func NewNode

func NewNode() *Node

NewNode creates a new Node instance. OPTIMIZATION: Uses sync.Pool to reuse Node objects and reduce GC pressure. Call ReleaseNode when the Node is no longer needed to return it to the pool.

func (*Node) Accept

func (n *Node) Accept(visitor any)

Accept visits the node with a visitor - default implementation

func (*Node) AddVisibilityBlock

func (n *Node) AddVisibilityBlock()

AddVisibilityBlock increments visibility blocks

func (*Node) BlocksVisibility

func (n *Node) BlocksVisibility() bool

BlocksVisibility returns true if the node blocks visibility

func (*Node) ClearVisibilityBlocks

func (n *Node) ClearVisibilityBlocks()

ClearVisibilityBlocks sets visibility blocks to 0

func (*Node) CopyVisibilityInfo

func (n *Node) CopyVisibilityInfo(info map[string]any)

CopyVisibilityInfo copies visibility information from another node

func (*Node) CurrentFileInfo

func (n *Node) CurrentFileInfo() map[string]any

CurrentFileInfo returns the node's file information (getter equivalent)

func (*Node) EnsureInvisibility

func (n *Node) EnsureInvisibility()

EnsureInvisibility sets node visibility to false

func (*Node) EnsureVisibility

func (n *Node) EnsureVisibility()

EnsureVisibility sets node visibility to true

func (*Node) Eval

func (n *Node) Eval(context any) any

Eval evaluates the node - default implementation

func (*Node) FileInfo

func (n *Node) FileInfo() map[string]any

FileInfo returns the node's file information

func (*Node) Fround

func (n *Node) Fround(context any, value float64) float64

Fround rounds a float value based on context precision

func (*Node) GenCSS

func (n *Node) GenCSS(context any, output *CSSOutput)

GenCSS generates CSS representation - default implementation

func (*Node) GenCSSSourceMap

func (n *Node) GenCSSSourceMap(context map[string]any, output *SourceMapOutput)

GenCSSSourceMap implements SourceMapNode interface for Node

func (*Node) GetIndex

func (n *Node) GetIndex() int

GetIndex returns the node's index

func (*Node) GetNode added in v0.4.0

func (n *Node) GetNode() *Node

GetNode returns the Node itself (used for interface compliance in types that embed *Node)

func (*Node) GetTypeIndex

func (n *Node) GetTypeIndex() int

GetTypeIndex returns the node's type index for visitor pattern

func (*Node) IsRulesetLike

func (n *Node) IsRulesetLike() bool

IsRulesetLike returns false for base Node

func (*Node) IsVisible

func (n *Node) IsVisible() *bool

IsVisible returns the node's visibility state

func (*Node) Operate

func (n *Node) Operate(context any, op string, a, b float64) float64

Operate performs arithmetic operations

func (*Node) RemoveVisibilityBlock

func (n *Node) RemoveVisibilityBlock()

RemoveVisibilityBlock decrements visibility blocks

func (*Node) SetFileInfo

func (n *Node) SetFileInfo(info map[string]any)

SetFileInfo sets the node's file information

func (*Node) SetParent

func (n *Node) SetParent(nodes any, parent *Node)

SetParent sets the parent for one or more nodes

func (*Node) ToCSS

func (n *Node) ToCSS(context any) string

ToCSS generates CSS string representation

func (*Node) VisibilityInfo

func (n *Node) VisibilityInfo() map[string]any

VisibilityInfo returns the node's visibility information

type NodeJSPluginBridge

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

NodeJSPluginBridge bridges the runtime.JSPluginLoader with the less_go.PluginLoader interface. It enables the parsing and evaluation pipeline to use JavaScript plugins loaded via Node.js.

func NewNodeJSPluginBridge

func NewNodeJSPluginBridge() (*NodeJSPluginBridge, error)

NewNodeJSPluginBridge creates a new bridge with a fresh Node.js runtime. This should be called once per compilation to spawn a new Node.js process.

func NewNodeJSPluginBridgeWithRuntime

func NewNodeJSPluginBridgeWithRuntime(rt *runtime.NodeJSRuntime) *NodeJSPluginBridge

NewNodeJSPluginBridgeWithRuntime creates a bridge using an existing runtime. This allows sharing the Node.js process across multiple compilations.

func (*NodeJSPluginBridge) AddFunctionToCurrentScope

func (b *NodeJSPluginBridge) AddFunctionToCurrentScope(name string)

AddFunctionToCurrentScope registers a function name at the current scope depth. This is used when re-registering plugin functions inherited from ancestor frames (e.g., when a mixin defined inside a namespace with @plugin is called). The function must already exist in the Node.js runtime - this just makes it visible at the current scope level in BOTH Go and Node.js.

OPTIMIZATION: Only syncs with Node.js when needsScopeSync is true.

func (*NodeJSPluginBridge) CallFunction

func (b *NodeJSPluginBridge) CallFunction(name string, args ...any) (any, error)

CallFunction calls a JavaScript function by name. Only functions visible in the current scope hierarchy can be called.

func (*NodeJSPluginBridge) CallFunctionWithContext

func (b *NodeJSPluginBridge) CallFunctionWithContext(name string, evalContext runtime.EvalContextProvider, args ...any) (any, error)

CallFunctionWithContext calls a JavaScript function by name with evaluation context. This is used by plugin functions that need to access Less variables. The context provides frames and importantScope for variable lookup.

func (*NodeJSPluginBridge) CheckVariableReplacements

func (b *NodeJSPluginBridge) CheckVariableReplacements(variables []VariableInfo) (map[string]map[string]any, error)

CheckVariableReplacements checks which variables should be replaced by pre-eval visitors. Returns a map of variable ID to replacement info.

func (*NodeJSPluginBridge) Close

func (b *NodeJSPluginBridge) Close() error

Close shuts down the Node.js runtime. This should be called when the compilation is complete.

func (*NodeJSPluginBridge) CreateScopedPluginManager

func (b *NodeJSPluginBridge) CreateScopedPluginManager() *runtime.ScopedPluginManager

CreateScopedPluginManager creates a ScopedPluginManager for the current scope. This provides compatibility with the existing PluginManager interface.

func (*NodeJSPluginBridge) EnterScope

func (b *NodeJSPluginBridge) EnterScope() *runtime.PluginScope

EnterScope creates and enters a new child scope. This is used when entering a ruleset or mixin that might have local plugins.

OPTIMIZATION: Only syncs with Node.js when needsScopeSync is true (i.e., when a local plugin was loaded that needs scoping). For global plugins only, we skip IPC entirely for massive performance improvement (~8x faster).

func (*NodeJSPluginBridge) EvalPlugin

func (b *NodeJSPluginBridge) EvalPlugin(contents string, newEnv *Parse, importManager any, pluginArgs map[string]any, newFileInfo any) any

EvalPlugin evaluates plugin contents directly (inline plugin code). This is used when a plugin's JavaScript code is provided inline rather than as a file path.

func (*NodeJSPluginBridge) ExitScope

func (b *NodeJSPluginBridge) ExitScope() *runtime.PluginScope

ExitScope exits the current scope and returns to the parent. Returns the parent scope, or nil if already at root.

OPTIMIZATION: Only syncs with Node.js when needsScopeSync is true.

func (*NodeJSPluginBridge) GetFunctionRegistry

func (b *NodeJSPluginBridge) GetFunctionRegistry() *runtime.PluginFunctionRegistry

GetFunctionRegistry returns the function registry.

func (*NodeJSPluginBridge) GetLoader

func (b *NodeJSPluginBridge) GetLoader() *runtime.JSPluginLoader

GetLoader returns the underlying plugin loader.

func (*NodeJSPluginBridge) GetPostEvalVisitors

func (b *NodeJSPluginBridge) GetPostEvalVisitors() []*runtime.JSVisitor

GetPostEvalVisitors returns post-evaluation visitors from the current scope.

func (*NodeJSPluginBridge) GetPostProcessors

func (b *NodeJSPluginBridge) GetPostProcessors() []*runtime.JSPostProcessor

GetPostProcessors returns all registered post-processors.

func (*NodeJSPluginBridge) GetPreEvalVisitors

func (b *NodeJSPluginBridge) GetPreEvalVisitors() []*runtime.JSVisitor

GetPreEvalVisitors returns pre-evaluation visitors from the current scope.

func (*NodeJSPluginBridge) GetPreProcessors

func (b *NodeJSPluginBridge) GetPreProcessors() []*runtime.JSPreProcessor

GetPreProcessors returns all registered pre-processors.

func (*NodeJSPluginBridge) GetProcessorManager

func (b *NodeJSPluginBridge) GetProcessorManager() *runtime.ProcessorManager

GetProcessorManager returns the processor manager for pre/post processing.

func (*NodeJSPluginBridge) GetRuntime

func (b *NodeJSPluginBridge) GetRuntime() *runtime.NodeJSRuntime

GetRuntime returns the underlying Node.js runtime.

func (*NodeJSPluginBridge) GetScope

func (b *NodeJSPluginBridge) GetScope() *runtime.PluginScope

GetScope returns the current plugin scope.

func (*NodeJSPluginBridge) GetVisitorManager

func (b *NodeJSPluginBridge) GetVisitorManager() *runtime.VisitorManager

GetVisitorManager returns the visitor manager.

func (*NodeJSPluginBridge) GetVisitors

func (b *NodeJSPluginBridge) GetVisitors() []*runtime.JSVisitor

GetVisitors returns all visitors from the current scope. This is used by transform_tree.go to get plugin visitors.

func (*NodeJSPluginBridge) HasFunction

func (b *NodeJSPluginBridge) HasFunction(name string) bool

HasFunction checks if a function exists in the current scope hierarchy. This respects plugin scoping - local plugins are only visible in their scope.

func (*NodeJSPluginBridge) HasPreEvalVisitors

func (b *NodeJSPluginBridge) HasPreEvalVisitors() bool

HasPreEvalVisitors returns true if there are any pre-eval visitors registered.

func (*NodeJSPluginBridge) InitSHMProtocol

func (b *NodeJSPluginBridge) InitSHMProtocol() error

InitSHMProtocol initializes the high-performance shared memory protocol. This should be called once at the start of compilation for best performance. After initialization, plugin function calls will use binary IPC instead of JSON.

func (*NodeJSPluginBridge) LoadPlugin

func (b *NodeJSPluginBridge) LoadPlugin(path, currentDirectory string, context map[string]any, environment any, fileManager any) any

LoadPlugin loads a plugin asynchronously. For now, this just calls LoadPluginSync since we're in a synchronous Go context.

func (*NodeJSPluginBridge) LoadPluginSync

func (b *NodeJSPluginBridge) LoadPluginSync(path, currentDirectory string, context map[string]any, environment any, fileManager any) any

LoadPluginSync synchronously loads a plugin from the specified path. This wraps the runtime.JSPluginLoader and integrates the results with the scope.

func (*NodeJSPluginBridge) LookupFunction

func (b *NodeJSPluginBridge) LookupFunction(name string) (*runtime.JSFunctionDefinition, bool)

LookupFunction looks up a function by name in the current scope. This is used by the function caller during evaluation.

func (*NodeJSPluginBridge) RunPostProcessors

func (b *NodeJSPluginBridge) RunPostProcessors(css string, options map[string]any) (string, error)

RunPostProcessors runs all post-processors on the CSS output.

func (*NodeJSPluginBridge) RunPreEvalVisitorsJSON

func (b *NodeJSPluginBridge) RunPreEvalVisitorsJSON(ast map[string]any) (map[string]any, bool, error)

RunPreEvalVisitorsJSON runs pre-eval visitors on a JSON-serialized AST. Returns the modified AST as a map.

func (*NodeJSPluginBridge) RunPreProcessors

func (b *NodeJSPluginBridge) RunPreProcessors(input string, options map[string]any) (string, error)

RunPreProcessors runs all pre-processors on the input source.

func (*NodeJSPluginBridge) SetScope

func (b *NodeJSPluginBridge) SetScope(scope *runtime.PluginScope)

SetScope sets the current scope directly. This allows restoring a previous scope state.

func (*NodeJSPluginBridge) UseSHMProtocol

func (b *NodeJSPluginBridge) UseSHMProtocol() bool

UseSHMProtocol returns whether the binary SHM protocol is enabled.

type NodePrototype

type NodePrototype struct {
	Type      string
	TypeIndex int
}

func (*NodePrototype) GetPrototype

func (np *NodePrototype) GetPrototype() any

func (*NodePrototype) SetTypeIndex

func (np *NodePrototype) SetTypeIndex(index int)

type NodeVisitor

type NodeVisitor interface {
	Visit(any) any
}

NodeVisitor interface defines the Visit method

type NodeWithOp

type NodeWithOp interface {
	GetOp() string
}

NodeWithOp defines types that have an GetOp method.

type NodeWithParens

type NodeWithParens interface {
	GetParens() bool
}

NodeWithParens defines types that have a GetParens method.

type NodeWithType

type NodeWithType interface {
	GetType() string
}

NodeWithType defines types that have a GetType method.

type NodeWithTypeIndex

type NodeWithTypeIndex interface {
	GetTypeIndex() int
}

type NodeWithValue

type NodeWithValue interface {
	GetValue() any
}

NodeWithValue represents a node that has a value field (like MixinCall args)

type NumberFunctionWrapper

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

NumberFunctionWrapper wraps number functions to implement FunctionDefinition interface

func (*NumberFunctionWrapper) Call

func (w *NumberFunctionWrapper) Call(args ...any) (any, error)

func (*NumberFunctionWrapper) CallCtx

func (w *NumberFunctionWrapper) CallCtx(ctx *Context, args ...any) (any, error)

func (*NumberFunctionWrapper) NeedsEvalArgs

func (w *NumberFunctionWrapper) NeedsEvalArgs() bool

type Operation

type Operation struct {
	*Node
	Op       string
	Operands []any
	IsSpaced bool
}

Operation represents an operation node in the Less AST

func NewOperation

func NewOperation(op string, operands []any, isSpaced bool) *Operation

NewOperation creates a new Operation instance

func (*Operation) Accept

func (o *Operation) Accept(visitor any)

func (*Operation) Eval

func (o *Operation) Eval(context any) (any, error)

func (*Operation) GenCSS

func (o *Operation) GenCSS(context any, output *CSSOutput)

func (*Operation) GetType

func (o *Operation) GetType() string

GetType returns the type of the node for visitor pattern consistency

func (*Operation) Type

func (o *Operation) Type() string

Type returns the type of the node

type Paren

type Paren struct {
	*Node
	Value     any  // This will store the node value
	NoSpacing bool // If true, no space should be added before this paren in output
}

Paren represents a parenthesized value in the Less AST

func NewParen

func NewParen(node any) *Paren

NewParen creates a new Paren instance with the provided node as value

func NewParenWithSpacing added in v0.3.0

func NewParenWithSpacing(node any, noSpacing bool) *Paren

NewParenWithSpacing creates a new Paren instance with explicit spacing control

func (*Paren) Eval

func (p *Paren) Eval(context any) any

func (*Paren) GenCSS

func (p *Paren) GenCSS(context any, output *CSSOutput)

func (*Paren) GetType

func (p *Paren) GetType() string

GetType returns the type of the node for visitor pattern consistency

func (*Paren) ToCSS

func (p *Paren) ToCSS(context any) string

func (*Paren) Type

func (p *Paren) Type() string

Type returns the type of the node

type Parse

type Parse struct {
	Paths           []string
	RewriteUrls     RewriteUrlsType
	Rootpath        string
	StrictImports   bool
	Insecure        bool
	DumpLineNumbers bool
	Compress        bool
	SyncImport      bool
	ChunkInput      bool
	Mime            string
	UseFileCache    bool
	ProcessImports  bool
	PluginManager   any
	Quiet           bool
}

func NewParse

func NewParse(options map[string]any) *Parse

type ParseCallback

type ParseCallback func(error, any, bool, string)

type ParseCallbackFunc

type ParseCallbackFunc func(error, any, *ImportManager, map[string]any)

ParseCallbackFunc represents the callback function signature for parse operations

type ParseFunc

type ParseFunc func(string, map[string]any, ParseCallbackFunc) any

ParseFunc represents the parse function signature returned by the factory

func CreateParse

func CreateParse(environment any, parseTree any, importManagerFactory func(any, *Parse, map[string]any) *ImportManager) ParseFunc

CreateParse creates a parse function with the given dependencies This mirrors the JavaScript export default function(environment, ParseTree, ImportManager)

type ParseNodeCallback

type ParseNodeCallback func(*ParseNodeResult)

ParseNodeCallback is the callback function for parseNode

type ParseNodeResult

type ParseNodeResult struct {
	Error any   // Can be error or boolean true
	Nodes []any // Parsed nodes
}

ParseNodeResult represents the result of a parseNode operation

type ParsePromise

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

ParsePromise represents a basic promise-like structure

func (*ParsePromise) Await

func (p *ParsePromise) Await() (any, error)

Await waits for the promise to complete and returns result and error

func (*ParsePromise) Then

func (p *ParsePromise) Then(onSuccess func(any), onError func(error))

Then provides promise-like then functionality

type ParseResult

type ParseResult struct {
	Error *LessError
	Root  *Ruleset
}

ParseResult represents the result of a parse operation

type ParseTree

type ParseTree struct {
	Root    any
	Imports *ImportManager
	// contains filtered or unexported fields
}

ParseTree represents a Less parse tree that can be converted to CSS

func (*ParseTree) Release added in v0.4.0

func (pt *ParseTree) Release()

Release releases all AST nodes in the parse tree back to their pools. Call this method when you're completely done with the parse tree and won't use it again. This helps reduce memory allocations for subsequent compilations. Note: After calling Release, the ParseTree should not be used again.

func (*ParseTree) ToCSS

func (pt *ParseTree) ToCSS(options *ToCSSOptions) (*ToCSSResult, error)

ToCSS converts the parse tree to CSS

type ParseTreeClass

type ParseTreeClass struct {
	SourceMapBuilder any
}

ParseTreeClass represents the ParseTree class constructor

func DefaultParseTreeFactory

func DefaultParseTreeFactory(sourceMapBuilder any) *ParseTreeClass

DefaultParseTreeFactory creates a default ParseTree factory

func (*ParseTreeClass) NewParseTree

func (ptc *ParseTreeClass) NewParseTree(root any, imports *ImportManager) *ParseTree

NewParseTree creates a new ParseTree instance

type ParseTreeFactory

type ParseTreeFactory func(sourceMapBuilder any) *ParseTreeClass

ParseTreeFactory represents the factory function type that creates ParseTree classes

func NewParseTreeFactory

func NewParseTreeFactory(sourceMapBuilder any) ParseTreeFactory

NewParseTreeFactory creates a factory function for ParseTree

type Parser

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

Parser represents a Less parser instance

func NewParser

func NewParser(context map[string]any, imports map[string]any, fileInfo map[string]any, currentIndex int) *Parser

NewParser creates a new Parser instance

func (*Parser) CreateSelectorParseFunc

func (p *Parser) CreateSelectorParseFunc() SelectorParseFunc

CreateSelectorParseFunc creates a SelectorParseFunc that can be used by selector nodes

func (*Parser) CreateSelectorsParseFunc

func (p *Parser) CreateSelectorsParseFunc() SelectorsParseFunc

CreateSelectorsParseFunc creates a SelectorsParseFunc that can be used by ruleset nodes

func (*Parser) CreateValueParseFunc

func (p *Parser) CreateValueParseFunc() ValueParseFunc

CreateValueParseFunc creates a ValueParseFunc that can be used by ruleset nodes

func (*Parser) Parse

func (p *Parser) Parse(str string, callback func(*LessError, *Ruleset), data *AdditionalData)

Parse parses a Less string using structured AdditionalData

type ParserEvaluable

type ParserEvaluable interface {
	Eval(any) any
}

type ParserFrame

type ParserFrame interface {
	Variable(name string) map[string]any
	Property(name string) []any
}

ParserFrame represents a scope frame that can look up variables and properties

type ParserFunctionCaller

type ParserFunctionCaller interface {
	IsValid() bool
	Call(args []any) (any, error)
}

type ParserInput

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

ParserInput represents the parser input state

func NewParserInput

func NewParserInput() *ParserInput

NewParserInput creates a new ParserInput instance

func (*ParserInput) Char

func (p *ParserInput) Char(tok byte) any

func (*ParserInput) CommentsReset

func (p *ParserInput) CommentsReset()

CommentsReset clears the comment store (equivalent to commentStore.length = 0 in JS)

func (*ParserInput) ConsumeComment

func (p *ParserInput) ConsumeComment() *inputComment

ConsumeComment removes and returns the first comment from the store

func (*ParserInput) CurrentChar

func (p *ParserInput) CurrentChar() byte

func (*ParserInput) End

func (p *ParserInput) End() EndState

func (*ParserInput) Finished

func (p *ParserInput) Finished() bool

Finished returns whether parsing has finished

func (*ParserInput) Forget

func (p *ParserInput) Forget()

func (*ParserInput) GetAutoCommentAbsorb

func (p *ParserInput) GetAutoCommentAbsorb() bool

GetAutoCommentAbsorb returns the current autoCommentAbsorb setting

func (*ParserInput) GetComments

func (p *ParserInput) GetComments() []inputComment

GetComments returns the stored comments

func (*ParserInput) GetIndex

func (p *ParserInput) GetIndex() int

func (*ParserInput) GetInput

func (p *ParserInput) GetInput() string

func (*ParserInput) IsWhitespace

func (p *ParserInput) IsWhitespace(offset int) bool

func (*ParserInput) ParseUntil

func (p *ParserInput) ParseUntil(tok any) any

func (*ParserInput) Peek

func (p *ParserInput) Peek(tok any) bool

func (*ParserInput) PeekChar

func (p *ParserInput) PeekChar(tok byte) any

func (*ParserInput) PeekNotNumeric

func (p *ParserInput) PeekNotNumeric() bool

func (*ParserInput) PrevChar

func (p *ParserInput) PrevChar() byte

func (*ParserInput) Quoted

func (p *ParserInput) Quoted(loc int) any

func (*ParserInput) Re

func (p *ParserInput) Re(tok *regexp.Regexp) any

func (*ParserInput) Remaining added in v0.4.0

func (p *ParserInput) Remaining() string

Remaining returns the remaining unparsed input

func (*ParserInput) Restore

func (p *ParserInput) Restore(possibleErrorMessage string)

func (*ParserInput) Save

func (p *ParserInput) Save()

func (*ParserInput) SetAutoCommentAbsorb

func (p *ParserInput) SetAutoCommentAbsorb(value bool)

SetAutoCommentAbsorb sets the autoCommentAbsorb setting

func (*ParserInput) SetIndex

func (p *ParserInput) SetIndex(index int)

SetIndex sets the current index position

func (*ParserInput) Start

func (p *ParserInput) Start(str string, chunkInput bool, failFunction func(string, int))

func (*ParserInput) Str

func (p *ParserInput) Str(tok string) any

type ParserInterface

type ParserInterface interface {
	Parse(str string, callback func(*LessError, *Ruleset), additionalData *AdditionalData)
}

type ParserLogger

type ParserLogger interface {
	Warn(msg string)
	Error(msg string)
	Info(msg string)
	Debug(msg string)
}

ParserLogger interface for parser logging functionality

type ParserTracer

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

ParserTracer provides runtime debugging and execution tracing for the parser

func GetParserTracer

func GetParserTracer() *ParserTracer

GetParserTracer returns the global tracer instance

func InitParserTracer

func InitParserTracer() *ParserTracer

InitParserTracer initializes the global parser tracer based on environment variables

func (*ParserTracer) GetCallStackString

func (t *ParserTracer) GetCallStackString() string

GetCallStackString returns the current call stack as a string

func (*ParserTracer) IsEnabled

func (t *ParserTracer) IsEnabled() bool

IsEnabled returns whether tracing is enabled

func (*ParserTracer) ShouldTrace

func (t *ParserTracer) ShouldTrace(funcName string) bool

ShouldTrace returns whether a specific function should be traced

func (*ParserTracer) TraceCallStackAt

func (t *ParserTracer) TraceCallStackAt(label string, p *Parser)

TraceCallStackAt logs the call stack at a specific point Use this when you encounter unexpected behavior

func (*ParserTracer) TraceChar

func (t *ParserTracer) TraceChar(funcName string, char byte, matched bool)

TraceChar logs a character match attempt

func (*ParserTracer) TraceCheckpoint

func (t *ParserTracer) TraceCheckpoint(checkpointName string, p *Parser)

TraceCheckpoint logs a checkpoint with the current call stack Use this after successfully parsing major constructs

func (*ParserTracer) TraceEnter

func (t *ParserTracer) TraceEnter(funcName string, p *Parser) func()

TraceEnter logs function entry and returns a cleanup function Usage: defer tracer.TraceEnter("FunctionName", parser)()

func (*ParserTracer) TraceError

func (t *ParserTracer) TraceError(funcName string, errMsg string, p *Parser)

TraceError logs a parser error with stack trace

func (*ParserTracer) TraceMode

func (t *ParserTracer) TraceMode(modeName string, details string, p *Parser)

TraceMode logs parser mode/state information

func (*ParserTracer) TraceRegex

func (t *ParserTracer) TraceRegex(funcName string, pattern string, matched bool, result any)

TraceRegex logs a regex match attempt

func (*ParserTracer) TraceResult

func (t *ParserTracer) TraceResult(funcName string, result any, msg string)

TraceResult logs a parse result (success or nil)

func (*ParserTracer) TraceSaveRestore

func (t *ParserTracer) TraceSaveRestore(operation string, funcName string, p *Parser)

TraceSaveRestore logs parser state operations

type Parsers

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

Parsers contains all the parsing methods

func NewParsers

func NewParsers(parser *Parser) *Parsers

NewParsers creates a new Parsers instance

func (*Parsers) Addition

func (p *Parsers) Addition() any

Addition parses addition and subtraction operations

func (*Parsers) AnonymousValue

func (p *Parsers) AnonymousValue() any

AnonymousValue parses anonymous values for performance

func (*Parsers) AtRule

func (p *Parsers) AtRule() any

AtRule parses at-rules

func (*Parsers) AtomicCondition

func (p *Parsers) AtomicCondition(needsParens bool, preparsedCond any) any

AtomicCondition parses atomic conditions

func (*Parsers) Attribute

func (p *Parsers) Attribute() any

Attribute parses attribute selectors

func (*Parsers) Block

func (p *Parsers) Block() any

Block parses a { ... } block

func (*Parsers) BlockRuleset

func (p *Parsers) BlockRuleset() any

BlockRuleset parses a block and wraps it in a ruleset

func (*Parsers) ColorOperand added in v0.3.1

func (p *Parsers) ColorOperand() any

ColorOperand parses color channel identifiers (l, c, h, r, g, b, s) Used for CSS relative color syntax like oklch(from #0000FF calc(l - 0.1) c h)

func (*Parsers) Combinator

func (p *Parsers) Combinator() *Combinator

Combinator parses selector combinators

func (*Parsers) Comment

func (p *Parsers) Comment() any

Comment parses comments

func (*Parsers) Condition

func (p *Parsers) Condition(needsParens bool) any

Condition parses conditions

func (*Parsers) ConditionAnd

func (p *Parsers) ConditionAnd(needsParens bool) any

ConditionAnd parses AND conditions

func (*Parsers) Conditions

func (p *Parsers) Conditions() any

Conditions parses condition lists

func (*Parsers) Declaration

func (p *Parsers) Declaration() any

Declaration parses property declarations

func (*Parsers) DetachedRuleset

func (p *Parsers) DetachedRuleset() any

DetachedRuleset parses detached rulesets

func (*Parsers) Element

func (p *Parsers) Element() any

Element parses selector elements

func (*Parsers) End

func (p *Parsers) End() bool

End checks for declaration terminators

func (*Parsers) Entity

func (p *Parsers) Entity() any

Entity parses entities

func (*Parsers) Expression

func (p *Parsers) Expression() any

Expression parses expressions

func (*Parsers) Extend

func (p *Parsers) Extend() []any

Extend parses extend rules

func (*Parsers) ExtendRule

func (p *Parsers) ExtendRule() any

ExtendRule parses extend rules

func (*Parsers) IeAlpha

func (p *Parsers) IeAlpha() []any

IeAlpha parses IE alpha function

func (*Parsers) Import

func (p *Parsers) Import() any

Import parses @import rules

func (*Parsers) ImportOptions

func (p *Parsers) ImportOptions() map[string]any

ImportOptions parses import options

func (*Parsers) Important

func (p *Parsers) Important() any

Important parses !important

func (*Parsers) MediaFeature

func (p *Parsers) MediaFeature(syntaxOptions map[string]any) any

MediaFeature parses media features

func (*Parsers) MediaFeatures

func (p *Parsers) MediaFeatures(syntaxOptions map[string]any) any

MediaFeatures parses media features

func (*Parsers) Multiplication

func (p *Parsers) Multiplication() any

Multiplication parses multiplication and division operations

func (*Parsers) NegatedCondition

func (p *Parsers) NegatedCondition(needsParens bool) any

NegatedCondition parses negated conditions

func (*Parsers) NestableAtRule

func (p *Parsers) NestableAtRule() any

NestableAtRule parses nestable at-rules like @media

func (*Parsers) Operand

func (p *Parsers) Operand() any

Operand parses operands for operations

func (*Parsers) ParenthesisCondition

func (p *Parsers) ParenthesisCondition(needsParens bool) any

ParenthesisCondition parses conditions in parentheses

func (*Parsers) PermissiveValue

func (p *Parsers) PermissiveValue(untilTokens *regexp.Regexp, allowComments bool) any

PermissiveValue parses permissive values

func (*Parsers) Plugin

func (p *Parsers) Plugin() any

Plugin parses @plugin directives

func (*Parsers) PluginArgs

func (p *Parsers) PluginArgs() string

PluginArgs parses plugin arguments

func (*Parsers) PrepareAndGetNestableAtRule

func (p *Parsers) PrepareAndGetNestableAtRule(atRuleType string, index int, debugInfo map[string]any) any

PrepareAndGetNestableAtRule handles @media, @container rules

func (*Parsers) Primary

func (p *Parsers) Primary() []any

Primary is the main entry and exit point of the parser

func (*Parsers) Property

func (p *Parsers) Property() any

Property parses property names

func (*Parsers) RuleProperty

func (p *Parsers) RuleProperty() any

RuleProperty parses rule properties

func (*Parsers) Ruleset

func (p *Parsers) Ruleset() any

Ruleset parses CSS rulesets

func (*Parsers) Selector

func (p *Parsers) Selector(isLess bool) any

Selector parses selectors

func (*Parsers) Selectors

func (p *Parsers) Selectors() []any

Selectors parses multiple selectors separated by commas

func (*Parsers) Sub

func (p *Parsers) Sub() any

Sub parses parenthetical expressions Matches Less.js behavior: parses (addition) only, no multi-entity fallback

func (*Parsers) Value

func (p *Parsers) Value() any

Value parses values

func (*Parsers) Variable

func (p *Parsers) Variable() any

Variable parses variable declarations (@var:)

func (*Parsers) VariableCall

func (p *Parsers) VariableCall(parsedName ...string) any

VariableCall parses variable calls parsedName: if provided, indicates we're parsing in a value context (inValue=true)

type Plugin

type Plugin interface {
	Install(less LessInterface, pluginManager *PluginManager, functionRegistry any) error
}

Plugin interface represents the minimal interface a plugin must implement

type PluginCallCollector

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

PluginCallCollector walks the AST and collects all Call nodes that reference JavaScript plugin functions.

func NewPluginCallCollector

func NewPluginCallCollector(pluginFunctionNames []string) *PluginCallCollector

NewPluginCallCollector creates a new collector with the given plugin function names.

func (*PluginCallCollector) Collect

func (c *PluginCallCollector) Collect(root any) []*PluginCallInfo

Collect walks the AST starting from root and collects all plugin function calls.

type PluginCallInfo

type PluginCallInfo struct {
	// FunctionName is the name of the plugin function being called
	FunctionName string

	// Args are the arguments to the function (not yet evaluated)
	Args []any

	// CacheKey is the pre-computed cache key for this call
	CacheKey string
}

PluginCallInfo represents information about a plugin function call collected during AST traversal for cache pre-warming.

type PluginFunctionCaller

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

func (*PluginFunctionCaller) Call

func (c *PluginFunctionCaller) Call(args []any) (any, error)

func (*PluginFunctionCaller) IsValid

func (c *PluginFunctionCaller) IsValid() bool

type PluginFunctionProvider

type PluginFunctionProvider interface {
	LookupPluginFunction(name string) (any, bool)
	HasPluginFunction(name string) bool
	CallPluginFunction(name string, args ...any) (any, error)
}

type PluginLoader

type PluginLoader interface {
	EvalPlugin(contents string, newEnv *Parse, importManager any, pluginArgs map[string]any, newFileInfo any) any
	LoadPluginSync(path, currentDirectory string, context map[string]any, environment any, fileManager any) any
	LoadPlugin(path, currentDirectory string, context map[string]any, environment any, fileManager any) any
}

PluginLoader interface represents the minimal interface needed for plugin loading

type PluginLoaderFactory

type PluginLoaderFactory func(less LessInterface) PluginLoader

PluginLoaderFactory represents a factory function for creating PluginLoader instances

func LazyPluginLoaderFactory

func LazyPluginLoaderFactory(bridge *LazyNodeJSPluginBridge) PluginLoaderFactory

func NodeJSPluginLoaderFactory

func NodeJSPluginLoaderFactory(runtime *runtime.NodeJSRuntime) PluginLoaderFactory

NodeJSPluginLoaderFactory creates a PluginLoaderFactory that returns NodeJSPluginBridge. This can be passed to LessContext to enable JavaScript plugin support.

type PluginManager

type PluginManager struct {
	Loader PluginLoader
	// contains filtered or unexported fields
}

PluginManager manages plugins for the Less system

func NewPluginManager

func NewPluginManager(less LessInterface) *PluginManager

NewPluginManager creates a new PluginManager instance

func PluginManagerFactory

func PluginManagerFactory(less LessInterface, newFactory bool) *PluginManager

PluginManagerFactory creates or returns the global PluginManager instance

func (*PluginManager) AddFileManager

func (pm *PluginManager) AddFileManager(manager any)

AddFileManager adds a file manager

func (*PluginManager) AddPlugin

func (pm *PluginManager) AddPlugin(plugin any, filename string, functionRegistry any)

AddPlugin adds a single plugin

func (*PluginManager) AddPlugins

func (pm *PluginManager) AddPlugins(plugins []any)

AddPlugins adds all the plugins in the slice

func (*PluginManager) AddPostProcessor

func (pm *PluginManager) AddPostProcessor(postProcessor any, priority int)

AddPostProcessor adds a post processor object with priority

func (*PluginManager) AddPreProcessor

func (pm *PluginManager) AddPreProcessor(preProcessor any, priority int)

AddPreProcessor adds a pre processor object with priority

func (*PluginManager) AddVisitor

func (pm *PluginManager) AddVisitor(visitor any)

AddVisitor adds a visitor

func (*PluginManager) Get

func (pm *PluginManager) Get(filename string) any

Get retrieves a cached plugin by filename

func (*PluginManager) GetFileManagers

func (pm *PluginManager) GetFileManagers() []any

GetFileManagers returns the file managers array

func (*PluginManager) GetFunctions

func (pm *PluginManager) GetFunctions() any

GetFunctions returns the functions registry

func (*PluginManager) GetPostProcessors

func (pm *PluginManager) GetPostProcessors() []any

GetPostProcessors returns the array of post processors only

func (*PluginManager) GetPreProcessors

func (pm *PluginManager) GetPreProcessors() []any

GetPreProcessors returns the array of pre processors only

func (*PluginManager) GetVisitors

func (pm *PluginManager) GetVisitors() []any

GetVisitors returns the visitors array

func (*PluginManager) Visitor

func (pm *PluginManager) Visitor() *VisitorIterator

Visitor returns a visitor iterator

type PluginSpec added in v0.1.5

type PluginSpec struct {
	// Name is the plugin name or path
	// Can be: relative path, absolute path, or npm module name
	// NPM modules are resolved with "less-plugin-" prefix first
	Name string

	// Options is an optional string of options to pass to the plugin
	// Passed to the plugin's setOptions() method
	Options string
}

PluginSpec specifies a plugin to load before compilation

type PotentialMatch

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

PotentialMatch represents a potential match during extend processing. This struct replaces map[string]any to reduce allocations.

func (*PotentialMatch) Reset

func (pm *PotentialMatch) Reset()

Reset resets a PotentialMatch for reuse from the pool

type ProcessExtendsVisitor

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

func GetProcessExtendsVisitor

func GetProcessExtendsVisitor() *ProcessExtendsVisitor

GetProcessExtendsVisitor retrieves a ProcessExtendsVisitor from the pool

func NewExtendVisitor

func NewExtendVisitor() *ProcessExtendsVisitor

NewExtendVisitor creates a new extend visitor (alias for NewProcessExtendsVisitor)

func NewProcessExtendsVisitor

func NewProcessExtendsVisitor() *ProcessExtendsVisitor

func (*ProcessExtendsVisitor) IsReplacing

func (pev *ProcessExtendsVisitor) IsReplacing() bool

IsReplacing returns true as ProcessExtendsVisitor is a replacing visitor

func (*ProcessExtendsVisitor) Reset

func (pev *ProcessExtendsVisitor) Reset()

Reset resets the ProcessExtendsVisitor for reuse from the pool. The visitor's methodLookup map is preserved (it's expensive to rebuild).

func (*ProcessExtendsVisitor) Run

func (pev *ProcessExtendsVisitor) Run(root any) any

func (*ProcessExtendsVisitor) VisitAtRule

func (pev *ProcessExtendsVisitor) VisitAtRule(atRuleNode any, visitArgs *VisitArgs)

func (*ProcessExtendsVisitor) VisitAtRuleOut

func (pev *ProcessExtendsVisitor) VisitAtRuleOut(atRuleNode any)

func (*ProcessExtendsVisitor) VisitDeclaration

func (pev *ProcessExtendsVisitor) VisitDeclaration(ruleNode any, visitArgs *VisitArgs)

func (*ProcessExtendsVisitor) VisitMedia

func (pev *ProcessExtendsVisitor) VisitMedia(mediaNode any, visitArgs *VisitArgs)

func (*ProcessExtendsVisitor) VisitMediaOut

func (pev *ProcessExtendsVisitor) VisitMediaOut(mediaNode any)

func (*ProcessExtendsVisitor) VisitMixinDefinition

func (pev *ProcessExtendsVisitor) VisitMixinDefinition(mixinDefinitionNode any, visitArgs *VisitArgs)

func (*ProcessExtendsVisitor) VisitNode

func (pev *ProcessExtendsVisitor) VisitNode(node any, visitArgs *VisitArgs) (any, bool)

VisitNode implements direct dispatch without reflection for better performance

func (*ProcessExtendsVisitor) VisitNodeOut

func (pev *ProcessExtendsVisitor) VisitNodeOut(node any) bool

VisitNodeOut implements direct dispatch for visitOut methods

func (*ProcessExtendsVisitor) VisitRuleset

func (pev *ProcessExtendsVisitor) VisitRuleset(rulesetNode any, visitArgs *VisitArgs)

func (*ProcessExtendsVisitor) VisitSelector

func (pev *ProcessExtendsVisitor) VisitSelector(selectorNode any, visitArgs *VisitArgs)

type ProcessorEntry

type ProcessorEntry struct {
	Processor any
	Priority  int
}

ProcessorEntry represents a processor with its priority

type Promise

type Promise interface {
	Then(onSuccess func(*LoadedFile), onError func(error))
}

type PromiseResult

type PromiseResult struct {
	File  *LoadedFile
	Error error
}

type Property

type Property struct {
	*Node
	// contains filtered or unexported fields
}

Property represents a property node in the Less AST

func NewProperty

func NewProperty(name string, index int, fileInfo map[string]any) *Property

NewProperty creates a new Property instance

func (*Property) Eval

func (p *Property) Eval(context any) (any, error)

Eval evaluates the property in the given context

func (*Property) Find

func (p *Property) Find(arr []any, predicate func(any) any) any

Find searches through an array for the first element that satisfies the predicate

func (*Property) GetName

func (p *Property) GetName() string

GetName returns the property name

func (*Property) GetType

func (p *Property) GetType() string

GetType returns the type of the node

func (*Property) Type

func (p *Property) Type() string

Type returns the type of the node

type QueryInParens

type QueryInParens struct {
	*Node
	// contains filtered or unexported fields
}

QueryInParens represents a query in parentheses node in the Less AST

func NewQueryInParens

func NewQueryInParens(op string, l any, m any, op2 string, r any, i int) *QueryInParens

NewQueryInParens creates a new QueryInParens instance

func (*QueryInParens) Accept

func (q *QueryInParens) Accept(visitor any)

Accept visits the node with a visitor

func (*QueryInParens) Eval

func (q *QueryInParens) Eval(context any) (any, error)

Eval evaluates the query IMPORTANT: This method returns a NEW QueryInParens instance with evaluated values rather than mutating the original. This is critical for mixin expansion where the same QueryInParens node may be evaluated multiple times with different contexts.

func (*QueryInParens) GenCSS

func (q *QueryInParens) GenCSS(context any, output *CSSOutput)

GenCSS generates CSS representation

func (*QueryInParens) GetType

func (q *QueryInParens) GetType() string

GetType returns the type of the node

func (*QueryInParens) Type

func (q *QueryInParens) Type() string

Type returns the type of the node

type Quoted

type Quoted struct {
	*Node
	// contains filtered or unexported fields
}

Quoted represents a quoted string in the Less AST

func E

func E(str interface{}) (*Quoted, error)

E escapes a string value, creating a Quoted with escaped=true

func Format

func Format(stringArg interface{}, args ...interface{}) (*Quoted, error)

Format performs string formatting with %s, %d, %a placeholders

func NewQuoted

func NewQuoted(str string, content string, escaped bool, index int, currentFileInfo map[string]any) *Quoted

NewQuoted creates a new Quoted instance

func Replace

func Replace(stringArg, pattern, replacement interface{}, flags ...interface{}) (*Quoted, error)

Replace performs string replacement using regular expressions

func (*Quoted) Compare

func (q *Quoted) Compare(other any) *int

Compare compares two quoted strings

func (*Quoted) ContainsVariables

func (q *Quoted) ContainsVariables() bool

ContainsVariables checks if the quoted string contains variable interpolations

func (*Quoted) Eval

func (q *Quoted) Eval(context any) (any, error)

Eval evaluates the quoted string, replacing variables and properties

func (*Quoted) FileInfo

func (q *Quoted) FileInfo() map[string]any

FileInfo returns the node's file information

func (*Quoted) GenCSS

func (q *Quoted) GenCSS(context any, output *CSSOutput)

GenCSS generates CSS representation

func (*Quoted) GetEscaped

func (q *Quoted) GetEscaped() bool

GetEscaped returns whether the quoted string is escaped

func (*Quoted) GetIndex

func (q *Quoted) GetIndex() int

GetIndex returns the node's index

func (*Quoted) GetQuote

func (q *Quoted) GetQuote() string

GetQuote returns the quote character used

func (*Quoted) GetType

func (q *Quoted) GetType() string

GetType returns the node type

func (*Quoted) GetValue

func (q *Quoted) GetValue() string

GetValue returns the raw string value of the quoted string

func (*Quoted) ToCSS

func (q *Quoted) ToCSS(context any) string

ToCSS generates CSS string representation

func (*Quoted) Type

func (q *Quoted) Type() string

Type returns the node type

type Registry

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

func (*Registry) Add

func (r *Registry) Add(name string, fn any)

func (*Registry) AddMultiple

func (r *Registry) AddMultiple(functions map[string]any)

func (*Registry) Create

func (r *Registry) Create(base *Registry) *Registry

func (*Registry) Get

func (r *Registry) Get(name string) any

func (*Registry) GetLocalFunctions

func (r *Registry) GetLocalFunctions() map[string]any

func (*Registry) Inherit

func (r *Registry) Inherit() *Registry

type RegistryAdapter

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

func (*RegistryAdapter) Get

type RegistryFunctionAdapter

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

func NewRegistryFunctionAdapter

func NewRegistryFunctionAdapter(registry *Registry) *RegistryFunctionAdapter

func (*RegistryFunctionAdapter) Get

type Releasable added in v0.4.0

type Releasable interface {
	Release()
}

Releasable is an interface for nodes that can be released back to pools

type RenderContext

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

RenderContext represents the bound context for render function

type RenderPromise

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

RenderPromise represents a Promise-like interface that matches JavaScript Promise behavior Unlike the previous implementation, this is synchronous (deferred) like JavaScript, not async

func (*RenderPromise) Await

func (rp *RenderPromise) Await() (any, error)

Await blocks until the promise resolves or rejects (Go-specific helper)

func (*RenderPromise) Catch

func (rp *RenderPromise) Catch(onReject func(error) error) *RenderPromise

Catch simulates JavaScript Promise.catch() behavior

func (*RenderPromise) Then

func (rp *RenderPromise) Then(onResolve func(any) any, onReject func(error) error) *RenderPromise

Then simulates JavaScript Promise.then() behavior

type RewriteUrlsType

type RewriteUrlsType int
const (
	RewriteUrlsOff RewriteUrlsType = iota
	RewriteUrlsLocal
	RewriteUrlsAll
)

type Ruleset

type Ruleset struct {
	*Node
	Selectors     []any
	Rules         []any
	StrictImports bool
	AllowRoot     bool

	// NOTE: rulesets and variableCache were removed - caching these caused stale data
	// issues when Rules are modified during evaluation (mixin expansion, visitors, etc.)
	// Original ruleset reference for eval
	OriginalRuleset *Ruleset
	Root            bool
	// Extend support
	ExtendOnEveryPath bool
	Paths             [][]any
	FirstRoot         bool
	AllowImports      bool
	AllExtends        []*Extend // For storing extends found by ExtendFinderVisitor
	FunctionRegistry  any       // Changed from *functions.Registry to avoid import cycle
	// Parser functions for handling dynamic content
	SelectorsParseFunc SelectorsParseFunc
	ValueParseFunc     ValueParseFunc
	ParseContext       map[string]any
	ParseImports       map[string]any
	// Parse object matching JavaScript structure
	Parse map[string]any // Contains context and importManager
	// Debug info
	DebugInfo any
	// Multi-media flag for nested media queries
	MultiMedia bool
	// InsideMixinDefinition marks rulesets that are nested inside mixin definitions
	// These should not be output directly, only when the mixin is called
	InsideMixinDefinition bool
	// LoadedPluginFunctions stores function names loaded via @plugin in this ruleset's scope
	// This is used for function lookup when this ruleset is in the frames of a mixin call
	LoadedPluginFunctions map[string]bool
	// contains filtered or unexported fields
}

Ruleset represents a ruleset node in the Less AST

func GetRulesetFromPool

func GetRulesetFromPool() *Ruleset

func NewRuleset

func NewRuleset(selectors []any, rules []any, strictImports bool, visibilityInfo map[string]any, parseFuncs ...any) *Ruleset

OPTIMIZATION: Uses sync.Pool to reuse Ruleset objects and reduce GC pressure. Call Release() when the Ruleset is no longer needed to return it to the pool.

func (*Ruleset) Accept

func (r *Ruleset) Accept(visitor any)

func (*Ruleset) Eval

func (r *Ruleset) Eval(context any) (any, error)

func (*Ruleset) EvalImports

func (r *Ruleset) EvalImports(context any) error

EvalImports evaluates import rules like JavaScript version

func (*Ruleset) Find

func (r *Ruleset) Find(selector any, self any, filter func(any) bool) []any

Find finds rules matching a selector like JavaScript version

func (*Ruleset) GenCSS

func (r *Ruleset) GenCSS(context any, output *CSSOutput)

func (*Ruleset) GenCSSSourceMap added in v0.1.4

func (r *Ruleset) GenCSSSourceMap(context map[string]any, output *SourceMapOutput)

GenCSSSourceMap generates CSS with source map information This implements the SourceMapNode interface for source map generation

func (*Ruleset) GetAllExtends

func (r *Ruleset) GetAllExtends() []*Extend

Used by ProcessExtendsVisitor

func (*Ruleset) GetAllowImports

func (r *Ruleset) GetAllowImports() bool

func (*Ruleset) GetFirstRoot

func (r *Ruleset) GetFirstRoot() bool

func (*Ruleset) GetPaths

func (r *Ruleset) GetPaths() []any

func (*Ruleset) GetRoot

func (r *Ruleset) GetRoot() bool

func (*Ruleset) GetRules

func (r *Ruleset) GetRules() []any

Required by ToCSSVisitor

func (*Ruleset) GetSelectors

func (r *Ruleset) GetSelectors() []any

func (*Ruleset) GetType

func (r *Ruleset) GetType() string

func (*Ruleset) GetTypeIndex

func (r *Ruleset) GetTypeIndex() int

func (*Ruleset) HasProperties

func (r *Ruleset) HasProperties() bool

Matches JavaScript rules.properties

func (*Ruleset) HasVariable

func (r *Ruleset) HasVariable(name string) bool

func (*Ruleset) HasVariables

func (r *Ruleset) HasVariables() bool

Matches JavaScript rules.variables

func (*Ruleset) IsRuleset

func (r *Ruleset) IsRuleset() bool

func (*Ruleset) IsRulesetLike

func (r *Ruleset) IsRulesetLike() bool

func (*Ruleset) JoinSelector

func (r *Ruleset) JoinSelector(paths *[][]any, context [][]any, selector any)

JoinSelector joins a single selector with the current context This is a complex method that implements the JavaScript selector joining logic

func (*Ruleset) JoinSelectors

func (r *Ruleset) JoinSelectors(paths *[][]any, context [][]any, selectors []any)

func (*Ruleset) LastDeclaration

func (r *Ruleset) LastDeclaration() any

func (*Ruleset) MakeImportant

func (r *Ruleset) MakeImportant() any

func (*Ruleset) MatchArgs

func (r *Ruleset) MatchArgs(args []any) bool

func (*Ruleset) MatchCondition

func (r *Ruleset) MatchCondition(args []any, context any) bool

func (*Ruleset) ParseValue

func (r *Ruleset) ParseValue(toParse any) any

func (*Ruleset) PrependRule

func (r *Ruleset) PrependRule(rule any)

func (*Ruleset) Properties

func (r *Ruleset) Properties() map[string][]any

func (*Ruleset) Property

func (r *Ruleset) Property(name string) []any

func (*Ruleset) Release

func (r *Ruleset) Release()

func (*Ruleset) ResetCache

func (r *Ruleset) ResetCache()

func (*Ruleset) Rulesets

func (r *Ruleset) Rulesets() []any

func (*Ruleset) SetAllExtends

func (r *Ruleset) SetAllExtends(extends []*Extend)

Used by ExtendFinderVisitor

func (*Ruleset) SetPaths

func (r *Ruleset) SetPaths(paths []any)

func (*Ruleset) SetRoot

func (r *Ruleset) SetRoot(value any)

func (*Ruleset) SetRules

func (r *Ruleset) SetRules(rules []any)

Required by ToCSSVisitor

func (*Ruleset) SetSelectors

func (r *Ruleset) SetSelectors(selectors []any)

Required by JoinSelectorVisitor

func (*Ruleset) ToCSS

func (r *Ruleset) ToCSS(options map[string]any) (string, error)

ToCSS converts the ruleset to CSS output (original signature)

func (*Ruleset) ToCSSString

func (r *Ruleset) ToCSSString(context any) string

ToCSSString converts the ruleset to CSS output (Node interface version)

func (*Ruleset) Type

func (r *Ruleset) Type() string

func (*Ruleset) Variable

func (r *Ruleset) Variable(name string) map[string]any

func (*Ruleset) Variables

func (r *Ruleset) Variables() map[string]any

type SafeIndexError

type SafeIndexError struct {
	Index int
	Len   int
	Msg   string
}

SafeIndexError represents an error when accessing an invalid index

func (*SafeIndexError) Error

func (e *SafeIndexError) Error() string

type Selector

type Selector struct {
	*Node
	Elements       []*Element
	ExtendList     []any // Placeholder for actual type e.g., []*Extend
	Condition      any   // Placeholder for actual type e.g., ConditionNode
	EvaldCondition bool
	MixinElements_ []string // Cached result of MixinElements()
	MediaEmpty     bool
	ParseFunc      SelectorParseFunc // Function for parsing selector strings
	ParseContext   map[string]any    // Context for parser
	ParseImports   map[string]any    // Imports for parser

}

Selector represents a CSS selector.

func GetSelectorFromPool

func GetSelectorFromPool() *Selector

func NewSelector

func NewSelector(elementsInput any, extendList []any, condition any, index int, currentFileInfo map[string]any, visibilityInfo map[string]any, parseFunc ...any) (*Selector, error)

NewSelector creates a new Selector instance. elementsInput can be []*Element, *Element, or string. For backward compatibility, parseFunc, parseContext, and parseImports are optional. OPTIMIZATION: Uses sync.Pool to reuse Selector objects and reduce GC pressure. Call Release() when the Selector is no longer needed to return it to the pool.

func (*Selector) Accept

func (s *Selector) Accept(visitor any)

Accept visits the node with a visitor.

func (*Selector) CreateDerived

func (s *Selector) CreateDerived(elementsInput any, extendList []any, evaldCondition any) (*Selector, error)

CreateDerived creates a new selector derived from the current one. evaldCondition is the evaluated condition node (not a boolean).

func (*Selector) CreateEmptySelectors

func (s *Selector) CreateEmptySelectors() ([]*Selector, error)

CreateEmptySelectors creates a default empty selector.

func (*Selector) Eval

func (s *Selector) Eval(context any) (any, error)

Eval evaluates the selector.

func (*Selector) GenCSS

func (s *Selector) GenCSS(context any, output *CSSOutput)

GenCSS generates the CSS representation of the selector.

func (*Selector) GetExtendList

func (s *Selector) GetExtendList() []*Extend

GetExtendList returns the ExtendList of the selector

func (*Selector) GetIsOutput

func (s *Selector) GetIsOutput() bool

GetIsOutput determines if the selector should be part of the output.

func (*Selector) GetType

func (s *Selector) GetType() string

GetType returns the type of the node for visitor pattern consistency

func (*Selector) IsJustParentSelector

func (s *Selector) IsJustParentSelector() bool

IsJustParentSelector checks if the selector is solely a parent reference (&).

func (*Selector) IsVisible

func (s *Selector) IsVisible() *bool

IsVisible returns whether the selector is visible (for path filtering)

func (*Selector) Match

func (s *Selector) Match(other *Selector) int

Match compares this selector with another.

func (*Selector) MixinElements

func (s *Selector) MixinElements() ([]string, error)

MixinElements gets the string parts of the selector for mixin matching.

func (*Selector) Release

func (s *Selector) Release()

func (*Selector) SetExtendList

func (s *Selector) SetExtendList(extends []*Extend)

SetExtendList sets the extend list for this selector

func (*Selector) ToCSS

func (s *Selector) ToCSS(context any) string

ToCSS generates CSS string representation (overrides Node ToCSS)

func (*Selector) Type

func (s *Selector) Type() string

Type returns the node type.

type SelectorList

type SelectorList struct {
	*Node
	Selectors []any // Contains Selector nodes and Anonymous nodes (for commas)
}

SelectorList represents a list of selectors separated by commas This is used for parenthesized selector lists like :is(.a, .b, .c) where the list contains Selector nodes and Anonymous comma nodes

func NewSelectorList

func NewSelectorList(selectors []any) *SelectorList

NewSelectorList creates a new SelectorList instance

func (*SelectorList) Eval

func (sl *SelectorList) Eval(context any) any

Eval evaluates the selector list and returns a new list with evaluated selectors

func (*SelectorList) GenCSS

func (sl *SelectorList) GenCSS(context any, output *CSSOutput)

GenCSS generates CSS representation

func (*SelectorList) GetType

func (sl *SelectorList) GetType() string

GetType returns the type of the node for visitor pattern consistency

func (*SelectorList) ToCSS

func (sl *SelectorList) ToCSS(context any) string

ToCSS generates a CSS string representation

func (*SelectorList) Type

func (sl *SelectorList) Type() string

Type returns the type of the node

type SelectorParseFunc

type SelectorParseFunc func(input string, context map[string]any, imports map[string]any, fileInfo map[string]any, index int) ([]*Element, error)

SelectorParseFunc is a function type for parsing selector strings This allows dependency injection of parser functionality without circular imports

type SelectorsParseFunc

type SelectorsParseFunc func(input string, context map[string]any, imports map[string]any, fileInfo map[string]any, index int) ([]any, error)

SelectorsParseFunc is a function type for parsing selector strings into selectors

type SetTreeVisibilityVisitor

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

SetTreeVisibilityVisitor implements the visitor pattern to set tree visibility

func GetSetTreeVisibilityVisitor

func GetSetTreeVisibilityVisitor(visible any) *SetTreeVisibilityVisitor

GetSetTreeVisibilityVisitor retrieves a SetTreeVisibilityVisitor from the pool

func NewSetTreeVisibilityVisitor

func NewSetTreeVisibilityVisitor(visible any) *SetTreeVisibilityVisitor

NewSetTreeVisibilityVisitor creates a new SetTreeVisibilityVisitor instance

func (*SetTreeVisibilityVisitor) Reset

func (v *SetTreeVisibilityVisitor) Reset(visible any)

Reset resets the SetTreeVisibilityVisitor for reuse from the pool.

func (*SetTreeVisibilityVisitor) Run

func (v *SetTreeVisibilityVisitor) Run(root any)

Run starts the visitor on the root node

func (*SetTreeVisibilityVisitor) Visit

func (v *SetTreeVisibilityVisitor) Visit(node any) any

Visit visits a single node using type assertions for fast dispatch

func (*SetTreeVisibilityVisitor) VisitArray

func (v *SetTreeVisibilityVisitor) VisitArray(nodes []any) []any

VisitArray visits an array of nodes using type assertions. This method matches the interface expected by Ruleset.Accept: VisitArray([]any) []any

type SimpleFileManager

type SimpleFileManager struct {
	*AbstractFileManager
}

func NewSimpleFileManager

func NewSimpleFileManager() *SimpleFileManager

func (*SimpleFileManager) AlwaysMakePathsAbsolute

func (s *SimpleFileManager) AlwaysMakePathsAbsolute() bool

func (*SimpleFileManager) GetPath

func (s *SimpleFileManager) GetPath(filename string) string

func (*SimpleFileManager) IsPathAbsolute

func (s *SimpleFileManager) IsPathAbsolute(path string) bool

func (*SimpleFileManager) Join

func (s *SimpleFileManager) Join(path1, path2 string) string

func (*SimpleFileManager) LoadFile

func (s *SimpleFileManager) LoadFile(path, currentDirectory string, context map[string]any, environment ImportManagerEnvironment, callback func(error, *LoadedFile)) any

func (*SimpleFileManager) LoadFileSync

func (s *SimpleFileManager) LoadFileSync(path, currentDirectory string, context map[string]any, environment ImportManagerEnvironment) *LoadedFile

type SimpleFunctionDef

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

func (*SimpleFunctionDef) Call

func (s *SimpleFunctionDef) Call(args ...any) (any, error)

func (*SimpleFunctionDef) CallCtx

func (s *SimpleFunctionDef) CallCtx(ctx *Context, args ...any) (any, error)

func (*SimpleFunctionDef) NeedsEvalArgs

func (s *SimpleFunctionDef) NeedsEvalArgs() bool

type SimpleImportManagerEnvironment

type SimpleImportManagerEnvironment struct{}

func (*SimpleImportManagerEnvironment) GetFileManager

func (s *SimpleImportManagerEnvironment) GetFileManager(path, currentDirectory string, context map[string]any, environment ImportManagerEnvironment) FileManager

type SourceMapBuilder

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

func NewSourceMapBuilder

func NewSourceMapBuilder(options SourceMapBuilderOptions) *SourceMapBuilder

func (*SourceMapBuilder) GetExternalSourceMap

func (smb *SourceMapBuilder) GetExternalSourceMap() string

func (*SourceMapBuilder) GetInputFilename

func (smb *SourceMapBuilder) GetInputFilename() string

func (*SourceMapBuilder) GetOutputFilename

func (smb *SourceMapBuilder) GetOutputFilename() string

func (*SourceMapBuilder) GetSourceMapURL

func (smb *SourceMapBuilder) GetSourceMapURL() string

func (*SourceMapBuilder) IsInline

func (smb *SourceMapBuilder) IsInline() bool

func (*SourceMapBuilder) SetExternalSourceMap

func (smb *SourceMapBuilder) SetExternalSourceMap(sourceMap string)

func (*SourceMapBuilder) ToCSS

func (smb *SourceMapBuilder) ToCSS(rootNode SourceMapNode, options map[string]any, imports *Imports, environment SourceMapEnvironment) string

type SourceMapBuilderOptions

type SourceMapBuilderOptions struct {
	SourceMapFilename          string
	SourceMapURL               string
	SourceMapOutputFilename    string
	SourceMapInputFilename     string
	SourceMapBasepath          string
	SourceMapRootpath          string
	OutputSourceFiles          bool
	SourceMapGenerator         any
	SourceMapFileInline        bool
	DisableSourcemapAnnotation bool
}

type SourceMapEnvironment

type SourceMapEnvironment interface {
	EncodeBase64(str string) string
}

type SourceMapGenerator

type SourceMapGenerator interface {
	AddMapping(mapping SourceMapMapping)
	SetSourceContent(source, content string)
	ToJSON() map[string]any
}

type SourceMapMapping

type SourceMapMapping struct {
	Generated SourceMapPosition `json:"generated"`
	Original  SourceMapPosition `json:"original"`
	Source    string            `json:"source"`
}

type SourceMapNode

type SourceMapNode interface {
	GenCSSSourceMap(context map[string]any, output *SourceMapOutput)
}

type SourceMapOptions added in v0.1.4

type SourceMapOptions struct {
	// SourceMapFilename is the name of the source map file
	SourceMapFilename string

	// SourceMapURL overrides the source map URL in the CSS output
	SourceMapURL string

	// SourceMapBasepath is the base path to remove from source paths
	SourceMapBasepath string

	// SourceMapRootpath is the root path to prepend to source paths
	SourceMapRootpath string

	// SourceMapOutputFilename is the output filename for path calculation
	SourceMapOutputFilename string

	// OutputSourceFiles embeds the source content in the source map
	OutputSourceFiles bool

	// SourceMapFileInline embeds the source map as a data URI in the CSS
	SourceMapFileInline bool

	// DisableSourcemapAnnotation disables adding the sourceMappingURL comment
	DisableSourcemapAnnotation bool
}

SourceMapOptions contains source map generation settings

type SourceMapOutput

type SourceMapOutput struct {
	SourceMap string
	// contains filtered or unexported fields
}

func NewSourceMapOutput

func NewSourceMapOutput(options SourceMapOutputOptions) *SourceMapOutput

func (*SourceMapOutput) Add

func (smo *SourceMapOutput) Add(chunk string, fileInfo *FileInfo, index int, mapLines bool)

func (*SourceMapOutput) IsEmpty

func (smo *SourceMapOutput) IsEmpty() bool

func (*SourceMapOutput) NormalizeFilename

func (smo *SourceMapOutput) NormalizeFilename(filename string) string

func (*SourceMapOutput) RemoveBasepath

func (smo *SourceMapOutput) RemoveBasepath(path string) string

func (*SourceMapOutput) ToCSS

func (smo *SourceMapOutput) ToCSS(context map[string]any) string

type SourceMapOutputOptions

type SourceMapOutputOptions struct {
	RootNode                      SourceMapNode
	ContentsMap                   map[string]string
	ContentsIgnoredCharsMap       map[string]int
	SourceMapFilename             string
	OutputFilename                string
	SourceMapURL                  string
	SourceMapBasepath             string
	SourceMapRootpath             string
	OutputSourceFiles             bool
	SourceMapGeneratorConstructor func() SourceMapGenerator
}

type SourceMapPosition

type SourceMapPosition struct {
	Line   int `json:"line"`
	Column int `json:"column"`
}

type StringFunctionWrapper

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

StringFunctionWrapper wraps string functions to implement FunctionDefinition interface

func (*StringFunctionWrapper) Call

func (w *StringFunctionWrapper) Call(args ...any) (any, error)

func (*StringFunctionWrapper) CallCtx

func (w *StringFunctionWrapper) CallCtx(ctx *Context, args ...any) (any, error)

func (*StringFunctionWrapper) NeedsEvalArgs

func (w *StringFunctionWrapper) NeedsEvalArgs() bool

type StyleContext

type StyleContext struct {
	Index           int
	CurrentFileInfo map[string]any
	Context         EvalContext
}

StyleContext represents the context needed for style function execution

type StylizeFunc

type StylizeFunc func(str string, style string) string

type SvgContext

type SvgContext struct {
	Index           int
	CurrentFileInfo map[string]any
	Context         EvalContext
}

SvgContext represents the context needed for svg function execution

type SvgFunctionWrapper

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

SvgFunctionWrapper wraps svg functions to implement FunctionDefinition interface

func (*SvgFunctionWrapper) Call

func (w *SvgFunctionWrapper) Call(args ...any) (any, error)

func (*SvgFunctionWrapper) CallCtx

func (w *SvgFunctionWrapper) CallCtx(ctx *Context, args ...any) (any, error)

func (*SvgFunctionWrapper) NeedsEvalArgs

func (w *SvgFunctionWrapper) NeedsEvalArgs() bool

type ToCSSOptions

type ToCSSOptions struct {
	Compress          bool
	DumpLineNumbers   any
	StrictUnits       bool
	NumPrecision      int
	SourceMap         any
	PluginManager     any
	PluginBridge      any // *LazyNodeJSPluginBridge or *NodeJSPluginBridge for JS plugin function lookup
	Functions         any
	ProcessImports    bool
	ImportManager     any
	RewriteUrls       any      // Can be string ("all", "local", "off") or RewriteUrlsType
	Rootpath          string   // Root path for URL rewriting
	Math              MathType // Math mode for operations (ALWAYS, PARENS_DIVISION, PARENS)
	Paths             []string // Include paths for resolving imports and file references
	UrlArgs           string   // Query string to append to URLs (e.g., "424242")
	JavascriptEnabled bool     // Enable inline JavaScript evaluation
}

ToCSSOptions represents options for CSS conversion

type ToCSSResult

type ToCSSResult struct {
	CSS     string   `json:"css"`
	Map     string   `json:"map,omitempty"`
	Imports []string `json:"imports"`
}

ToCSSResult represents the result of converting a parse tree to CSS

type ToCSSVisitor

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

ToCSSVisitor implements CSS output visitor

func GetToCSSVisitor

func GetToCSSVisitor(context any) *ToCSSVisitor

GetToCSSVisitor retrieves a ToCSSVisitor from the pool and configures it with the given context

func NewToCSSVisitor

func NewToCSSVisitor(context any) *ToCSSVisitor

NewToCSSVisitor creates a new ToCSSVisitor

func (*ToCSSVisitor) CheckValidNodes

func (v *ToCSSVisitor) CheckValidNodes(rules []any, isRoot bool) error

CheckValidNodes checks if nodes are valid for their context

func (*ToCSSVisitor) IsReplacing

func (v *ToCSSVisitor) IsReplacing() bool

IsReplacing returns true as ToCSSVisitor is a replacing visitor

func (*ToCSSVisitor) Reset

func (v *ToCSSVisitor) Reset(context any)

Reset resets the ToCSSVisitor for reuse from the pool. The visitor's methodLookup map is preserved (it's expensive to rebuild).

func (*ToCSSVisitor) Run

func (v *ToCSSVisitor) Run(root any) any

Run runs the visitor on the root node

func (*ToCSSVisitor) VisitAnonymous

func (v *ToCSSVisitor) VisitAnonymous(anonymousNode any, visitArgs *VisitArgs) any

VisitAnonymous visits an anonymous node

func (*ToCSSVisitor) VisitAtRule

func (v *ToCSSVisitor) VisitAtRule(atRuleNode any, visitArgs *VisitArgs) any

VisitAtRule visits an at-rule node

func (*ToCSSVisitor) VisitAtRuleWithBody

func (v *ToCSSVisitor) VisitAtRuleWithBody(atRuleNode any, visitArgs *VisitArgs) any

VisitAtRuleWithBody visits an at-rule with body

func (*ToCSSVisitor) VisitAtRuleWithoutBody

func (v *ToCSSVisitor) VisitAtRuleWithoutBody(atRuleNode any, visitArgs *VisitArgs) any

VisitAtRuleWithoutBody visits an at-rule without body

func (*ToCSSVisitor) VisitComment

func (v *ToCSSVisitor) VisitComment(commentNode any, visitArgs *VisitArgs) any

VisitComment visits a comment node

func (*ToCSSVisitor) VisitContainer

func (v *ToCSSVisitor) VisitContainer(containerNode any, visitArgs *VisitArgs) any

VisitContainer visits a container node (same logic as media)

func (*ToCSSVisitor) VisitDeclaration

func (v *ToCSSVisitor) VisitDeclaration(declNode any, visitArgs *VisitArgs) any

VisitDeclaration visits a declaration node

func (*ToCSSVisitor) VisitExtend

func (v *ToCSSVisitor) VisitExtend(extendNode any, visitArgs *VisitArgs) any

VisitExtend visits an extend node

func (*ToCSSVisitor) VisitImport

func (v *ToCSSVisitor) VisitImport(importNode any, visitArgs *VisitArgs) any

VisitImport visits an import node

func (*ToCSSVisitor) VisitMedia

func (v *ToCSSVisitor) VisitMedia(mediaNode any, visitArgs *VisitArgs) any

VisitMedia visits a media node

func (*ToCSSVisitor) VisitMixinDefinition

func (v *ToCSSVisitor) VisitMixinDefinition(mixinNode any, visitArgs *VisitArgs) any

VisitMixinDefinition visits a mixin definition node

func (*ToCSSVisitor) VisitNode

func (v *ToCSSVisitor) VisitNode(node any, visitArgs *VisitArgs) (any, bool)

VisitNode implements direct dispatch without reflection for better performance

func (*ToCSSVisitor) VisitNodeOut

func (v *ToCSSVisitor) VisitNodeOut(node any) bool

VisitNodeOut implements direct dispatch for visitOut methods

func (*ToCSSVisitor) VisitRuleset

func (v *ToCSSVisitor) VisitRuleset(rulesetNode any, visitArgs *VisitArgs) any

VisitRuleset visits a ruleset node

type ToStringOptions

type ToStringOptions struct {
	Stylize StylizeFunc
}

type TreeRegistry

type TreeRegistry struct {
	NodeTypes map[string]any
}

type TypeFunctionDef

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

TypeFunctionDef wraps type functions to implement FunctionDefinition

func (*TypeFunctionDef) Call

func (t *TypeFunctionDef) Call(args ...any) (any, error)

func (*TypeFunctionDef) CallCtx

func (t *TypeFunctionDef) CallCtx(ctx *Context, args ...any) (any, error)

func (*TypeFunctionDef) NeedsEvalArgs

func (t *TypeFunctionDef) NeedsEvalArgs() bool

type TypesFunctions

type TypesFunctions struct{}

TypesFunctions implements type checking and unit manipulation functions for Less

func NewTypesFunctions

func NewTypesFunctions() *TypesFunctions

func (*TypesFunctions) GetFunctions

func (tf *TypesFunctions) GetFunctions() map[string]any

func (*TypesFunctions) GetUnit

func (tf *TypesFunctions) GetUnit(n any) (*Anonymous, error)

func (*TypesFunctions) IsColor

func (tf *TypesFunctions) IsColor(n any) (*Keyword, error)

func (*TypesFunctions) IsEm

func (tf *TypesFunctions) IsEm(n any) (*Keyword, error)

func (*TypesFunctions) IsKeyword

func (tf *TypesFunctions) IsKeyword(n any) (*Keyword, error)

func (*TypesFunctions) IsNumber

func (tf *TypesFunctions) IsNumber(n any) (*Keyword, error)

func (*TypesFunctions) IsPercentage

func (tf *TypesFunctions) IsPercentage(n any) (*Keyword, error)

func (*TypesFunctions) IsPx

func (tf *TypesFunctions) IsPx(n any) (*Keyword, error)

func (*TypesFunctions) IsRuleset

func (tf *TypesFunctions) IsRuleset(n any) (*Keyword, error)

func (*TypesFunctions) IsString

func (tf *TypesFunctions) IsString(n any) (*Keyword, error)

func (*TypesFunctions) IsURL

func (tf *TypesFunctions) IsURL(n any) (*Keyword, error)

func (*TypesFunctions) IsUnit

func (tf *TypesFunctions) IsUnit(n any, unit any) (*Keyword, error)

func (*TypesFunctions) Unit

func (tf *TypesFunctions) Unit(val any, unit any) (*Dimension, error)

type URL

type URL struct {
	*Node
	Value any // Exported for external access

	IsEvald bool // Exported for external access
	// contains filtered or unexported fields
}

URL represents a URL node in the Less AST

func NewURL

func NewURL(val any, index int, currentFileInfo map[string]any, isEvald bool) *URL

func SvgGradient

func SvgGradient(ctx SvgContext, args ...interface{}) (*URL, error)

SvgGradient implements the svg-gradient() function which creates SVG gradient data URIs

func SvgGradientWithCatch

func SvgGradientWithCatch(ctx SvgContext, args ...interface{}) *URL

SvgGradientWithCatch implements svg-gradient with error handling like the JavaScript version

func (*URL) Accept

func (u *URL) Accept(visitor any)

func (*URL) Eval

func (u *URL) Eval(context any) (any, error)

Eval evaluates the URL - match JavaScript implementation closely

func (*URL) GenCSS

func (u *URL) GenCSS(context any, output *CSSOutput)

func (*URL) GetType

func (u *URL) GetType() string

GetType returns the type of the node for visitor pattern consistency

func (*URL) Type

func (u *URL) Type() string

Type returns the node type to match JavaScript's lowercase 'Url'

type URLParseError

type URLParseError struct {
	URL string
}

func (*URLParseError) Error

func (e *URLParseError) Error() string

type URLParts

type URLParts struct {
	HostPart    string
	Directories []string
	RawPath     string
	Path        string
	Filename    string
	FileURL     string
	URL         string
}

type UnicodeDescriptor

type UnicodeDescriptor struct {
	*Node
	// contains filtered or unexported fields
}

UnicodeDescriptor represents a unicode descriptor node in the Less AST

func NewUnicodeDescriptor

func NewUnicodeDescriptor(value any) *UnicodeDescriptor

func (*UnicodeDescriptor) Accept

func (u *UnicodeDescriptor) Accept(visitor any)

Accept implements the Visitor pattern

func (*UnicodeDescriptor) AddVisibilityBlock

func (u *UnicodeDescriptor) AddVisibilityBlock()

func (*UnicodeDescriptor) BlocksVisibility

func (u *UnicodeDescriptor) BlocksVisibility() bool

func (*UnicodeDescriptor) CopyVisibilityInfo

func (u *UnicodeDescriptor) CopyVisibilityInfo(info map[string]any)

func (*UnicodeDescriptor) EnsureInvisibility

func (u *UnicodeDescriptor) EnsureInvisibility()

func (*UnicodeDescriptor) EnsureVisibility

func (u *UnicodeDescriptor) EnsureVisibility()

func (*UnicodeDescriptor) Eval

Eval returns the UnicodeDescriptor itself (matches JavaScript behavior)

func (*UnicodeDescriptor) FileInfo

func (u *UnicodeDescriptor) FileInfo() map[string]any

func (*UnicodeDescriptor) Fround

func (u *UnicodeDescriptor) Fround(context any, value float64) float64

Fround rounds numbers based on precision (inherited from Node)

func (*UnicodeDescriptor) GenCSS

func (u *UnicodeDescriptor) GenCSS(context any, output *CSSOutput)

func (*UnicodeDescriptor) GetIndex

func (u *UnicodeDescriptor) GetIndex() int

func (*UnicodeDescriptor) GetValue

func (u *UnicodeDescriptor) GetValue() any

func (*UnicodeDescriptor) IsRulesetLike

func (u *UnicodeDescriptor) IsRulesetLike() bool

func (*UnicodeDescriptor) IsVisible

func (u *UnicodeDescriptor) IsVisible() *bool

func (*UnicodeDescriptor) Operate

func (u *UnicodeDescriptor) Operate(context any, op string, a, b float64) float64

Operate performs basic arithmetic operations (inherited from Node)

func (*UnicodeDescriptor) RemoveVisibilityBlock

func (u *UnicodeDescriptor) RemoveVisibilityBlock()

func (*UnicodeDescriptor) SetParent

func (u *UnicodeDescriptor) SetParent(nodes any, parent *Node)

func (*UnicodeDescriptor) SetValue

func (u *UnicodeDescriptor) SetValue(value any)

func (*UnicodeDescriptor) ToCSS

func (u *UnicodeDescriptor) ToCSS(context any) string

func (*UnicodeDescriptor) Type

func (u *UnicodeDescriptor) Type() string

func (*UnicodeDescriptor) VisibilityInfo

func (u *UnicodeDescriptor) VisibilityInfo() map[string]any

type Unit

type Unit struct {
	*Node
	Numerator   []string
	Denominator []string
	BackupUnit  string
}

func GetUnitFromPool

func GetUnitFromPool() *Unit

func NewUnit

func NewUnit(numerator []string, denominator []string, backupUnit string) *Unit

func (*Unit) Cancel

func (u *Unit) Cancel()

func (*Unit) Clone

func (u *Unit) Clone() *Unit

func (*Unit) Compare

func (u *Unit) Compare(other *Unit) int

func (*Unit) GenCSS

func (u *Unit) GenCSS(context any, output *CSSOutput)

func (*Unit) Is

func (u *Unit) Is(unitString string) bool

func (*Unit) IsEmpty

func (u *Unit) IsEmpty() bool

func (*Unit) IsLength

func (u *Unit) IsLength() bool

func (*Unit) IsSingular

func (u *Unit) IsSingular() bool

func (*Unit) Map

func (u *Unit) Map(callback func(string, bool) string)

func (*Unit) Release

func (u *Unit) Release()

func (*Unit) ToCSS

func (u *Unit) ToCSS(context any) string

func (*Unit) ToString

func (u *Unit) ToString() string

func (*Unit) Type

func (u *Unit) Type() string

func (*Unit) UsedUnits

func (u *Unit) UsedUnits() map[string]string

type Value

type Value struct {
	*Node
	Value []any
}

Value represents a value node in the Less AST

func NewValue

func NewValue(value any) (*Value, error)

func (*Value) Accept

func (v *Value) Accept(visitor any)

func (*Value) Eval

func (v *Value) Eval(context any) (any, error)

func (*Value) GenCSS

func (v *Value) GenCSS(context any, output *CSSOutput)

func (*Value) GetType

func (v *Value) GetType() string

func (*Value) GetTypeIndex

func (v *Value) GetTypeIndex() int

func (*Value) GetValue

func (v *Value) GetValue() []any

GetValue returns the value array (for JS serialization compatibility)

func (*Value) ToCSS

func (v *Value) ToCSS(context any) string

func (*Value) Type

func (v *Value) Type() string

type ValueError

type ValueError struct {
	Message string
}

ValueError represents a Less value error

func (*ValueError) Error

func (e *ValueError) Error() string

type ValueParseFunc

type ValueParseFunc func(input string, context map[string]any, imports map[string]any, fileInfo map[string]any, index int) ([]any, error)

ValueParseFunc is a function type for parsing value strings into values

type Variable

type Variable struct {
	*Node
	// contains filtered or unexported fields
}

Variable represents a variable node in the Less AST

func NewVariable

func NewVariable(name string, index int, currentFileInfo map[string]any) *Variable

func Style

func Style(ctx StyleContext, args ...interface{}) (*Variable, error)

Style implements the style() function which creates a Variable from the argument's value and evaluates it

func StyleWithCatch

func StyleWithCatch(ctx StyleContext, args ...interface{}) *Variable

StyleWithCatch implements the style function with error handling like the JavaScript version

func (*Variable) Eval

func (v *Variable) Eval(context any) (any, error)

func (*Variable) FileInfo

func (v *Variable) FileInfo() map[string]any

func (*Variable) GenCSS

func (v *Variable) GenCSS(context any, output *CSSOutput)

func (*Variable) GetIndex

func (v *Variable) GetIndex() int

func (*Variable) GetName

func (v *Variable) GetName() string

func (*Variable) GetType

func (v *Variable) GetType() string

func (*Variable) ToCSS

func (v *Variable) ToCSS(context any) string

func (*Variable) Type

func (v *Variable) Type() string

type VariableCall

type VariableCall struct {
	*Node
	// contains filtered or unexported fields
}

VariableCall represents a variable call node in the Less AST

func NewVariableCall

func NewVariableCall(variable string, index int, currentFileInfo map[string]any) *VariableCall

func (*VariableCall) Eval

func (vc *VariableCall) Eval(context any) (result any, err error)

Eval evaluates the variable call - match JavaScript implementation

func (*VariableCall) FileInfo

func (vc *VariableCall) FileInfo() map[string]any

func (*VariableCall) GetIndex

func (vc *VariableCall) GetIndex() int

func (*VariableCall) GetType

func (vc *VariableCall) GetType() string

func (*VariableCall) Type

func (vc *VariableCall) Type() string

type VariableInfo

type VariableInfo struct {
	ID   string `json:"id"`
	Name string `json:"name"`
}

VariableInfo represents a variable to check for replacement.

type VariableReplacement

type VariableReplacement struct {
	Type  string         `json:"_type"`
	Value string         `json:"value,omitempty"`
	Quote string         `json:"quote,omitempty"`
	RGB   []float64      `json:"rgb,omitempty"`
	Alpha float64        `json:"alpha,omitempty"`
	Unit  string         `json:"unit,omitempty"`
	Props map[string]any `json:"-"`
}

VariableReplacement represents a replacement for a variable.

type VersionInfo

type VersionInfo struct {
	Major int
	Minor int
	Patch int
}

type VisibilityNode

type VisibilityNode interface {
	BlocksVisibility() bool
	EnsureVisibility()
	EnsureInvisibility()
}

VisibilityNode interface for nodes that support visibility operations

type VisitArgs

type VisitArgs struct {
	VisitDeeper bool
}

type VisitFunc

type VisitFunc func(node any, visitArgs *VisitArgs) any

type VisitOutFunc

type VisitOutFunc func(node any)

type Visitor

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

func NewVisitor

func NewVisitor(implementation any) *Visitor

func (*Visitor) Flatten

func (v *Visitor) Flatten(arr []any, out *[]any) []any

func (*Visitor) Visit

func (v *Visitor) Visit(node any) any

func (*Visitor) VisitArray

func (v *Visitor) VisitArray(nodes []any, nonReplacing ...bool) []any

type VisitorIterator

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

VisitorIterator represents an iterator for visitors

func (*VisitorIterator) First

func (vi *VisitorIterator) First() any

func (*VisitorIterator) Get

func (vi *VisitorIterator) Get() any

Get returns the next visitor in the iteration

Directories

Path Synopsis
Package runtime provides JavaScript execution capabilities for LESS plugins.
Package runtime provides JavaScript execution capabilities for LESS plugins.

Jump to

Keyboard shortcuts

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