About Expressions

Beside a ruby programming API, KLayout provides support for simple expressions in some places. In particular this feature is employed to generate dynamic strings, for example when deriving the label text for a ruler.

String interpolation

The feature of inserting dynamic content into a string is called interpolation. The Syntax KLayout uses for string interpolation is a dollar character followed by the expression which is evaluated. Simple expressions can be put directly after the dollar character. Others must be put into brackets.

Every dollar expression is evaluated and the expression is substituted by the result string. For example:

StringEvaluates to
An irrational number: $sqrt(2).An irrational number: 1.4142136
1+2 is $(1+2).1+2 is 3.

String interpolation plays a role where expressions are used to generate dynamic strings. When expressions are used as standalone features (i.e. as parts of a custom layout query - see About Custom Layout Queries), string interpolation is not supported inside string constants, but strings can be built dynamically using the "+" operator.

Basic data types

Expressions use different data types to represent strings or numeric values. The following data types are supported currently:

TypeExamples
Numeric1.2
-0.5e-6
String"abc"
'x'
Booleantrue
false
Array[1,5,4]
Undefined (no value)nil

Apart from that, all RBA objects are supported with their methods (see Class Index). For example, that is a valid expression which gives a value of 100:

Box.new(-10, 0, 90, 60).width

In a boolean context (i.e. the conditional evaluation "condition ? expr1 : expr2"), "nil" and the boolean "false" will render false, while all other values render true. This follows the Ruby convention and in effect, unlike some other languages, a numeric value if 0 is not treated as "false" but as "true"!

Constants

The following constants are defined currently:

ConstantDescription
M_PIThe mathematical constant 'pi'
M_EThe mathematical constant 'e'
false'false' boolean value
true'true' boolean value
nilThe 'undefined' value

Operators and precedence

KLayout's expressions support the following operators with the given precedence:

Prec.OperatorData typesResult typeDescription
1(...)AnyGrouping of sub-expressions
2[...,...]AnyArrayArray formation
3!...BooleanBooleanLogical 'not'
3~...NumericNumericBitwise 'not' (evaluated as 32 bit integers)
3-...NumericNumericNegation
4...^...NumericNumericBitwise 'xor' (evaluated as 32 bit integers)
4...&...NumericNumericBitwise 'and' (evaluated as 32 bit integers)
4...|...NumericNumericBitwise 'or' (evaluated as 32 bit integers)
5...%...NumericNumericModulo
5.../...NumericNumericDivision
5...*...NumericNumericProduct
Numeric*StringStringString multiplication (n times the same string)
6...-...NumericNumericSubtraction
6...+...NumericNumericAddition
StringstringConcatenation
7...<<...NumericNumericBit shift to left
7...>>...NumericNumericBit shift to right
8...==...AnyBooleanEquality
8...!=...AnyBooleanInequality
8...<=...AnyBooleanLess or equal
8...<...AnyBooleanLess
8...>=...AnyBooleanGreater or equal
8...>...AnyBooleanGreater
8...~...StringBooleanMatch with a glob expression
8...!~...StringBooleanNon-match with a glob expression
9...&&...BooleanBooleanLogical 'and'
9...||...BooleanBooleanLogical 'or'
10...?...:...Boolean?Any:AnyAnyConditional evaluation

The match operators work on strings. They use the glob pattern notation (as used in the shell for example) and support substring matching with the usual bracket notation. Substrings can be referred to by "$n" later, where n is the nth bracket. For example:

ExpressionResult
"foo" ~ "f*"true
"foo" ~ "bar"false
"foo" !~ "bar"true
"foo" ~ "f(*)"; $1"oo"

Method calls

Expressions support all the objects provided by KLayout for the Ruby API. Objects are values inside expressions like integers or strings are. Sometimes, objects can be manipulated with the operators as well (like "box1 + box2"). The most important way to work with objects however are methods.

The dot calls a method on an object. Before the dot an expression must be given which results in an object, or a class name must be given. In the latter case, static methods will be called. After the dot, a valid method name is expected.

Important note: the method names used inside expressions usually is equivalent to the names mentioned in the class documentation. Setter methods like "box_with=" can be used as targets in assignments, i.e.

shape.box_width = 20

Boolean predicates (like "is_box?") are used without the question mark because that is reserved for the decision operator (".. ? .. : .."):

shape.is_box

Concatenation of expressions

The semicolon separates two expressions. The value of that compound expression is the value of the last one.

Variables

Depending on the context, some variables may be already defined. For example, when used for generating ruler dimension labels, "D" is a predefined variable that is the length of the ruler. See the specific documentation on these variables.

Inside expressions, variables can be defined to store intermediate results for example. To define a variable use the "var" keyword followed by the variable name and an optional initialisation. Assignment of values can be done with the "=" operator. For example, the following expression gives the result 4:

var x = 3; x = x + 1; x

Special variables

Special variables start with a dollar character. Currently the only special variables available are "$1..9" which is the 1 to 9nth substring match of the last match expression.

Special constants

In the context of a layout, various additional constant expressions are supported:

Distance and area units

A value with a unit is automatically converted to database units. For example, "0.15 um" will give 150 if the database unit of the layout is 1 nm. See below for a list of units available. Supported units are:

UnitDescription
nmNanometers
um, mic, micronMicrometers
mmMillimeters
mMeters
nm2Square nanometers
um2, mic2, micron2Square micrometers
mm2Square millimeters
m2Square meters (for very big chips)

Layer index constants

A layer given in the common notation and enclosed in angle brackets is converted to a layer index. For example: "<16/0>" will be converted to the layer index of the layer with layer number 16 and datatype 0.

Cell index constants

A cell name enclosed in double angle brackets will be converted to the index of that cell, for example "<<TOP>>".

Functions

KLayout's expressions support the following functions:

FunctionData typesResult typeDescription
absolute_file_path(x)StringStringConvert a relative file path to an absolute one
absolute_path(x)StringStringReturns the absolute path component of a file specification
abs(x)NumericNumericReturns the absolute value of a number
acos(x)NumericNumericInverse cosine function
asin(x)NumericNumericInverse sine function
atan2(x,y)NumericNumericInverse tangent of x/y
atan(x)NumericNumericInverse tangent function
basename(x)StringStringReturns the basename component of a file specification
ceil(x)NumericNumericRound up
combine(x,y)StringStringCombines the path components x and y using the system specific separator
cosh(x)NumericNumericHyperbolic cosine function
cos(x)NumericNumericCosine function
env(x)StringStringAccess an environment variable
error(x)StringRaise an error
exp(x)NumericNumericExponential function
extension(x)StringStringReturns the extension component of a file specification
file_exists(x)StringBooleanReturns true if the given file exists
find(s,t)StringNumericFinds the first occurrence of a t in s and returns the position (where 0 is the first character)
floor(x)NumericNumericRound down
gsub(s,x,y)StringStringSubstitute all occurrences of a x in s by y
is_array(x)AnyBooleanTrue if the argument is an array
is_dir(x)StringBooleanReturns true if the given path is a directory
is_nil(x)AnyBooleanTrue if the argument is undefined
is_numeric(x)AnyBooleanTrue if the argument is numeric
is_string(x)AnyBooleanTrue if the argument is a string
item(a,i)ArrayAnyAccess a certain item of an array
join(a,s)Array, StringStringJoin all array members in a into a string using the separator s
len(x)StringNumericReturn the length of a string
log10(x)NumericNumericBase 10 logarithm function
log(x)NumericNumericNatural logarithm function
max(a,b ...)NumericNumericMaximum of the given arguments
min(a,b ...)NumericNumericMinimum of the given arguments
path(x)StringStringReturns the path component of a file specification
pow(x,y)NumericNumericPower function (x to the power of y)
rfind(s,t)StringNumericFinds the last occurrence of a t in s and returns the position (where 0 is the first character)
round(x)NumericNumericRound up or down
sinh(x)NumericNumericHyperbolic sine function
sin(x)NumericNumericSine function
split(t,s)StringArraySplits t into elements using the separator s
sprintf(f,a ...)String, AnyStringImplement of 'C' sprintf. Provides not all features but the most commonly used ones (precision, field width, alignment, zero padding, 'e', 'g', 'f', 'd', 'x', 'u' and 's' formats)
sqrt(x)NumericNumericSquare root
substr(t,f[,l])StringStringReturn a substring of t (starting from position f with length l). 'l' is optional. If omitted, the tail of the string is returned.
sub(s,x,y)StringStringSubstitute the first occurrence of a x in s by y
tanh(x)NumericNumericHyperbolic tangent function
tan(x)NumericNumericTangent function
to_f(x)AnyNumericConvert argument to numeric if possible
to_i(x)AnyNumeric (integer)Convert argument to numeric (32 bit integer)
to_s(x)AnyStringConvert argument to string