SlideShare a Scribd company logo
Tcl Scripting for EDA
Ahmed Abdelazeem
ii © 2024 Abdelazeem
Tcl Scripting for EDA
Never forget the story of Palestine
©2024Abdelazeem iii Tcl Scripting for EDA
Palestinian trail of Blood.
iv © 2024 Abdelazeem
Tcl Scripting for EDA
To the People of Palestine
This work is humbly dedicated to the people of Palestine - to every mother who has buried a child, to every father who has
carried the weight of loss, to every child who has learned the meaning of fear before the meaning of play.
Your courage in the face of cruelty, your steadfastness in the shadow of siege, and your unyielding grip on hope are a
testament to the strength of the human spirit.
You are not forgotten.
Your pain is carried in the hearts of millions, and your story will echo through history until justice calls your name.
May the day come when your skies are free, your lands are whole, and your children know nothing but peace.
©2024Abdelazeem v Tcl Scripting for EDA
vi © 2024 Abdelazeem
Tcl Scripting for EDA
This page intentionally blank
©2024Abdelazeem vii Tcl Scripting for EDA
viii © 2024 Abdelazeem
Tcl Scripting for EDA
©2024Abdelazeem ix Tcl Scripting for EDA
Tcl Scripting for EDA Agenda
Day 1
Introduction to Tcl . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Tcl Basics 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
Tcl Basics 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
Lab 1 - Extracting Bits From Integers
Control Flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Lab 2 - Working with a String Bitstream
Day 2
Lists & Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
Lab 3 - Sorting Design Blocks
File I/O and Program Access . . . . . . . . . . . . . . . . . . . . . . . . . 7
Regular Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
Lab 4 - Netlist Hacking
Tcl in EDA Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
Lab 5 - Working with a Tcl-enabled EDA tool
Next Steps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
Appendices
A - From Scripts to Applications . . . . . . . . . . . . . . . . . . . . . 11
B - Binary Files and Strings. . . . . . . . . . . . . . . . . . . . . . . . . 12
C - Client-Server Allplications and Networking . . . . . . . . . 13
D - Expect - Interacting with Command-Line Programs . 14
Index
Tcl Lab Exercises and Case Studies
x © 2024 Abdelazeem
Tcl Scripting for EDA
1.1
© 2024 Abdelazeem Tcl Training
Tcl Training
Tcl Scripting for EDA
1.2
© 2024 Abdelazeem Tcl Training
Tcl Scripting for EDA (tse1) 1.2
Workshop Overview
• Objectives
– Introduce Tcl
– Understand Tcl uses and strengths
– Learn how to write simple Tcl scripts
– Demonstrate how Tcl can be used for EDA scripting
• Format
– Lectures & labs
– Regular breaks (morning, lunch, and afternoon)
– Interactive classroom, encouraging interruptions & questions,
quizzes
– Difficult concepts explained several times
– Real-world EDA Tcl scripting examples
Welcome to Tcl Scripting Workshop by Abdelazeem!
1.3
Copyright © 2024 Abdelazeem Tcl Training
Tcl Scripting for EDA (tse1) 1.3
Workshop Plan
DAY TWO
List & Arrays
LAB 3: Sorting Design Blocks
File I/O & Program Access
Regular Expressions
LAB 4: VHDL Netlist Hacking
Tcl in EDA tools
LAB 5: Working with a
Tcl-enabled EDA tool
Next Steps
DAY ONE
Introduction to Tcl
Tcl Basics 1 & 2
LAB 1: Extracting Bits from
Integers
Control Flow
Strings
LAB 2: Working with a String
Bitstream
The Workshop material provides additional Appendices covering various
advanced Tcl topics:
• From Scripts to Applications
How do you present, package and distribute your Tcl scripts to your colleagues
and customers? This Appendix covers various Tcl commands useful for building
robust and portable Tcl applications.
• Binary Files and Strings
Summary of Tcl commands and examples for manipulation of binary files and
strings. Tcl can read, write and process these similarly to “ordinary” Tcl strings.
• Client-Server Applications and Networking
Does your application require communication with other programs on the same
machine or over the network? Client-server communication applications can be
built easily with Tcl as this Appendix demonstrates on a practical example.
• Interaction with Command-Line Programs
Does your application require to communicate with old interactive command-line
programs (network clients, test hardware terminals, etc.)? Tcl Expect extension is
an ideal tool for this job. With Expect, any interactive command-line application
can be enhanced to provide Tcl scripting capabilities, allowing automation of many
repetitive tasks. An introduction to Expect is provided in this Appendix.
1.4
Copyright © 2024 Abdelazeem Tcl Training
Tcl Scripting for EDA (tse1) 1.4
Why Tcl?
• Productivity
• Portability
– Ms Windows, UNIX variants, Macintosh, OpenVMS, BeOS, …
• Availability
– Download, use, modify and re-distribute without royalties
• Interfacing between the tools
– Can bridge incompatible interfaces, platforms, distant locations
• Many available extensions
– GUI programming (Tk, Tix, BLT, Togl, ...)
– Interaction with command-line applications (expect, …)
– Database (OraTcl), object-oriented programming ([incr Tcl]), ...
Tcl stands for “Tool Command Language”.
Tcl was originally developed to replace ad-hoc scripting languages used by
research VLSI tools at UC Berkeley. While it started as an EDA scripting
language, Tcl popularity grew fast and today it has been reported to be used in
many different applications ranging from hand-held devices to mission-critical
systems. Tcl is now a mature and very powerful portable scripting language with
many extensions available for various application areas.
Commercial support for Tcl has been provided by a variety of companies,
including Sun Microsystems, Scriptics and at the present day ActiveState
Corporation. Future developments of Tcl are being overseen by an independent
body - a Tcl Core Team.
1.5
Copyright © 2024 Abdelazeem Tcl Training
Tcl Scripting for EDA (tse1) 1.5
Tcl: Main Features
• Rapid application development
• Embeddable
• Extendible
• Flexible integration
• Easy to learn
Tk
Tcl
expect
My
extension
. . .
Tcl
My
application
Application B
(e.g. WinNT)
Application A
(e.g. Solaris)
Tcl
Tcl allows for complex applications to be developed quickly. An interactive nature
of the Tcl development environment provides immediate feedback on the
operation of the developed application.
Tcl scripting can be easily embedded into applications written in C or C++. This
allows for application’s internal functions to become visible as Tcl commands.
Furthermore, build-in Tcl command set provides a powerful facilities for controlling
the execution of these new commands, analysis of data, arithmetic functions, data
input/output and others. This is the approach used by many EDA vendors today.
Tcl was designed to be extendible. New functionality can be added easily by
defining new Tcl commands using Tcl or C/C++..
Tcl is an ideal tool for solving application integration problems, involving for
example incompatible interfaces, different operating systems, applications running
on different machines across the network, etc.
Tcl has a simple syntax and few basic language rules, which makes it easy to
learn.
1.6
Copyright © 2024 Abdelazeem Tcl Training
Tcl Scripting for EDA (tse1) 1.6
Tcl in EDA
• Quickly becoming the standard EDA scripting language
• Typical uses
– simulation, synthesis and test automation scripting
– data analysis and visualization
– design flow integration
– netlist conversion, analysis and hacking
– linking incompatible tools running on different platforms
– scripting front-ends for command-line based applications
– IP core customization scripting
– automated test benches, regression testing, HW/SW co-verification
– portable system demonstrators/applications
– project/EDA system administration (installation, backup, etc.)
Only recently, Tcl was adopted by the EDA industrial community as a “standard”
scripting language for EDA tool scripting. Availability of a common language eases
design tool integration, reduces training costs, but also accelerates EDA tool
development as a common standarized Tcl support may be implemented using
freely downloadable sources.
1.7
Copyright © 2024 Abdelazeem Tcl Training
Tcl Scripting for EDA (tse1) 1.7
Tcl shell (tclsh)
• Command-line interface
– Interactive incremental testing (try & see)
• Available within many modern EDA tools
• Executable file names
– For example for Tcl 8.3: tclsh8.3, tclsh83.exe
– During this course: tclsh
$ tclsh
% puts "Hello world!"
Hello world!
% info commands
tell socket subst open eof pwd glob list exec
pid auto_load_index time unknown eval lrange
fblocked lsearch auto_import ...
% exit
$
$ tclsh
% puts "Hello world!"
Hello world!
% info commands
tell socket subst open eof pwd glob list exec
pid auto_load_index time unknown eval lrange
fblocked lsearch auto_import ...
% exit
$
Command prompt
(UNIX or Ms Windows)
Tcl command
prompt
Standard output (UNIX
terminal)
Leave tclsh
Recognized Tcl
commands
!
!
Try this:
Try this:
This course is based on Tcl version 8.0, which is currently the most common
version available with EDA tools.
You may also come across tools which use Tcl versions 7.6, 8.2 and beyond.
There are significant differences between these versions (new commands and
new command options) and therefore it is advisable to consult tool documentation
for any incompatibilities.
tclsh syntax
tclsh ?fileName arg arg ...?
1.8
Copyright © 2024 Abdelazeem Tcl Training
Tcl Scripting for EDA (tse1) 1.8
$ tclsh
% source my_script.tcl
Hello world!
% !!
Hello world!
...
% exit
$ tclsh
% source my_script.tcl
Hello world!
% !!
Hello world!
...
% exit
$ tclsh my_script.tcl
Hello world!
$ !!
Hello world!
...
$ tclsh my_script.tcl
Hello world!
$ !!
Hello world!
...
1. EDIT
From a UNIX shell:
From a Tcl interpreter:
2. TEST
Working with Tcl scripts (UNIX)
• Interactive & iterative process
Repeat
last UNIX
command
Repeat
last Tcl
command
Writing a Tcl script typically involves an iterative process of editing and testing Tcl
script files. This process is identical for all platforms supported by Tcl.
1.9
Copyright © 2024 Abdelazeem Tcl Training
Tcl Scripting for EDA (tse1) 1.9
C:> tclsh
% source my_script.tcl
Hello world!
% !!
Hello world!
...
% exit
C:> tclsh
% source my_script.tcl
Hello world!
% !!
Hello world!
...
% exit
C:> tclsh my_script.tcl
Hello world!
C:> tclsh my_script.tcl
Hello world!
...
C:> tclsh my_script.tcl
Hello world!
C:> tclsh my_script.tcl
Hello world!
...
1. EDIT
From Command/MSDOS Prompt:
From a Tcl interpreter:
2. TEST
Working with Tcl scripts (Ms Windows)
• Interactive & iterative process
Press
to repeat
last
command
Repeat
last Tcl
command
Or use
↑
↑
While a command-line Tcl interpreter is a typical interface available to an EDA tool
Tcl script writer, there are also other Tcl development tools which provide more
advanced features. One example of such a tool is TclPro, which provides Tcl
debugging, syntax checking, Tcl application packaging and other features. For
more information on TclPro, please visit dev.scriptics.com.
Debugger
controls
Command
stack
Tcl script
display
Breakpoints
Command return
value and error
code
Variable
traces
1.10
Copyright © 2024 Abdelazeem Tcl Training
Tcl Scripting for EDA (tse1) 1.10
Tcl Interpreter in EDA Tools
• Tcl interpreter is typically embedded in your EDA tool
command console (GUI or command line)
– Try invoking info commands in your favourite EDA tool!
HERE
HERE
HERE
HERE
HERE
HERE
Tcl-enabled EDA tools will be discussed in more detail later in this Workshop.
1.11
Copyright © 2024 Abdelazeem Tcl Training
Tcl Scripting for EDA (tse1) 1.11
% info
wrong # args: should be "info option
?arg arg ...?"
% info xyzzy
bad option "xyzzy": should be args,
body, cmdcount, commands, complete,
default, exists, globals, level,
library, locals, patchlevel, procs,
script, tclversion, or vars
% info commands
tell socket subst open eof pwd glob
list exec pid auto_load_index time
unknown eval lrange fblocked lsearch
auto_import
...
% man info
% info
wrong # args: should be "info option
?arg arg ...?"
% info xyzzy
bad option "xyzzy": should be args,
body, cmdcount, commands, complete,
default, exists, globals, level,
library, locals, patchlevel, procs,
script, tclversion, or vars
% info commands
tell socket subst open eof pwd glob
list exec pid auto_load_index time
unknown eval lrange fblocked lsearch
auto_import
...
% man info
Help!
• Command hints and manual pages
UNIX only!
Command-line hints provide quick feedback on the command syntax and available
options. Manual pages are the best source of information for each Tcl command.
They are well written and updated with each release of Tcl distribution.
Manual page browsing using man command works only on UNIX platforms (Tcl
interpreter actually invokes man command from the native UNIX environment). On
UNIX, Tcl manual pages are typically located in section n of the on-line UNIX
manual. You may use -S option to select this section in case of command name
conflict with another UNIX application, for example
man -S n file
will retrieve manual page for Tcl file command and not for the UNIX file
command.
Microsoft Windows users may use Windows help file provided with the Windows
Tcl distribution. The help file contains manual pages identical to those in the UNIX
distribution.
Furthermore, manual pages may be downloaded from
http://dev.scriptics.com/ in HTML format for both platforms.
EDA vendors distribute proprietary documentation for additional Tcl commands
provided by their EDA tools.
1.12
Copyright © 2024 Abdelazeem Tcl Training
Tcl Scripting for EDA (tse1) 1.12
Quiz 1
• What categories of EDA tools support Tcl?
(a) high-level synthesis
(b) HDL simulation
(c) automatic placement & routing
(d) prototyping & testing tools
(e) all of the above
Answer
2.1
Copyright © 2024 Abdelazeem Tcl Training
Tcl Scripting for EDA
Tcl Basics 1
2.2
Copyright © 2024 Abdelazeem Tcl Training
Tcl Basics 1 (tb11) 2.2
Aims and Topics
• Aim
– To familiarize with Tcl syntax and operation of a Tcl interpreter
• Topics
– Tcl syntax
– Variables
– Substitution
– Command evaluation
2.3
Copyright © 2024 Abdelazeem Tcl Training
Tcl Basics 1 (tb11) 2.3
Tcl Commands
• Tcl is CASE SENSITIVE
• Tcl script is composed of “commands”
• Tcl command is composed of “words”
Tcl commands
Tcl script
info commands Enter ↵
info commands
spaces or tabs
separate command words
newline terminates
the command
Command
name
1st
argument
2nd
argument
3rd
argument
...
Tcl interpreter first breaks
the command into words
2.4
Copyright © 2024 Abdelazeem Tcl Training
Tcl Basics 1 (tb11) 2.4
Tcl Script Processing Summary
Word Grouping
Substitution
Command Evaluation
Command Separation
Each line of a Tcl script is processed in four steps indicated above. If you want to
be able to write effective Tcl scripts you need to understand how this process
works.
The previous slide outlined command separation. In the following we will look at
the steps which follow next.
2.5
Copyright © 2024 Abdelazeem Tcl Training
puts "Hello { world! }} "
puts "Hello " world! "" "
puts "Hello " world! " "
puts "Hello "world!" "
puts {Hello { world! }} }
puts {Hello " world! "" }
puts {Hello }world!{ }
puts "Hello { world! }} "
puts "Hello " world! "" "
puts "Hello " world! " "
puts "Hello "world!" "
puts {Hello { world! }} }
puts {Hello " world! "" }
puts {Hello }world!{ }
Tcl Basics 1 (tb11) 2.5
• Use "" or {} to group words together
• ""/{} inside {} and {} inside "" are treated as ordinary
characters
• "" inside "" are pair-matched
Word Grouping With "" and {}
puts "Hello world!"
puts Hello world!
puts {Hello world!}
puts Hello world!
spaces, tabs and newlines
are preserved within "" or {}
quote characters
are discarded
brace characters
are discarded
Note that there are other differences between grouping with "" and {}
(more later!).
Word grouping examples:
puts Hello { world! }}
puts Hello " world! "
SyntaxError!
puts Hello { world! }}
puts Hello " world! ""
SyntaxError!
escape " with a backslash
having a space or a tab might be important!
SyntaxError!
2.6
Copyright © 2024 Abdelazeem Tcl Training
Tcl Basics 1 (tb11) 2.6
# This is a comment
cmdName arg arg arg ...
cmdName arg arg arg ...; cmdName arg arg arg ...
cmdName arg arg arg ...; # This is an inline comment
cmdName arg 
arg arg ...
# Even a comment can be split across multiple 
lines!
# This is a comment
cmdName arg arg arg ...
cmdName arg arg arg ...; cmdName arg arg arg ...
cmdName arg arg arg ...; # This is an inline comment
cmdName arg 
arg arg ...
# Even a comment can be split across multiple 
lines!
Tcl Syntax Summary
• Other elements of Tcl syntax
– Comments start with #
– In-line commands are separated with ;
– All characters with special meaning can be escaped with 
both newline and semicolon (;)
terminate the command
command must be
terminated before
an in-line comment
 Enter ↵
escape a newline to
continue on subsequent
lines
2.7
Copyright © 2024 Abdelazeem Tcl Training
Tcl Basics 1 (tb11) 2.7
Variables
• No need to declare variables
– Use set to create a variable and assign/retrieve its value
– Use unset to delete one or more variables
• Tcl is typeless—variables store STRING values
% set a "Hello world!"
Hello world!
% set a
Hello world!
% set b
can’t read "b": no such variable
% set b 123
123
% unset a b
%
% set a "Hello world!"
Hello world!
% set a
Hello world!
% set b
can’t read "b": no such variable
% set b 123
123
% unset a b
%
assigns Hello world! to variable a and returns this new value
with no value, set returns the value of the named variable
deletes variables a and b from the Tcl interpreter
(deleting variable which wasn’t previously defined is an error)
reading variable which wasn’t previously defined is an error
value 123 is a string containing characters 1, 2 and 3
set and unset syntax
set varName ?value?
unset varName ?varName varName ...?
2.8
Copyright © 2024 Abdelazeem Tcl Training
Tcl Basics 1 (tb11) 2.8
Variable Names and Values
• Variable names
– Are CASE SENSITIVE
– May be composed of ANY characters
• Strings can also represent numeric values:
– Integers: 123 (decimal), 0x7b or 0x7B (hexadecimal), 0173 (octal)
– Real numbers: 3.14159, 1.23e+2 or 1.23E2, 123.0
– Boolean: 0 (false), 1 (true)
% set a 123; set A 456
456
% set a
123
% set !£%^&* "bad idea!"
bad idea!
% set !£%^&*
bad idea!
% set a 123; set A 456
456
% set a
123
% set !£%^&* "bad idea!"
bad idea!
% set !£%^&*
bad idea!
% set reg 0173
0173
% set reg 0x7b
0x7b
% set pi 3.14159
3.14159
% set match_found 1
1
% set reg 0173
0173
% set reg 0x7b
0x7b
% set pi 3.14159
3.14159
% set match_found 1
1
a and A
are
different
variables
in Tcl this is a valid
variable name!
integer (octal)
integer (hex)
real number
Boolean
Use only letters, digits and
underscores in variable
names to maintain
readability!
2.9
Copyright © 2024 Abdelazeem Tcl Training
Tcl Basics 1 (tb11) 2.9
Substitution and Command Evaluation
• After separating commands and word grouping, Tcl
command is processed in further two stages:
Word Grouping
Substitution
Command Evaluation
Command Separation remember me?
variable
command
backslash
2.10
Copyright © 2024 Abdelazeem Tcl Training
Tcl Basics 1 (tb11) 2.10
Substitution
• All command words are searched for special constructs which
trigger substitution
– Words are examined from left to right, character by character
• Each character is processed exactly ONCE
start
$
2.11
Copyright © 2024 Abdelazeem Tcl Training
Tcl Basics 1 (tb11) 2.11
Variable Substitution ($)
• Each occurrence of $varName is replaced with the
corresponding variable value
– Except where $ is escaped ($)
% set d 10; set p 2
2
% puts "Time = $d ns"
Time = 10 ns
% set d 10; set p 2
2
% puts "Time = $d ns"
Time = 10 ns
puts Time = 10 ns
puts Time = $d ns
$d is replaced by its
value (10)
NOTE: word boundaries remain
unchanged!
2.12
Copyright © 2024 Abdelazeem Tcl Training
Tcl Basics 1 (tb11) 2.12
More on Variable Substitution
• Use ${varName} to indicate variable name when
– No space is required after the variable’s value
– Name contains characters other than letters, digits or underscores
• $ followed by a character which is not a letter, digit or
underscore is treated as an ordinary character
⇒Constructs such as $$a are allowed
% puts "Time = $dns"
can’t read ”dns": no such variable
% puts "Time = ${d}ns or $p%"
Time = 10ns or 2%
% puts "This is $!£%^&*"
This is $!£%^&*
% puts "This is a ${!£%^&*}"
This is a bad idea!
% puts "The price is $$d."
The price is $10.
% puts "Time = $dns"
can’t read ”dns": no such variable
% puts "Time = ${d}ns or $p%"
Time = 10ns or 2%
% puts "This is $!£%^&*"
This is $!£%^&*
% puts "This is a ${!£%^&*}"
This is a bad idea!
% puts "The price is $$d."
The price is $10.
use ${} to indicate the variable name
$ is treated as an ordinary character
(doesn’t need to be escaped)
no space after variable’s value
($p% doesn’t need ${}!)
2.13
Copyright © 2024 Abdelazeem Tcl Training
Tcl Basics 1 (tb11) 2.13
Backslash Substitution ()
• Replaces <character> with its substitution equivalent
– Except where  is escaped ()
% puts "Flagt"rst" on"
Flag "rst" on
% puts "Flagt"rst" on"
Flag "rst" on
puts
puts Flagt"rst" on
Flag "rst" on
tab quotes quotes
NOTE: word boundaries remain
unchanged!
2.14
Copyright © 2024 Abdelazeem Tcl Training
Tcl Basics 1 (tb11) 2.14
More on Backslash Substitution
• Backslash substitution can be used to insert
– Special terminal characters
• n (newline), t (tab), b (backspace), a (audible alert), ...
– Any character using its binary value
• x4f or x4F (hexadecimal value), 117 (octal value)
– Escape special characters or just replicate other characters
• $ (dollar),  (backslash), " (quotes), } (brace),  (space)
• i (character i), ...
% puts "Synthesis done. aaa"
Synthesis done.
% puts "ABC = x41102x43"
ABC = ABC
% puts "Some specials: $""
Some specials: $"
% puts "Synthesis done. aaa"
Synthesis done.
% puts "ABC = x41102x43"
ABC = ABC
% puts "Some specials: $""
Some specials: $"
beeps 3 times
inserting binary values into a Tcl string
escaping special characters $, “ and
2.15
Copyright © 2024 Abdelazeem Tcl Training
Tcl Basics 1 (tb11) 2.15
Everyone’s Favourite: The Newline
• Inserting newlines
• Avoiding newlines
– If you don’t want the space, use b
% puts "Line 1nLine 2"
Line 1
Line 2
%
% puts "Line 1nLine 2"
Line 1
Line 2
%
% puts "Line 1
Line 2"
Line 1 Line 2
%
% puts "Line 1
Line 2"
Line 1 Line 2
%
% puts "Line 1
Line 2"
Line 1
Line 2
%
% puts "Line 1
Line 2"
Line 1
Line 2
%
escaped newline + zero or more spaces or tabs are
replaced with a space!
newlines within ""
or {} are reserved
insert a newline with n
% puts "No
bSpace"
NoSpace
%
% puts "No
bSpace"
NoSpace
%
2nd newline inserted
by puts
delete the substituted
space with a backspace
Newlines are very useful for improving readability of user messages, simulation
data, serial bitstream, formatting raw data strings, etc. The above examples
demonstrate some of the typical uses of newlines in Tcl scripts.
2.16
Copyright © 2024 Abdelazeem Tcl Training
Tcl Basics 1 (tb11) 2.16
Command Substitution ([])
• Each occurrence of [<commands>] is replaced with the value
returned from the last command executed in <commands>
– Except where [] are escaped ([ and ])
% set d 10
10
% puts "Time = [set d]ns"
Time = 10ns
% set d 10
10
% puts "Time = [set d]ns"
Time = 10ns
puts
puts Time = [set d]ns
Time = 10ns
NOTE: word boundaries remain
unchanged!
Word Grouping
Substitution
Command Evaluation
Command Separation
10
set d
2.17
Copyright © 2024 Abdelazeem Tcl Training
Tcl Basics 1 (tb11) 2.17
Nested Command Substitution
• Command substitution can be nested
– Each occurrence of [] will trigger a new command substitution
% set a "eggs"
eggs
% puts "Two nested [set b [set a]]"
Two nested eggs
% set a "eggs"
eggs
% puts "Two nested [set b [set a]]"
Two nested eggs
puts "Two nested [set b [set a]]"
puts Two nested eggs
eggs
set a
eggs
set b eggs
set b [set a]
!
"
2.18
Copyright © 2024 Abdelazeem Tcl Training
Tcl Basics 1 (tb11) 2.18
Word Grouping with []
• [] can be used for word grouping too!
– Do not escape word separators and grouping quotes within []
% puts [set b "No [set a "escapes here"]"]
No escapes here
% puts [set b "No [set a "escapes here"]"]
No escapes here
puts [set b "No [set a "escapes here"]"]
puts No escapes here
escapes here
set a "escapes here"
No escapes here
set b "No escapes here"
[] group the argument to puts
!
"
2.19
Copyright © 2024 Abdelazeem Tcl Training
Tcl Basics 1 (tb11) 2.19
Command Evaluation
Word Grouping
Substitution
Command Evaluation
Command Separation
variable
command
backslash
?
2.20
Copyright © 2024 Abdelazeem Tcl Training
Tcl Basics 1 (tb11) 2.20
Command Evaluation
• Tcl interpreter searches for a matching Tcl command
(command name is the 1st word) and then passes all
arguments to it
• Next the command will execute
– Can interpret arguments in any way (strings, numbers, etc.)
• When done, the command will return a result back
to the interpreter
• Commands
– Built-in
– User-defined
puts
No escapes here
No escapes here
puts
set
2.21
Copyright © 2024 Abdelazeem Tcl Training
Tcl Basics 1 (tb11) 2.21
Quiz 2
• What is the value stored in b?
(a) {10}{
(b) 10{ #14
(c) {10}{ #[set c 14]
(d) $a{ #14
(e) {10}{ #14
(f) {$a}{ #[set c 14]
(g) {$a}{ #14
(h) This will generate a syntax error!
set a 10
set b "{$a}{ #[set c 14]"
puts "$b"
set a 10
set b "{$a}{ #[set c 14]"
puts "$b"
space
file: examples/quiz2.tcl
Answer set a 10
set b "{$a}{ #[set c 14]"
Part A: [set c 14] => 14
Part B: {# => { #
Part C: {$a} => {10}
puts "$b"
sol: {10}{ #14
2.22
Copyright © 2024 Abdelazeem Tcl Training
Palestine will live
3.1
Copyright © 2024 Abdelazeem Tcl Training
Tcl Scripting for EDA
Tcl Basics 2
3.2
Copyright © 2024 Abdelazeem Tcl Training
Tcl Basics 2 (tb21) 3.2
Aims and Topics
• Aim
– To learn about using Tcl for arithmetic calculations, basics of file
manipulation and structured scripting
• Topics
– Mathematical operations
– Basic file manipulation
– Basic procedures
3.3
Copyright © 2024 Abdelazeem Tcl Training
Tcl Basics 2 (tb21) 3.3
Mathematical Operations
• Tcl supports all usual operators and functions
• Mathematical
– Arithmetic
– Relational
– Logical
– Bit-wise
– Various functions
• But also
– String pattern matching
– List, array, string manipulation
– File I/O, inter-process, network
– ... (more later)
3.4
Copyright © 2024 Abdelazeem Tcl Training
Tcl Basics 2 (tb21) 3.4
Tcl as a Calculator
• Use expr command to evaluate mathematical expressions
• Use real number strings to invoke real number operators
% expr 1 + 1
2
% set a 10; set b 20
20
% expr $a - $b
-10
% expr {$a - $b}
-10
% expr 1 + 1
2
% set a 10; set b 20
20
% expr $a - $b
-10
% expr {$a - $b}
-10
% expr 9 / 2
4
% expr 9 / 2.0
4.5
% expr 9 / 2
4
% expr 9 / 2.0
4.5
substitution performed only by the
expr command!
$a - $b
expr
integer division
real number division
Enclose the expression
in braces for efficiency
If a variable may contain integers
AND real numbers, consider adding
+ 0.0
in the expression, e.g.
set a [expr {$a + 0.0}]
substitution performed first by the
Tcl interpreter and then by the
expr command
10
expr
- 20
expr syntax
The improved speed of calculation when the expression is enclosed in braces can
be observed even on a simple example above.
expr {$a -$b} executes 7 times faster than expr $a - $b
Try: source examples/expr_speed.tcl
expr arg ?arg arg ...?
Execution time Relative execution time
expr $a - $b 7µs 7
expr {$a -$b} 1µs 1
Tcl 8.0.5 on Pentium III/1GHz PC, 256MB RAM, Windows 2000
3.5
Copyright © 2024 Abdelazeem Tcl Training
Tcl Basics 2 (tb21) 3.5
Available Operators
highest
precedence
lowest
precedence
-a, !a, ~a
a*b, a/b, a%b
a+b, a-b
a<<b, a>>b
a<b, a>b, a<=b, a>=b
a==b, a!=b
a&b
a^b
a|b
a&&b
a||b
a?b:c
• Arithmetic operators accept
integers and reals
• Relational operators accept
integers, reals and strings
• Logical operators accept integers
and reals
– non-zero = true
– zero = false
• Bit-wise operators accept
integers only
• Evaluated from left to right in
the order from highest to lowest
precedence
Operator Description Operands
-a
!a
~a
negative of a
logical NOT: 1 if a is zero, 0 otherwise
bit-wise complement of a
integer, real
integer, real
integer
a*b, a/b
a%b
multiply a and b, divide a by b
remainder after integer division of a by b
integer, real
integer
a+b, a-b add a and b, subtract b from a integer, real
a<<b, a>>b left-shift a by b bits, right-shift a by b bits integer
a<b, a>b,
a<=b, a>=b
1 if the comparison is true: a less than b,
a greater than b, a less than or equal to
b, a greater than or equal to b
integer, real, string
a==b, a!=b 1 if the comparison is true: a is equal to
b, a is not equal to b
integer, real, string
a&b bit-wise AND of a and b integer
a^b bit-wise exclusive OR of a and b integer
a|b bit-wise OR of a and b integer
a&&b logical AND: 1 if both a and b are non-
zero, 0 otherwise
integer, real
a||b logical OR: 1 if either a or b is non-zero,
0 otherwise
integer, real
a?b:c if a is non-zero then evaluates to b,
otherwise evaluates to c
integer, real (for a)
3.6
Copyright © 2024 Abdelazeem Tcl Training
Tcl Basics 2 (tb21) 3.6
Examples: Tcl Operators
% set a 2
2
% expr $a > 0 && $a <= 3
1
% expr !(($a == 1) || ($a == 2))
0
% expr $a || 0
1
% set a 2
2
% expr $a > 0 && $a <= 3
1
% expr !(($a == 1) || ($a == 2))
0
% expr $a || 0
1
OK because > and <= have higher
precedence than &&
Always use parentheses () to
ensure readability.
1 = true
0 = false
non-zero evaluates to true
1st 2nd
3rd
% set a 0x07
0x07
% expr $a & 0x04
4
% set a [expr $a | 0x08]
15
% set a_neg [expr ~$a + 1]
-15
% set a 0x07
0x07
% expr $a & 0x04
4
% set a [expr $a | 0x08]
15
% set a_neg [expr ~$a + 1]
-15
read bit 2
bits 7 6 5 4 3 2 1 0
0000 0111 (7)
AND 0000 0100 (4)
0000 0100 (4)
0000 0111 (7)
OR 0000 1000 (8)
0000 1111 (15)
INV 0000 1111 (15)
1111 0000 (-16)
1111 0001 (-15)
+ 0000 0001 (1)
set bit 3 to 1
change the sign
(2's complement)
NB: equivalent to
set a_neg -$a
% expr "Tcl" == "Tcl"
syntax error in expression "Tcl == Tcl"
% expr {"Tcl" == "Tcl"}
1
% expr {$a > 2.3 ? "over" : "under"}
under
% expr {"TCL" < "Tcl"}
1
% expr {"0x0" == "000"}
1
% expr "Tcl" == "Tcl"
syntax error in expression "Tcl == Tcl"
% expr {"Tcl" == "Tcl"}
1
% expr {$a > 2.3 ? "over" : "under"}
under
% expr {"TCL" < "Tcl"}
1
% expr {"0x0" == "000"}
1
When using strings in expressions:
• enclose strings within "" or {}
• enclose the entire expression in {}
!
Avoid using ==, !=, >, <, >=, <=
for string comparison if the strings
could resemble numerical values!
lexicographical comparison
(Tcl is AFTER TCL, i.e. it has
GREATER index)
% expr $a << 2
60
% expr $a >> 1
7
% expr $a_neg >> 1
-8
% expr $a << 2
60
% expr $a >> 1
7
% expr $a_neg >> 1
-8
shift LEFT by 2 bits
0011 1100 (60)
0001 1110 0
0000 1111 0
shift RIGHT by 1 bit
0000 0111 (7)
0000 1111
right shift always propagates
the sign bit!
1111 1000 (-8)
1111 0001
left shift always inserts 0
3.7
Copyright © 2024 Abdelazeem Tcl Training
Tcl Basics 2 (tb21) 3.7
Mathematical Functions
• These functions can be used INSIDE math expressions
exp(x)
log(x)
log10(x)
pow(x,y)
sqrt(x)
fmod(x,y)
hypot(x,y)
acos(x)
asin(x)
atan(x)
atan2(x,y)
cos(x)
cosh(x)
sin(x)
sinh(x)
tan(x)
tanh(x)
abs(x)
ceil(x)
floor(x)
round(x)
int(x)
double(x)
srand(x)
rand()
expr
Although Tcl was not built as a language for mathematical computations, it
provides a number of useful mathematical functions. All these functions have to
be used inside expressions formed using the expr command (consult expr manual
page for more details on supported functions).
Examples:
% expr sin(3.1415927 / 2.0)
1.0
% expr pow(2, 16)
65536.0
% expr int(pow(2, 16))
65536
% expr ceil(sqrt(2))
2.0
% expr floor(sqrt(2))
1.0
% expr fmod(4.57, 2.0)
0.57
% expr int(rand()*10)
6
% expr sin(3.1415927 / 2.0)
1.0
% expr pow(2, 16)
65536.0
% expr int(pow(2, 16))
65536
% expr ceil(sqrt(2))
2.0
% expr floor(sqrt(2))
1.0
% expr fmod(4.57, 2.0)
0.57
% expr int(rand()*10)
6
π
trigonometric functions expect
arguments in RADIANS
returns real number even when the
arguments are integers...
...but this can be easily converted back to
integer, if needed
returns nearest integer GREATER than √2
returns nearest integer LESS than √2
returns a FLOATING-POINT reminder
after the division of 4.57 by 2.0
returns a random integer in the interval
0-9 (inclusive)
rand() returns a random real number in the interval
0 (inclusive) to 1 (exclusive)
3.8
Copyright © 2024 Abdelazeem Tcl Training
Tcl Basics 2 (tb21) 3.8
Incrementing and Decrementing
• Can be done using expr command...
• ...but Tcl also provides an efficient replacement: incr
% set a 10
10
% set a [expr $a + 1]
11
% set a [expr $a - 5]
6
% set a 10
10
% set a [expr $a + 1]
11
% set a [expr $a - 5]
6
% set a 10
10
% incr a
11
% incr a -5
6
% set a 10
10
% incr a
11
% incr a -5
6
increment constant is optional (defaults to 1)
decrement by using a negative increment constant
incr syntax
Generating random numbers in Tcl:
Random numbers can be used during testing to generate random events or noise
signals. Tcl provides a better number random generator than that provided by a
typical C math library.
Tcl uses a “minimal” generator of Park and Miller with the period of 231
- 2 (around
2.1 x 109
). If you need to generate more than about 1,000,000,000 reliable
random numbers in your scripting application, consider writing your own random
number generator. An excellent reference for various random generation and test
algorithms is Chapter 7 in the following book:
Numerical Recepies in C: The Art of Scientific Computing by W.H.Press et al.,
Cambridge University Press, 1992, second edition, ISBN 0-521-43108-5
incr varName ?increment?
3.9
Copyright © 2024 Abdelazeem Tcl Training
Tcl Basics 2 (tb21) 3.9
• In math calculations, the variable values are converted from
strings to numbers and then back to strings
– Integers are converted accurately
– Real numbers (floating-point)
• Default conversion precision is 12
• Set using the tcl_precision variable
• Internal number representation is platform dependent
– Typically: integer: 32 bits, floating-point: 64 bits
% expr 1.0 / 300.0
0.00333333333333
% set tcl_precision 17
17
% expr 1.0 / 300.0
0.0033333333333333335
% expr 1.0 / 300.0
0.00333333333333
% set tcl_precision 17
17
% expr 1.0 / 300.0
0.0033333333333333335
default floating-point precision is 12
(i.e. 12 significant digits)
with the precision set to 17, the automatic
rounding is DISABLED
Set precision to 17 to avoid loss
of accuracy during the conversion
(assuming IEEE floating-point ALU).
Numerical Accuracy
Tcl interpreter is written in C, therefore the numerical accuracy depends on the
accuracy of underlying C implementation.
Tcl integers are implemented as long C data types and real numbers are
implemented as double C data types.
3.10
Copyright © 2024 Abdelazeem Tcl Training
Tcl Basics 2 (tb21) 3.10
Basic Procedures
• Use proc command to create new Tcl commands
– New commands look and behave just like built-in commands
• Why should I use procedures?
– Store frequently used algorithms (code reuse, productivity gain)
– Structure your scripts (better readability, easier maintenance)
proc name arguments body
% proc average {n1 n2 n3 n4} {
set sum [expr {($n1+$n2+$n3+$n4)/4.0}]
return $sum
}
% average 1 2 3 4
2.5
% average -10 10 -50 3
-11.75
% proc average {n1 n2 n3 n4} {
set sum [expr {($n1+$n2+$n3+$n4)/4.0}]
return $sum
}
% average 1 2 3 4
2.5
% average -10 10 -50 3
-11.75
variables n1, n2, n3, n4
and sum are available only
INSIDE the procedure, i.e
they are local variables
without return
the procedure returns
the value returned by
the last executed
command
proc
average
average
1 2 3 4
3.11
Copyright © 2024 Abdelazeem
Tcl Basics 2 (tb21) 3.11
Global Variables
• Sometimes it is necessary to access variables OUTSIDE the
procedure body
• global command allows to access variables defined at global
scope from inside a procedure body
% set appname "My script"
My script
% proc print_error {msg} {
global appname
puts "$appname: $msg"
}
% set appname "My script"
My script
% proc print_error {msg} {
global appname
puts "$appname: $msg"
}
variable appname is available globally - both
INSIDE and OUTSIDE the procedure.
This is a global variable.
Minimize the use of GLOBAL variables to
improve script readability and to ease the
maintenance.
global syntax global varname ?varname ...?
3.12
Copyright © 2024 Abdelazeem Tcl Training
Tcl Basics 2 (tb21) 3.12
Basic File Manipulation
• Tcl provides portable file system operations
– Print working directory (pwd)
– Change current directory (cd)
– List files and directories matching a pattern (glob)
• Directory separator is / (forward slash) on ALL platforms!
% pwd
% pwd
% glob *
examples labs solutions
% glob examples/*.tcl
bitwidth.tcl hello.tcl ...
% pwd
/home
/home
/use
/use
r
r
s/mil
s/mil
an
an%
cd /esperan/tcl
% cd /abdelazeem/
tcl
% pwd
Abdelazeem
% glob *
examples labs solutions
% glob examples/*.tcl
bitwidth.tcl hello.tcl ...
change to /Abdelazeem/tcl directory (returns no
value)
list ALL files and directories in the current directory
list files and directories with extension .tcl in directory
examples
Syntax for the commands above
glob command and its pattern matching will be covered in more detail in Section 5
- “Strings”
pwd
cd ?dirName?
glob ?switches? pattern ?pattern?
3.13
Copyright © 2024 Abdelazeem Tcl Training
Tcl Basics 2 (tb21) 3.13
Tcl Interpreter Summary
Word Grouping
Substitution
Command Evaluation
Command Separation
variable
command
backslash
cd
set
puts
pwd
glob
average
proc
...
incr
expr
3.14
Copyright © 2024 Abdelazeem Tcl Training
Tcl Basics 2 (tb21) 3.14
Grouping with {} and "" Revisited
• Quotes ("") enable substitution
– [], $,  substitutions performed as usual
• Braces ({}) disable substitution
– No substitutions are performed
– Special substitution characters ([], $, ) are treated as ordinary
characters (no special interpretation)
– BUT escaping the newline character with  is allowed
% set a xyz
xyz
% puts "Substituting as usual: x41, $a,
number = [set b 123]"
Substituting as usual: A, xyz, number = 123
% puts {Substitution disabled: x41, $a,
number = [set b 123]}
Substitution disabled: x41, $a, number = [set b 123]
% set a xyz
xyz
% puts "Substituting as usual: x41, $a,
number = [set b 123]"
Substituting as usual: A, xyz, number = 123
% puts {Substitution disabled: x41, $a,
number = [set b 123]}
Substitution disabled: x41, $a, number = [set b 123]
all substitutions
performed as usual
substitutions disabled,
BUT <newline>
substitution is allowed
3.15
Copyright © 2024 Abdelazeem Tcl Training
Tcl Basics 2 (tb21) 3.15
When Do I Use "" and when Do I Use {}?
• Use "" for
– Quoting string values
– Immediate processing
• Substitutions performed BEFORE the command is executed
• Use {} for
– Avoiding substitution
– Deferred processing
• Delay substitutions until “LATER”
% set cost {$a*0.1 + $b*0.6 + $c*0.3}
$a*0.1 + $b*0.6 + $c*0.3
% set a 100; set b 200; set c 300
300
% expr $cost
220.0
% set cost {$a*0.1 + $b*0.6 + $c*0.3}
$a*0.1 + $b*0.6 + $c*0.3
% set a 100; set b 200; set c 300
300
% expr $cost
220.0
store frequently-used expressions, which
will be used later
evaluate the previously stored
expression with the current
variable values
NOTE: No braces!
use braces to avoid substituting
the values of $a, $b, $c immediately
Note that in the last command, the $cost argument must not be enclosed in
braces! This is because two rounds of substitutions are required to be performed
on the argument to expr. First the Tcl interpreter substitutes $cost for the
expression $a*0.1 + $b*0.6 $c*0.3 and then the expr command substitutes
values for $a, $b and $c.
3.16
Copyright © 2024 Abdelazeem Tcl Training
Tcl Basics 2 (tb21) 3.16
Quiz 3
• What value will print_q and print_b print?
(a) both will print 3
(b) print_q will print 2, print_b will print 3
(c) print_q will print 3, print_b will print 2
(d) both will print 2
% set a 2
2
% proc print_q {a} "puts {Value = $a}"
% proc print_b {a} {puts "Value = $a"}
% print_q 3
Value = ???
% print_b 3
Value = ???
% set a 2
2
% proc print_q {a} "puts {Value = $a}"
% proc print_b {a} {puts "Value = $a"}
% print_q 3
Value = ???
% print_b 3
Value = ???
file: examples/quiz3.tcl
Answer
3.17
Copyright © 2024 Abdelazeem Tcl Training
Tcl Basics 2 (tb21) 3.17
LAB 1: Extracting Bits from Integers
• Using a Tcl interpreter in an interactive mode, extract
4 least significant bits from a positive integer number
between 0 to 15.
• Example:
% set a 9
9
% set b0 [ ... ]
1
...
...
...
% set b "$b3$b2$b1$b0"
1001
% set a 9
9
% set b0 [ ... ]
1
...
...
...
% set b "$b3$b2$b1$b0"
1001
0
0 1
1
...
LSB
insert your code here
% set a 9
9
% set b0 [expr {$a & 1}]
1
% set b1 [expr {($a >> 1) & 1}]
0
% set b2 [expr {($a >> 2) & 1}]
0
% set b3 [expr {($a >> 3) & 1}]
1
% set b "$b3$b2$b1$b0"
1001
3.18
Copyright © 2024 Abdelazeem Tcl Training
Tcl Basics 2 (tb21) 3.18
LAB 1: Extracting Bits from Integers (2)
• Stage 1
– Use expr Tcl command with the following arithmetic operators
$a >> 1 shift content of variable a right by 1 bit
$a & 1 apply bit-wise AND on the contents of variable a to
extract the least significant bit
– Use command substitution []to assign individual bits to four
variables, e.g. b0, b1, b2 and b3, and then store the result in b
– Do NOT use if or other control flow commands (not covered yet)!
• Stage 2
– Store the algorithm as a new Tcl command to_bits (returns the result)
– Print b after the result to indicate binary format, e.g. 1010b
– Print a warning message if the input value is outside the valid 0-15 range
• use the a?b:c operator to test whether input falls within the valid range
# Define the to_bits procedure
proc to_bits {a} {
# Check if the input value is within the valid range 0-15
if {($a < 0) || ($a > 15)} {
puts "Warning: Input value $a is outside the valid range of 0-15"
return
}
# Extract individual bits
set b0 [expr {$a & 1}]
set b1 [expr {($a >> 1) & 1}]
set b2 [expr {($a >> 2) & 1}]
set b3 [expr {($a >> 3) & 1}]
# Concatenate bits to form the binary representation
set b "$b3$b2$b1$b0"
# Print the result in binary format
puts "${b}b"
}
1001
1
-------
1
0100
1
------
0
4.1
Copyright © 2024 Abdelazeem Tcl Training
Tcl Scripting for EDA
Control Flow
4.2
Copyright © 2024 Abdelazeem Tcl Training
Control Flow (tcf1) 4.2
Aims and Topics
• Aim
– To learn how to control command execution in Tcl
• Topics
– What is control flow?
– Conditional commands
– Looping commands
– Loop control
4.3
Copyright © 2024 Abdelazeem Tcl Training
Control Flow (tcf1) 4.3
What is Control Flow?
• A collection of Tcl commands which can be used to control
when and how many times commands are executed
conditionally
execute or skip
commands
repeat
commands
• Conditional command
execution
– if
– switch
• Looping commands
– for
– foreach
– while
• Loop control
– break
– continue
4.4
Copyright © 2024 Abdelazeem Tcl Training
Control Flow (tcf1) 4.4
Conditional Execution: if
• Execute commands IF the condition is true
– Condition is evaluated in the same way as expr expression
– Enclose the condition and if command body in {} unless you require
substitution
if {$area < $area_desired} then {
puts "Desired area constraint met."
}
if {$area < $area_desired} then {
puts "Desired area constraint met."
}
then is optional
condition
if body
Use indentation
to improve readability!
if
condition
1 (true)
0 (false)
if
body
4.5
Copyright © 2024 Abdelazeem Tcl Training
Control Flow (tcf1) 4.5
Conditional Execution: if-else
• Execute if body commands IF the condition is true,
ELSE execute else body
if {$area < $area_desired} then {
puts "Desired area constraint met."
} else {
puts "Area constraint VIOLATED."
}
if {$area < $area_desired} then {
puts "Desired area constraint met."
} else {
puts "Area constraint VIOLATED."
}
else is
optional
else body
if
condition
1 (true)
0 (false)
if
body
else
body
4.6
Copyright © 2024 Abdelazeem Tcl Training
Control Flow (tcf1) 4.6
Conditional Execution: if-elseif-else
• Test for more than one condition with elseif
– Any number of elseif’s can be used
if {$area < $area_desired} then {
puts "Desired area constraint met."
} elseif {$area < $area_max} then {
puts "Maximum area constraint met."
} else {
puts "Area constraints VIOLATED."
}
if {$area < $area_desired} then {
puts "Desired area constraint met."
} elseif {$area < $area_max} then {
puts "Maximum area constraint met."
} else {
puts "Area constraints VIOLATED."
}
then is optional if
condition
1 (true)
0 (false)
if
body
elseif
condition
1 (true)
0 (false)
elseif
body
else
body
Complete if syntax
if expr1 ?then? body1 elseif expr2 ?then? body2 
elseif ... ?else? ?bodyN?
4.7
Copyright © 2024 Abdelazeem Tcl Training
Control Flow (tcf1) 4.7
Conditional Execution: switch
• Useful for command branching
– Similar to if with many elseif’s
• default pattern matches all strings
switch -- $cellName {
AND {incr and_count}
OR {incr or_count}
INV {incr inv_count}
}
switch -- $cellName {
AND {incr and_count}
OR {incr or_count}
INV {incr inv_count}
}
string ==
pattern 1
1 (true)
0 (false)
pattern 1
body
string ==
pattern 2
1 (true)
0 (false)
pattern 2
body
string ==
pattern 3
1 (true)
0 (false)
pattern 3
body
switch -- $cellName {
AND {incr and_count}
OR {incr or_count}
INV {incr inv_count}
default {puts "Unrecognized cell."}
}
switch -- $cellName {
AND {incr and_count}
OR {incr or_count}
INV {incr inv_count}
default {puts "Unrecognized cell."}
}
default
body
-- is optional (more later) string (stored in cellName’s value)
patterns
pattern
bodies
default
must be
the LAST
pattern
Always provide default pattern
to capture unexpected errors.
switch command syntax (variant 1)
The above are trivial examples. Pattern bodies may contain more than one
command.
If default is not the last pattern, it will be matched as an ordinary string "default".
switch ?options? string {pattern1 body1 ?pattern2 body2 ...?}
4.8
Copyright © 2024 Abdelazeem Tcl Training
Control Flow (tcf1) 4.8
Matching Multiple Patterns with switch
• To match several different patterns use ‘-’ separator...
• ...or select how patterns
should be matched:
-exact exactly (default)
-glob glob-style matching
-regexp regular expressions
switch -- $cellName {
AND2 - AND3 {incr and_count}
OR2 -
OR3 {incr or_count}
INV {incr inv_count}
default {puts "Unrecognized cell."}
}
switch -- $cellName {
AND2 - AND3 {incr and_count}
OR2 -
OR3 {incr or_count}
INV {incr inv_count}
default {puts "Unrecognized cell."}
}
switch -glob -- $cellName {
AND* {incr and_count}
OR* {incr or_count}
INV {incr inv_count}
default {
puts "Unrecognized cell."}
}
switch -glob -- $cellName {
AND* {incr and_count}
OR* {incr or_count}
INV {incr inv_count}
default {
puts "Unrecognized cell."}
}
incr and_count will be executed
when $cellName is AND2 or AND3
Use one line for each pattern
to improve readability!
Always use -- to prevent
switch from confusing
strings with options.
match patterns using
glob-style pattern matching
Regular expression pattern matching will be discussed later in Session 8 -
Regular Expressions.
4.9
Copyright © 2024 Abdelazeem Tcl Training
Control Flow (tcf1) 4.9
Changing Patterns during Run-Time
• switch patterns can be changed during run-time!
– DO NOT enclose switch command body in {} to ALLOW
substitution BEFORE the switch command is executed
set hier_path "/DecoderModule/mp3/U*"
switch -glob -- $cellName 
${hier_path}AND* {incr and_count} 
${hier_path}OR* {incr or_count} 
${hier_path}INV {incr inv_count} 
default {puts "Unrecognized cell."}
set hier_path "/DecoderModule/mp3/U*"
switch -glob -- $cellName 
${hier_path}AND* {incr and_count} 
${hier_path}OR* {incr or_count} 
${hier_path}INV {incr inv_count} 
default {puts "Unrecognized cell."}
patterns defined
during run-time
using substitution
newlines
must be
escaped
switch command syntax (variant 2 - allows substitution)
switch matching patterns can be changed during the run-time. For example, the
switch statement above allows to define the path for the cells to be searched for
by changing the value of the hier_path variable.
Patterns searched for in the above command are:
• /DecoderModule/mp3/U*AND*
• /DecoderModule/mp3/U*OR*
• /DecoderModule/mp3/U*INV
switch ?options? string pattern1 body1 ?pattern2 body2 ...?
4.10
Copyright © 2024 Abdelazeem Tcl Training
Control Flow (tcf1) 4.10
Looping: for
• Use for to execute commands specified number of times
– LAB 1 revisited
• test is evaluated in the same way as expr expression
• Enclose start, test, next and body in {} unless you require
substitution
set a 9; set b ""
for {set i 0} {$i < 4} {incr i} {
set bit [expr ($a >> $i) & 0x1]
set b "$bit$b"
}
set a 9; set b ""
for {set i 0} {$i < 4} {incr i} {
set bit [expr ($a >> $i) & 0x1]
set b "$bit$b"
}
evaluate
test
1 (true)
0 (false)
execute
body
execute
start
execute
next
start test next
body
for syntax for start test next body
4.11
Copyright © 2024 Abdelazeem Tcl Training
Control Flow (tcf1) 4.11
Looping: foreach
• Use foreach to execute loop body for each element in a list
– Elements are processed from left to right
– Number of iterations is equal to the number of elements
– using 2 loop variables
% foreach cell $lib_cells {
puts "Found library cell: $cell"
}
Found library cell: INV
Found library cell: AND
Found library cell: OR
%
% foreach cell $lib_cells {
puts "Found library cell: $cell"
}
Found library cell: INV
Found library cell: AND
Found library cell: OR
%
next
element
available
?
1 (true)
0 (false)
assign next
elements to the
loop variables
execute
body
loop variable name list of elements to iterate through
body
% set lib_cells "INV AND OR"
INV AND OR
% set lib_cells "INV AND OR"
INV AND OR
4.12
Copyright © 2024 Abdelazeem Tcl Training
Control Flow (tcf1) 4.12
Multiple Loop Variables with foreach
• Useful for parsing results returned from other commands
% foreach {cell quantity} $cell_counts {
puts "Found library cell: $cell $quantity times"
}
Found library cell: INV 55 times
Found library cell: AND 10 times
Found library cell: OR 20 times
%
% foreach {cell quantity} $cell_counts {
puts "Found library cell: $cell $quantity times"
}
Found library cell: INV 55 times
Found library cell: AND 10 times
Found library cell: OR 20 times
%
two loop variables group loop variables into a single Tcl word
% set cell_counts "INV 55 AND 10 OR 20"
INV 55 AND 10 OR 20
% set cell_counts "INV 55 AND 10 OR 20"
INV 55 AND 10 OR 20
foreach syntax
or for multiple loop variables
foreach varName list body
foreach varList1 list1 ?varList2 list2 ...? body
4.13
Copyright © 2024 Abdelazeem Tcl Training
Control Flow (tcf1) 4.13
Looping: while
• Use while loop to execute commands in a loop which
– Terminates by meeting a certain condition
– Never terminates (indefinite loop)
set number 20
set bits 1
while {(pow(2, $bits) - 1) < $number} {
incr bits
}
set number 20
set bits 1
while {(pow(2, $bits) - 1) < $number} {
incr bits
}
while {1} {
puts "Tcl forever!"
}
while {1} {
puts "Tcl forever!"
}
evaluate
test
1 (true)
0 (false)
execute
body
test
body
while syntax while test body
4.14
Copyright © 2024 Abdelazeem Tcl Training
Control Flow (tcf1) 4.14
Loop Control: break and continue
• Use break to terminate the loop
– Usually used together with conditional commands
• Use continue to advance the loop to the next iteration
immediately
– Skips the rest of the current iteration
while {1} {
puts "Tcl is NOT forever..."
if {rand() > 0.9} {break}
}
while {1} {
puts "Tcl is NOT forever..."
if {rand() > 0.9} {break}
}
foreach cell $lib_cells {
if {$cell == "INV"} {continue}
puts "Found cell with 2+ inputs: $cell"
}
foreach cell $lib_cells {
if {$cell == "INV"} {continue}
puts "Found cell with 2+ inputs: $cell"
}
when rand() > 0.9, terminate
the loop
skip the loop iteration for INV cell
(puts is not executed for INV
cell)
break and continue Tcl commands do not take any arguments.
4.15
Copyright © 2024 Abdelazeem Tcl Training
Control Flow (tcf1) 4.15
Control Flow: Syntax Summary
if {condition} then { for {start} {test} {next} {
body body
} }
if {condition1} then { foreach varName list {
body1 body
} elseif {condition2} { }
body2
} elseif {condition3} {
body3 while {test} {
} body
}
switch string {
pattern1 {body1} break
pattern2 {body2}
pattern3 - continue
pattern4 {body4}
default {default body}
}
if {condition} then { for {start} {test} {next} {
body body
} }
if {condition1} then { foreach varName list {
body1 body
} elseif {condition2} { }
body2
} elseif {condition3} {
body3 while {test} {
} body
}
switch string {
pattern1 {body1} break
pattern2 {body2}
pattern3 - continue
pattern4 {body4}
default {default body}
}
Group conditions,
tests and bodies with
{} unless you
require substitution.
match pattern3 OR pattern4
if present,
default must be the LAST pattern
terminate the loop
skip the current
iteration
4.16
Copyright © 2024 Abdelazeem Tcl Training
Control Flow (tcf1) 4.16
if {$a > 0} {puts "positive"}
if {$a > 0} {
puts "positive"
}
if {$a > 0} {puts "positive"}
if {$a > 0} {
puts "positive"
} else {
puts "negative"
}
if {$a > 0} {puts "positive"}
if {$a > 0} {
puts "positive"
}
if {$a > 0} {puts "positive"}
if {$a > 0} {
puts "positive"
} else {
puts "negative"
}
Braces & Spaces (Grouping Mistakes)
WRONG RIGHT
if {$a > 0} puts "positive"
if {$a > 0}{
puts "positive"
}
if $a > 0 {puts "positive"}
if {$a > 0} {
puts "positive"
}
else {
puts "negative"
}
if {$a > 0} puts "positive"
if {$a > 0}{
puts "positive"
}
if $a > 0 {puts "positive"}
if {$a > 0} {
puts "positive"
}
else {
puts "negative"
}
body NOT
grouped!
TWO
commands!
missing space
between }{ !
condition NOT grouped!
Use braces and you
won't need to worry
about spaces!
4.17
Copyright © 2024 Abdelazeem Tcl Training
Control Flow (tcf1) 4.17
Quiz 4
• What is the value of a ?
(a) 150
(b) 100
(c) 140
(d) 300
(e) 200
set a 0
while {$a < 150} {
incr a
switch $a {
100 {continue}
140 {set a 300}
200 {break}
}
}
puts "Value of a = $a"
set a 0
while {$a < 150} {
incr a
switch $a {
100 {continue}
140 {set a 300}
200 {break}
}
}
puts "Value of a = $a"
file:
examples/quiz4.tcl
Answer
1. Initialization:
set a 0: Initializes a to 0.
2. While Loop:
while {$a < 150}: The loop continues as long as a is less than 150.
incr a: Increments the value of a by 1 in each iteration.
3. Switch Statement:
switch $a checks the value of a and performs the following actions:
100 {continue}: If a is 100, it uses the continue command, which skips the rest of the loop iteration
and starts the next iteration.
140 {set a 300}: If a is 140, it sets a to 300. This will cause the while loop to terminate because a is
no longer less than 150.
200 {break}: If a is 200 (which it won't be in this case because the loop stops when a is set to 300), it
would break out of the loop.
4. Output:
puts "Value of a = $a": Prints the final value of a.
4.18
Copyright © 2024 Abdelazeem Tcl Training
Never...
5.1
Copyright © 2024 Abdelazeem Tcl Training
Tcl Scripting for EDA
Strings
5.2
Copyright © 2024 Abdelazeem Tcl Training
Strings (tst1) 5.2
Aims and Topics
• Aim
– To learn about how to work with strings in Tcl
• Topics
– Constructing strings
– String operations
– Extracting information from strings
– Binary strings
5.3
Copyright © 2024 Abdelazeem Tcl Training
Strings (tst1) 5.3
What is a String?
• Any collection of characters
– Letters, digits, special characters, binary characters, etc.
• In Tcl, everything is a string
– Universal data type from/to which everything can be converted
– Easy to manipulate
!
d
l
r
o
H
e
l l o
w
5.4
Copyright © 2024 Abdelazeem Tcl Training
Strings (tst1) 5.4
Constructing Strings
• Strings in Tcl can be constructed in a variety of ways
– Typing the string characters
– Substitution and set
– Tcl append command
• append command is optimised for speed
% set a "Hello"; set b "world";
world
% set c "$a $b!"
Hello world!
% append d $a " " $b "!"
Hello world!
% set a "Hello"; set b "world";
world
% set c "$a $b!"
Hello world!
% append d $a " " $b "!"
Hello world!
% set test_files
test/test0.tcl ... test/test9999.tcl
% foreach f $test_files {append test_script "source $fn"}
% set test_script
source test/test0.tcl
...
source test/test9999.tcl
% set test_files
test/test0.tcl ... test/test9999.tcl
% foreach f $test_files {append test_script "source $fn"}
% set test_script
source test/test0.tcl
...
source test/test9999.tcl
variable d will be created
if it doesn't exist
Use append when constructing
long strings!
append syntax
It might seem that there is no justification for having append, when the same effect
can be achieved using substitution. However, the append command is significantly
faster when constructing long strings. In the above example, if the body of the
foreach loop is replaced with
set test_script "${test_script}source $fn"
the loop will be 200 times slower!
Try: source examples/append_vs_set.tcl
append varName ?value value ...?
Execution time Relative execution time
substitution 7.76s 204
append 38.1ms 1
Tcl 8.0.5 on Pentium III/1GHz PC, 256MB RAM, Windows 2000
5.5
Copyright © 2024 Abdelazeem Tcl Training
Strings (tst1) 5.5
• Can be done with ==, but this can fail when string characters
resemble numbers
• Use string compare instead (robust string comparison)
• Return value:
0 strings str1 and str2 are IDENTICAL
1 string str1 is lexicographically AFTER string str2
-1 string str1 is lexicographically BEFORE string str2
% expr {"0x0" == "000"}
1
% expr {"0x0" == "000"}
1
!
% expr {[string compare "0x0" "000"] == 0}
0
% expr {[string compare "0x0" "000"] == 0}
0
Comparing Strings
string compare syntax
string compare str1 str2
5.6
Copyright © 2024 Abdelazeem Tcl Training
Strings (tst1) 5.6
• Similar to comparison, but allows the first string to contain
match patterns
• Return value:
0 pattern does NOT match string
1 pattern matches string
String Matching
% string match "*/mp3/*" "/DecoderModule/mp3/U4"
1
% string match "*/mp3/*" "/DecoderModule/mpeg2/U12"
0
% string match "*/mp3/*" "/DecoderModule/mp3/U4"
1
% string match "*/mp3/*" "/DecoderModule/mpeg2/U12"
0
string match pattern string
glob-style match pattern
5.7
Copyright © 2024 Abdelazeem Tcl Training
Strings (tst1) 5.7
Glob-style Match Patterns
• glob-style patterns are similar to UNIX shell wildchar
patterns
• glob-style patterns use the following special characters
? matches any SINGLE character
* matches any sequence of zero or more characters
c matches the SINGLE (escaped) character c
[abc] matches any SINGLE character in abc
[a-b] matches any SINGLE character between a-b (inclusive)
{abc,xyz,...} matches any of the strings abc, xyz, etc.
• glob also understands UNIX shell tilde substitution
~ login user’s home directory
~user specified user's home directory (UNIX only!)
~user is limited to UNIX platforms only.
5.8
Copyright © 2024 Abdelazeem Tcl Training
Strings (tst1) 5.8
Other Useful String Commands
% string toupper "Vhdl Edif Tcl"
VHDL EDIF TCL
% string tolower "DECODER.VHD"
decoder.vhd
% string trim " Area: 2345
"
Area: 2345
% string trim "((a+b)))" ")("
a+b
% string trimleft "../mp3/" "/."
mp3/
% string trimright "../mp3/" "/"
../mp3
% string toupper "Vhdl Edif Tcl"
VHDL EDIF TCL
% string tolower "DECODER.VHD"
decoder.vhd
% string trim " Area: 2345
"
Area: 2345
% string trim "((a+b)))" ")("
a+b
% string trimleft "../mp3/" "/."
mp3/
% string trimright "../mp3/" "/"
../mp3
convert lowercase characters to
UPPERCASE
convert UPPERCASE characters to lowercase
remove white spaces (spaces, tabs,
newlines, carriage returns) from the
beginning and the end of the string
remove only the specified characters,
e.g. ) and ( in this case
remove only the specified characters (/ and .)
and only from the BEGINNING of the string
remove only the specified characters (/)
and only from the END of the string
• string is a mega-command with many useful functions
– Takes an input string and returns its modified value
– string does NOT modify the input string
Full syntax for the commands above:
string toupper string
string tolower string
string trim string ?chars?
string trimleft string ?chars?
string trimright string ?chars?
5.9
Copyright © 2024 Abdelazeem Tcl Training
Strings (tst1) 5.9
• Be aware of lexicographical rules
• Typical use of string comparison/matching
Examples: Comparing/Matching Strings
% string compare "A" "a"
-1
% string compare "Z" "a"
-1
% string compare "Z" [string toupper "a"]
1
% string compare "A" "a"
-1
% string compare "Z" "a"
-1
% string compare "Z" [string toupper "a"]
1
UPPERCASE characters are always
BEFORE lowercase characters...
Convert strings to either
lowercase or UPPERCASE
if you want to compare
alphabetically.
if {[string match *.edif $file]} {
puts "Found EDIF file: $file (.edif)"
} elseif {[string match *.edn [string tolower $file]]} {
puts "Found EDIF file: $file (.edn or .EDN)"
} elseif {![string compare "README.txt" $file]} {
puts "Found the README file!"
}
if {[string match *.edif $file]} {
puts "Found EDIF file: $file (.edif)"
} elseif {[string match *.edn [string tolower $file]]} {
puts "Found EDIF file: $file (.edn or .EDN)"
} elseif {![string compare "README.txt" $file]} {
puts "Found the README file!"
}
... which might not be what you
expect!
returns 1
if there is a
match
returns 0
if the strings
are identical
5.10
Copyright © 2024 Abdelazeem Tcl Training
Strings (tst1) 5.10
String Formatting
• Strings can be formatted into various forms using the
format command
– Printing numbers in hexadecimal, octal or decimal format
– Aligning text and numbers in columns
– Generating text in the format expected by other tools
• Typical examples
% format "Max period:%15.2e (%f) seconds" $period $period
Max period: 4.62e-006 (0.000005) seconds
% format "Max period:%15.2e (%f) seconds" $period $period
Max period: 4.62e-006 (0.000005) seconds
default precision is 6
set number precision to 2 and
(min) field width to 15
% set add 65365; set d 31; set period .00000462
.00000462
% format "Writing %d (%#x, %#o) to address %#x" $d $d $d $add
Writing 31 (0x1f, 037) to address 0xff55
% set add 65365; set d 31; set period .00000462
.00000462
% format "Writing %d (%#x, %#o) to address %#x" $d $d $d $add
Writing 31 (0x1f, 037) to address 0xff55
format syntax
format command is similar in capabilities to printf family of functions
in C.
format formatString ?arg arg ...?
5.11
Copyright © 2024 Abdelazeem Tcl Training
Strings (tst1) 5.11
Scanning Strings
• scan command extract values from a string according to
a format specification
– No need to know the character indices
– Useful for
• Extracting data from error messages and report logs
• Parsing input text from the user, and more...
– BUT regular expressions are more powerful (more later)
• Typical example
% set report "Total size: 12345 cells; Clock: 24 MHz"
Total size: 12345 cells; Clock: 24 MHz
% scan $report "%s%s%d" w1 w2 cells
3
% set cells
12345
% set report "Total size: 12345 cells; Clock: 24 MHz"
Total size: 12345 cells; Clock: 24 MHz
% scan $report "%s%s%d" w1 w2 cells
3
% set cells
12345
conversion specifiers:
string, string, integer
variables into which the matching strings
will be assigned
returns the number
of matched strings
scan syntax
While scan is a useful command for scanning simple string patterns, regular
expressions offer more powerful method for scanning strings (Session 8).
scan string format varName ?varName ...?
5.12
Copyright © 2024 Abdelazeem Tcl Training
Strings (tst1) 5.12
Using Character Indices
• Individual characters can be manipulated using their index
values with the string command
• Character index retrieval
– string first and string last search for the first or the last position
of character sequences
• Accessing characters using indices
– string index retrieves a character with a given index
– string range retrieves characters within the specified range
– string length counts the number of characters
H e l l o w o r l d !
0 1 2 ..................... 11
the first character
has index 0
5.13
Copyright © 2024 Abdelazeem Tcl Training
Strings (tst1) 5.13
• Retrieve the data packet between two FF2 marks
Examples: Character Indices
% string first "FF2" $data
7
% string last "FF2" $data
22
% string length $data
33
% string first "FF2" $data
7
% string last "FF2" $data
22
% string length $data
33
% set mark "FF2"
FF2
% set packet [ string range $data 
[expr [string first $mark $data] + [string length $mark]] 
[expr [string last $mark $data] - 1] ]
0001600B7914
% set mark "FF2"
FF2
% set packet [ string range $data 
[expr [string first $mark $data] + [string length $mark]] 
[expr [string last $mark $data] - 1] ]
0001600B7914
% string index $data 13
1
% string range $data 10 21
0001600B7914
% string range $data 25 end
03C899FE
% string index $data 13
1
% string range $data 10 21
0001600B7914
% string range $data 25 end
03C899FE
returns the index of the first character in the match
090FF00FF20001600B7914FF203C899FE
012345678901234567890123456789012
1 2 3
data =
end = index
of the last
character
Syntax for the above commands:
string first string1 string2
string last string1 string2
string index string charIndex
string range string firstIndex lastIndex
string length string
5.14
Copyright © 2024 Abdelazeem Tcl Training
Strings (tst1) 5.14
Quiz 5
file:
examples/quiz5.tcl
Answer
• What is the value of secret_msg ?
Tis great
set msg "T eciga lsrt"
set code "0 4 9"
set i 0
set j 0
while {$i != ([string length $msg]-1)} {
foreach k $code {
set i [expr $k+$j]
append secret_msg [string index $msg $i
]
}
incr j
}
puts $secret_msg
5.15
Copyright © 2024 Abdelazeem Tcl Training
Strings (tst1) 5.15
LAB 2: Working with a String Bitstream
• Write a procedure get_filename which will extract the
design file name from a Xilinx FPGA bitstream file (.bit).
• Example:
• Xilinx bitstream file has the following format
% source bitstream.tcl
% get_filename $bitstream
% source bitstream.tcl
% get_filename $bitstream
abdelazeem_a
d
d
.ncd
.ncd
...
0x61 length (2 bytes) 0x00
0x62 length (2 bytes) part name 0x00
0x63 length (2 bytes) date 0x00
0x64 length (2 bytes) time 0x00
0x65 length (4 bytes) FPGA configuration data
little-endian order (most significant byte on the left),
unsigned, length includes the trailing 0x00
may contain 0x00,
but not 0x61-0x65
design file name
this will read the FPGA
bitstream and store it in the Tcl
variable bitstream
Variable bitstream contains
bitstream is string in
hexadecimal format.
5.16
Copyright © 2024 Abdelazeem Tcl Training
Strings (tst1) 5.16
LAB 2: Working with a String Bitstream (2)
• Stage 1
– Search for the file name field markers using string first, e.g.
set first_marker_index [string first 61 $bitstream]
– Extract the file name hex characters from $bitstream using the
string range command (from/to indices need to be adjusted)
– Use a for loop to extract ASCII characters from the extracted file
name string (in hexadecimal format) using the format command, e.g.
set ascii_char [format "%c" "0x$hex_character"]
– Return the file name
• Stage 2
– Extract the other fields from the bitstream header
• NOTE: the field data may also contain characters 0x61-0x65 (a-e) !
– Check whether the file name field has the correct length
6.1
Copyright © 2024 Abdelazeem Tcl Training
Tcl Scripting for EDA
Lists and Arrays
6.2
Copyright © 2024 Abdelazeem Tcl Training
Lists and Arrays (tla1) 6.2
Aims and Topics
• Aim
– To learn how to use Tcl lists and arrays
• Topics
– Lists
• building lists
• manipulating lists
– Arrays
• building arrays
• manipulating arrays
– Lists versus Arrays
6.3
Copyright © 2024 Abdelazeem Tcl Training
Lists and Arrays (tla1) 6.3
What is a List?
• List is a collection of ORDERED elements
– List elements are strings
• Can represent anything (string values, other lists, other Tcl data
structures, etc.)
– List elements are separated by whitespaces
• Spaces, tabs, newlines
• Tcl list of 5 elements:
% set fruits "apple lemon banana pear grapes"
apple lemon banana pear grapes
% set fruits "apple lemon banana pear grapes"
apple lemon banana pear grapes
list element
"lemon"
separator
6.4
Copyright © 2024 Abdelazeem Tcl Training
Lists and Arrays (tla1) 6.4
Manipulating List Elements
• Use llength to count the number of elements in a list
• Retrieving list elements using indices
– lindex returns an element with a given index
– lrange returns elements within the given index range
– Both return an empty string if the elements could not be found
% llength $fruits
5
% llength $fruits
5
apple lemon banana pear grapes
0 1 ....................... 4
the first element
has index 0
fruits =
% lindex $fruits 1
lemon
% lindex $fruits end
grapes
% lindex $fruits 1
lemon
% lindex $fruits end
grapes
% lrange $fruits 0 2
apple lemon banana
% lrange $fruits 3 end
pear grapes
% lrange $fruits 0 2
apple lemon banana
% lrange $fruits 3 end
pear grapes
index of the last element end
=
Syntax for the commands above
llength list
lindex list index
lrange list firstIndex lastIndex
6.5
Copyright © 2024 Abdelazeem Tcl Training
Lists and Arrays (tla1) 6.5
Nested Lists
• Lists can be nested
– Use {}’s to define lists within lists
• Useful for storing complex data structures, e.g.
% set cells "inv {and2 or2} {and3 or3} or4"
inv {and2 or2} {and3 or3} or4
% set cells "inv {and2 or2} {and3 or3} or4"
inv {and2 or2} {and3 or3} or4
% set library "ams.vhdl {and 2 100} {or 2 120} {inv 1 20}"
ams.vhdl {and 2 100} {or 2 120} {inv 1 20}
% set library "ams.vhdl {and 2 100} {or 2 120} {inv 1 20}"
ams.vhdl {and 2 100} {or 2 120} {inv 1 20}
library source file cell data cell name
number of
inputs cell area
% set cells "inv {{and2 nand2} {or2 nor2}}"
inv {{and2 nand2} {or2 nor2}}
% set cells "inv {{and2 nand2} {or2 nor2}}"
inv {{and2 nand2} {or2 nor2}}
Tcl returns {}'s to
indicate list grouping.
The {}'s are NOT
part of the list!
lists within the cells list
lists within the 2nd element of the cells list
6.6
Copyright © 2024 Abdelazeem Tcl Training
Lists and Arrays (tla1) 6.6
Building Lists (1)
• Use word grouping with "" (or {})
• Use list command
• list command respects the list grouping,
while "" remove one level of grouping
% set fruits [list apple lemon banana pear grapes]
apple lemon banana pear grapes
% set fruits [list apple lemon banana pear grapes]
apple lemon banana pear grapes
% set basket "apple lemon"
apple lemon
% set fruits_list [list $basket banana pear grapes]
{apple lemon} banana pear grapes
% set fruits_quotes "$basket banana pear grapes"
apple lemon banana pear grapes
% set basket "apple lemon"
apple lemon
% set fruits_list [list $basket banana pear grapes]
{apple lemon} banana pear grapes
% set fruits_quotes "$basket banana pear grapes"
apple lemon banana pear grapes
compare!
4 elements
5 elements
all arguments become list elements
list syntax list ?arg arg ...?
6.7
Copyright © 2024 Abdelazeem Tcl Training
Lists and Arrays (tla1) 6.7
Building Lists (2)
• Use lappend to insert new list elements at the END
– Optimised for speed
– Will create the list variable if it does not exist
• Equivalent to
– Slow, but simple!
% lappend fruits strawberry orange
apple lemon banana pear grapes strawberry orange
% lappend fruits strawberry orange
apple lemon banana pear grapes strawberry orange
name of the list to append
(not $fruits!)
one or more elements to append
% set fruits "$fruits strawberry orange"
apple lemon banana pear grapes strawberry orange
% set fruits "$fruits strawberry orange"
apple lemon banana pear grapes strawberry orange
Use lappend when
building long lists!
lappend syntax
lappend is significantly faster then substitution when constructing long lists.
Let’s demonstrate the performance difference between using substitution and
lappend when constructing lists of various sizes. In the following, list
a is constructed in a for loop. The body of the loop contains either
set a "$a item" or lappend a "item"
Try: source examples/lappend_vs_set.tcl
lappend varName ?value value ...?
List size 1000 10000 100000
substitution 4 ms 214 ms 193 s
lappend 3 ms 30 ms 314 ms
speed-up 1.3 7.1 615
Tcl 8.0.5 on Pentium III/1GHz PC, 256MB RAM, Windows 2000
6.8
Copyright © 2024 Abdelazeem Tcl Training
Lists and Arrays (tla1) 6.8
Building Lists (3)
• Join two or more lists together with concat
– Returns a new list
– Removes one level of list grouping (same effect as with "")
– Eliminates leading and trailing spaces
% set basket "apple pear grapes"
apple pear grapes
% set basket_exotic "lemon banana"
lemon banana
% set fruits [concat $basket $basket_exotic]
apple pear grapes lemon banana
% set fruits [list $basket $basket_exotic]
{apple pear grapes} {lemon banana}
% set basket "apple pear grapes"
apple pear grapes
% set basket_exotic "lemon banana"
lemon banana
% set fruits [concat $basket $basket_exotic]
apple pear grapes lemon banana
% set fruits [list $basket $basket_exotic]
{apple pear grapes} {lemon banana}
% set fruits [concat $basket_exotic { orange }]
lemon banana orange
% set fruits "$basket_exotic { orange }"
lemon banana { orange }
% set fruits [concat $basket_exotic { orange }]
lemon banana orange
% set fruits "$basket_exotic { orange }"
lemon banana { orange }
compare!
compare!
spaces are
removed
5 elements
2 elements = lists within a list
concat syntax concat ?arg arg ...?
6.9
Copyright © 2024 Abdelazeem Tcl Training
Lists and Arrays (tla1) 6.9
Inserting and Replacing List Elements
• Use linsert to insert new list elements at ANY position
• Use lreplace to replace or delete existing list elements
% set fruits "apple lemon banana pear grapes"
apple lemon banana pear grapes
% set fruits [linsert $fruits 1 apricot]
apple apricot lemon banana pear grapes
% set fruits [linsert $fruits 4 cherry plum]
apple apricot lemon banana cherry plum pear grapes
% set fruits "apple lemon banana pear grapes"
apple lemon banana pear grapes
% set fruits [linsert $fruits 1 apricot]
apple apricot lemon banana pear grapes
% set fruits [linsert $fruits 4 cherry plum]
apple apricot lemon banana cherry plum pear grapes
% set fruits [lreplace $fruits 0 1 pineapple peach]
pineapple peach lemon banana cherry plum pear grapes
% set fruits [lreplace $fruits 3 end]
pineapple peach lemon
% set fruits [lreplace $fruits 0 1 pineapple peach]
pineapple peach lemon banana cherry plum pear grapes
% set fruits [lreplace $fruits 3 end]
pineapple peach lemon
% set fruits [lreplace $fruits 1 1 orange]
pineapple orange lemon
% set fruits [lreplace $fruits 0 0]
orange lemon
% set fruits [lreplace $fruits 1 1 orange]
pineapple orange lemon
% set fruits [lreplace $fruits 0 0]
orange lemon
insert BEFORE the
element with index 1
linsert can insert
one or more elements
replace elements within
this index range
(from-to)
delete elements within
the index range
use IDENTICAL indices
if only ONE element is
to be replaced
(or deleted)
Syntax for the commands above:
linsert list index element ?element element ...?
lreplace list firstIndex lastIndex ?element element ...?
6.10
Copyright © 2024 Abdelazeem Tcl Training
Lists and Arrays (tla1) 6.10
Example: Reversing the List
• Tcl does not provide a command which could reverse the
order of elements in a list
– Easy to write using the existing list commands
• Then use as an ordinary Tcl command
proc lreverse {l} {
set reversed_l ""
foreach element $l {
set reversed_l [linsert $reversed_l 0 $element]
}
return $reversed_l
}
proc lreverse {l} {
set reversed_l ""
foreach element $l {
set reversed_l [linsert $reversed_l 0 $element]
}
return $reversed_l
}
% set fruits "apple lemon banana pear grapes"
apple lemon banana pear grapes
% set reversed_fruits [lreverse $fruits]
grapes pear banana lemon apple
% set fruits "apple lemon banana pear grapes"
apple lemon banana pear grapes
% set reversed_fruits [lreverse $fruits]
grapes pear banana lemon apple
6.11
Copyright © 2024 Abdelazeem Tcl Training
Lists and Arrays (tla1) 6.11
% set dir_list [split "/Decoder/mp3/buffer/gnd" "/"]
{} Decoder mp3 buffer gnd
% set dir_list [lreplace $dir_list end end "GND"]
{} Decoder mp3 buffer GND
% set new_path [join $dir_list "::"]
::Decoder::mp3::buffer::GND
% set dir_list [split "/Decoder/mp3/buffer/gnd" "/"]
{} Decoder mp3 buffer gnd
% set dir_list [lreplace $dir_list end end "GND"]
{} Decoder mp3 buffer GND
% set new_path [join $dir_list "::"]
::Decoder::mp3::buffer::GND
list element separator
characters (1 or more)
capitalize the name
of the last element
reconstruct the
path using the
:: separator
Converting between Lists and Strings
• It is easy to convert between strings and lists
– split splits the string into a set of list elements
– join joins the list element into a string
– List element separator can be any string (1 space is the default)
• Typical uses
– Manipulate hierarchical paths (rename elements, change the
separator, determine the depth of hierarchy, etc.)
– Extract useful information from strings, and more...
split the path string
into list elements
empty
element
Syntax for the commands above:
split string ?splitChars?
join list ?joinString?
6.12
Copyright © 2024 Abdelazeem Tcl Training
Lists and Arrays (tla1) 6.12
Searching Lists
• Use lsearch to search the list for the FIRST element
matching the search pattern
• Search mode (?mode?) can be
-exact exact matching
-glob glob-style pattern matching, this is the DEFAULT
-regexp regular expression pattern matching (more later)
• Return value
-1 pattern does NOT match any elements in the list
0-end index of the first element matching the pattern
lsearch ?mode? list pattern
6.13
Copyright © 2024 Abdelazeem Tcl Training
Lists and Arrays (tla1) 6.13
Examples: Searching Lists
• Glob-style pattern matching
• Exact matching
% set cell_list "inv and2 or2 and3 or3 or4"
inv and2 or2 and3 or3 or4
% lsearch $cell_list or*
2
% lsearch -glob $cell_list xor*
-1
% set cell_list "inv and2 or2 and3 or3 or4"
inv and2 or2 and3 or3 or4
% lsearch $cell_list or*
2
% lsearch -glob $cell_list xor*
-1
% lsearch -exact $cell_list or4
5
% lsearch -exact $cell_list and
-1
% lsearch -exact $cell_list or4
5
% lsearch -exact $cell_list and
-1
optional
(-glob is the default)
glob-style search patterns
exact strings to be matched
or2
found at
index 2
-1 = not found
6.14
Copyright © 2024 Abdelazeem Tcl Training
Lists and Arrays (tla1) 6.14
Sorting Lists
• Use lsort to sort list elements
• lsort is a very powerful sorting command; various features
are available through lsort options
– Sort in increasing (default) or decreasing order
– Sort strings using ASCII (default) or dictionary comparison
– Sort numbers using integer or real number comparison
– Sort using a custom comparison command
% set sorted_cmds [lsort [info commands]]
after append array auto_execok auto_import auto_load
auto_load_index auto_mkindex auto_mkindex_old auto_qualify
auto_reset binary break case catch cd clock close concat
...
% set sorted_cmds [lsort [info commands]]
after append array auto_execok auto_import auto_load
auto_load_index auto_mkindex auto_mkindex_old auto_qualify
auto_reset binary break case catch cd clock close concat
...
returns the list of Tcl commands (UNSORTED)
SORTED list
of commands
lsort syntax lsort ?options? list
6.15
Copyright © 2024 Abdelazeem Tcl Training
Lists and Arrays (tla1) 6.15
Example: Sorting Blocks in a Hierarchy
• Sort design blocks using their hierarchical position
– Top-level first, bottom-level least
• First define a custom hierarchy comparison command
• Then use lsort to sort the blocks
set blocks "/Decoder/mp3/u1
/Decoder/mp3/buffer/u1 /Decoder/mp3/u2
/Decoder /Decoder/mp3 /Decoder/GND"
set blocks "/Decoder/mp3/u1
/Decoder/mp3/buffer/u1 /Decoder/mp3/u2
/Decoder /Decoder/mp3 /Decoder/GND"
proc hier_cmp {p1 p2} {
set p1_list [split $p1 "/"]
set p2_list [split $p2 "/"]
expr {[llength $p1_list] - [llength $p2_list]}
}
proc hier_cmp {p1 p2} {
set p1_list [split $p1 "/"]
set p2_list [split $p2 "/"]
expr {[llength $p1_list] - [llength $p2_list]}
}
% lsort -command hier_cmp $blocks
/Decoder /Decoder/mp3 /Decoder/GND /Decoder/mp3/u1
/Decoder/mp3/u2 /Decoder/mp3/buffer/u1
% lsort -command hier_cmp $blocks
/Decoder /Decoder/mp3 /Decoder/GND /Decoder/mp3/u1
/Decoder/mp3/u2 /Decoder/mp3/buffer/u1
Decoder
mp3 GND
u1 u2 buffer
u1
custom comparison
command should return:
+int when p1 > p2
0 when p1 = p2
-int when p1 < p2
compare using the custom
comparison command
(hier_cmp)
sorting
order
The above example demonstrates one of the main features of Tcl—productivity.
Tcl allows for complex tasks to be coded rapidly.
6.16
Copyright © 2024 Abdelazeem Tcl Training
Lists and Arrays (tla1) 6.16
Lists: Summary
• A powerful Tcl data object, which maintains the order
of its elements
• Can be created using a variety of methods
– substitution
– concatenation
– append
• List elements can be accessed using an integer index
• Tcl provides commands for list manipulation
– Creating lists
– Inserting/deleting list elements
– Searching for elements matching a pattern
– Sorting list elements
6.17
Copyright © 2024 Abdelazeem Tcl Training
Lists and Arrays (tla1) 6.17
What is an Array?
• An array is a collection of LABELLED elements
– Tcl arrays are associative; each element is identified by a key (also
called ‘index’, ‘label’ or ‘address’)
– Array element values and keys
are STRINGS
• Assigning/reading the
value of an array element
key
value
array variable name
% set IT_people(john) memo
memo
% set IT_people(john)
memo
% set IT_people(john) memo
memo
% set IT_people(john)
memo
array variable name key value
enclose the key within
parenthesis
will return an ERROR if the
key cannot be found
All keys in the array must be defined before the key is to be accessed. For
example, set IT_people(edward) will generate an error message.
6.18
Copyright © 2024 Abdelazeem Tcl Training
Lists and Arrays (tla1) 6.18
Basic Array Operations
• Arrays and their elements can be manipulated as other
Tcl variables
– Retrieve element’s value using variable substitution
– Remove the element or the entire array
• Element key can be also stored in a variable
% puts "John received a $IT_people(john)."
John received a memo.
% puts "John received a $IT_people(john)."
John received a memo.
% unset IT_people(john)
% unset IT_people
% unset IT_people(john)
% unset IT_people
% set name "john"
john
% puts "John received a $IT_people($name)."
John received a memo.
% set name "john"
john
% puts "John received a $IT_people($name)."
John received a memo.
6.19
Copyright © 2024 Abdelazeem Tcl Training
Lists and Arrays (tla1) 6.19
Manipulating Arrays
• New array elements can be added
– One at a time
– One or more elements in one command using array set
• Use array get to retrieve the entire contents of the array
% set IT_people(phil) "fax message"
fax message
% set IT_people(phil) "fax message"
fax message
% array set IT_people {
bill "vacancy notice"
angela "pay slip"
}
% array set IT_people {
bill "vacancy notice"
angela "pay slip"
}
% array get IT_people
angela {pay slip} phil {fax message} bill {vacancy notice} john memo
% array get IT_people
angela {pay slip} phil {fax message} bill {vacancy notice} john memo
key value
key value array set and array get
are useful when converting
between arrays and lists
Syntax for the commands above
array set arrayName list
array get arrayName ?pattern?
use optional pattern to
retrieve only those
elements which match
the glob-style pattern
6.20
Copyright © 2024 Abdelazeem Tcl Training
Lists and Arrays (tla1) 6.20
Multi-dimensional Arrays
• Arrays may represent multi-dimensional objects
– Use keys which ‘look’ like multi-dimensional indices
– Keys are still STRINGS, only they contain special characters
(e.g. commas)
% set image(0,0) 255
255
% set image(0,1) 33
33
% puts "Pixel intensity at (0,1) is $image(0,1)."
Pixel intensity at (0,1) is 33.
% set image(0,0) 255
255
% set image(0,1) 33
33
% puts "Pixel intensity at (0,1) is $image(0,1)."
Pixel intensity at (0,1) is 33.
2D array
looks like two indices (0, 0),
but this is really a string "0,0"!
% set frame_set(10,100,2) 250
250
% set synthesis_results(smallest,23ns) 34mW
34mW
% set image(filename) lena.rgb
lena.rgb
% set frame_set(10,100,2) 250
250
% set synthesis_results(smallest,23ns) 34mW
34mW
% set image(filename) lena.rgb
lena.rgb
string!
3D array
easy to combine
1D, 2D, 3D, ...
elements in ONE array!
Avoid spaces in array keys!
image(0,0) and
image(0, 0) are two
DIFFERENT array elements!
6.21
Copyright © 2024 Abdelazeem Tcl Training
Lists and Arrays (tla1) 6.21
Examining Arrays
• Use array mega-command to obtain information about
array variables
– Check for the existence of the array variable
• Returns 0 if the variable is not an array or it does not exist
• Returns 1 otherwise
– Retrieve the number of elements in the array
– Retrieve the list of array keys
% array exists IT_people
1
% array exists IT_people
1
% array size IT_people
4
% array size IT_people
4
% array names IT_people
angela phil bill john
% array names IT_people
angela phil bill john
Syntax for the above commands
array mega-command provides other useful functions. For example it is possible
to retrieve array elements sequentially using array startsearch, array
nextelement, array anymore, and array donesearch. For more details, consult
array manual page.
array exists arrayName
array size arrayName
array names arrayName ?pattern?
use optional pattern to
retrieve only the keys
matching the glob-style
pattern
6.22
Copyright © 2024 Abdelazeem Tcl Training
Lists and Arrays (tla1) 6.22
Examples: Using Arrays
• Look-up table
• 2D image data storage
% array set ports {
and2 {i1 i2 o1}
or2 {i1 i2 o1}
inv {i1 o1}
half_add {i1 i2 o1 cout}
full_add {i1 i2 cin o1 cout}
}
% set cell "and2"
and2
% puts "Cell $cell has ports: $ports($cell)"
Cell and2 has ports: i1 i2 o1
% array set ports {
and2 {i1 i2 o1}
or2 {i1 i2 o1}
inv {i1 o1}
half_add {i1 i2 o1 cout}
full_add {i1 i2 cin o1 cout}
}
% set cell "and2"
and2
% puts "Cell $cell has ports: $ports($cell)"
Cell and2 has ports: i1 i2 o1
% for {set x 0} {$x < 256} {incr x} {
for {set y 0} {$y < 256} {incr y} {
set image($x,$y) $y
}
}
% for {set x 0} {$x < 256} {incr x} {
for {set y 0} {$y < 256} {incr y} {
set image($x,$y) $y
}
}
(0,0)
(255,255)
6.23
Copyright © 2024 Abdelazeem Tcl Training
Lists and Arrays (tla1) 6.23
Lists versus Arrays
LISTS
• Can store various elements
• Order of elements is preserved
• Elements are retrieved using an
INTEGER index
• Lists are manipulated using the
list value
ARRAYS
• Can store various elements
• Order of elements if NOT
preserved
• Elements are retrieved using
a STRING key
• Arrays are manipulated using
the name of the array variable
• Since Tcl 8.0 there is NO PERFORMANCE DIFFERENCE
between Tcl lists and arrays
% set l [list r g b]
r g b
% llength $l
3
% set l [list r g b]
r g b
% llength $l
3
% array set a {
r RED g GREEN b BLUE }
% array names a
b r g
% array set a {
r RED g GREEN b BLUE }
% array names a
b r g
list l is accessed by
its value $l (not l)
array a is accessed
by the name of array
variable a (not $a)
order is NOT
preserved
order is
preserved
Lists and arrays provide two ways of storing multiple data elements. When
deciding between the two, it is best to choose a data structure which is the most
natural representation of the data.
For example, a phone book is most naturally represented in an array as names
can be used as array keys. A list of files is usually represented using lists, as this
allows easy file browsing, sorting and manipulation.
Before Tcl 8.0 lists access was much slower than array access. Since Tcl 8.0 both
lists and arrays are internally represented using similar data structures. Tcl then
provides advantages of using linked lists, but with the performance of array
access.
6.24
Copyright © 2024 Abdelazeem Tcl Training
Lists and Arrays (tla1) 6.24
Quiz 6
• What are the values stored in b and c?
(a) b = "" and c = "" (both are empty strings)
(b) b = pear and c = pear
(c) b = pear, but c assignment generates an error
(d) b = apple, but c assignment generates an error
(e) b = "", but c assignment generates an error
(f) b assignment generates an error and c = ""
set a_list {apple lemon pear}
array set a_array {0 apple 1 lemon 2 pear}
set b [lindex $a_list 3]
puts "b = "$b""
set c [$a_array(3)]
puts "c = "$c""
set a_list {apple lemon pear}
array set a_array {0 apple 1 lemon 2 pear}
set b [lindex $a_list 3]
puts "b = "$b""
set c [$a_array(3)]
puts "c = "$c""
file:
examples/quiz6.tcl
Answer
6.25
Copyright © 2024 Abdelazeem Tcl Training
Lists and Arrays (tla1) 6.25
LAB 3: Sorting Design Blocks
• Write a procedure sort_by_area which will sort the design
blocks according to their area
– decoder is a global list which contains the list of design blocks
– block_area is a global array which stores areas of all leaf blocks
• For example $block_area(/Decoder/mp3/u1) is the area
of the /Decoder/mp3/u1 block
• Example:
% source decoder.tcl
% sort_by_area $decoder
/Decoder/GND /Decoder/buffer/u1 /Decoder/mp3/u1 /Decoder/mp3/u2
% source decoder.tcl
% sort_by_area $decoder
/Decoder/GND /Decoder/buffer/u1 /Decoder/mp3/u1 /Decoder/mp3/u2
Decoder
mp3 GND
u1 u2 buffer
u1
6.26
Copyright © 2024 Abdelazeem Tcl Training
Lists and Arrays (tla1) 6.26
LAB 3: Sorting Design Blocks (2)
• Stage 1
– Sort the decoder list using a custom sorting command
• Use global block_area to allow access to the block_area global
variable from within the custom comparison command
• Stage 2
– Include both the sorted block names and their respective areas
in the returned result
• Each element is a list with 2 elements: block name & area
– Construct a sub-list containing only the leaf blocks extracted
from the list of all design cells available in the decoder_full variable
• Use lsearch [array names block_area] $block_name
to check whether an area figure can be obtained for the block
– Calculate the total area for all blocks in the decoder list,
including the hierarchical blocks (mp3 and Decoder)
7.1
Copyright © 2024 Abdelazeem Tcl Training
Tcl Scripting for EDA
File I/O and Program Access
7.2
Copyright © 2024 Abdelazeem Tcl Training
File I/O and Program Access (tfp1) 7.2
Aims and Topics
• Aim
– To learn about how to access files, execute programs
and create simple networking applications
• Topics
– Reading from and writing to files
– Invoking external programs
– Multi-process communication
7.3
Copyright © 2024 Abdelazeem Tcl Training
File I/O and Program Access (tfp1) 7.3
File Manipulation Revisited
• Simple file manipulation with cd, pwd and glob
• file command provides many other operations, e.g.:
% file mkdir ~/project/daily_backup
% file copy add_v2.vhdl ~/project/daily_backup
% file rename sub_v4.vhdl sub.vhd
% file rename sub.vhd ~/project/archive
% file delete compile.log
% file mkdir ~/project/daily_backup
% file copy add_v2.vhdl ~/project/daily_backup
% file rename sub_v4.vhdl sub.vhd
% file rename sub.vhd ~/project/archive
% file delete compile.log
% file isdirectory ~/project
1
% file dirname ~/project/README
~/project
% file mtime add_v2.vhdl
994776518
% file exists add_v3.vhdl
0
% file readable add_v2.vhdl
1
% file isdirectory ~/project
1
% file dirname ~/project/README
~/project
% file mtime add_v2.vhdl
994776518
% file exists add_v3.vhdl
0
% file readable add_v2.vhdl
1
CREATE a directory
COPY a file/directory
RENAME a file/directory
MOVE a file/directory
DELETE a file/directory
test whether the file
is a directory
extract only the directory
name from the path
Prefer using file Tcl
command to platform-
specific file commands
to improve portability.
test whether the
file exists
test whether the
file is readable
extract file modification time
(more on time later)
Full syntax for the
commands
above:
file mkdir dir ?dir ...?
file copy ?-force? ?--? source target
file copy ?-force? ?--? source ?source ...? targetDir
file rename ?-force? ?--? source target
file rename ?-force? ?--? source ?source ...? targetDir
file delete ?-force? ?--? pathName ?pathName ...?
file isdirectory name
file dirname name
file mtime name
file exists name
file readable name
7.4
Copyright © 2024 Abdelazeem Tcl Training
File I/O and Program Access (tfp1) 7.4
Opening and Closing Files
• Use open to open a file for access
– Returns a channel identifier (also called a file id or descriptor) which
is UNIQUE for each opened file
• After you finish accessing the file, close it with close
– Channel identifier is invalidated after the file was closed
% set fid [open test1.dat w]
file24
% set fid [open test1.dat w]
file24
% close $fid
% close $fid To improve performance,
do not leave files open when
they are not being used.
file24 is the
channel identifier
file name access mode
r read only (default)
r+ read/write (file must already exist)
w write only
w+ read/write
a append only
a+ read/append
open syntax
close syntax
open fileName
close channelId
open fileName access
open fileName access permissions
7.5
Copyright © 2024 Abdelazeem Tcl Training
File I/O and Program Access (tfp1) 7.5
Catching Command Errors
• Use the catch command to trap and handle errors from
specific commands/scripts
– Returns 1 if there was an error executing Tcl command,
0 otherwise
– result contains the error message returned by the command,
or the command result (if the command did not generate an error)
• Beware
– catch also suppresses syntax and programming errors
– Use catch at lowest possible level to catch only the errors you expect!
% catch {set fid [open does_not_exist.txt r]} result
1
% set result
couldn’t open "does_not_exist.txt": no such file or directory
% catch {set fid [open does_not_exist.txt r]} result
1
% set result
couldn’t open "does_not_exist.txt": no such file or directory
!
7.6
Copyright © 2024 abdelazeem Tcl Training
File I/O and Program Access (tfp1) 7.6
Writing to Files
• Use puts to write to files
– Returns an empty string on success, error message otherwise
• Special channels are available for standard terminal I/O
– stdout (standard terminal output), stderr (standard terminal
error output), stdin (standard terminal input)
% puts $fid "Hello world!"
%
% puts -nonewline $fid "Hello world!"
%
% puts $fid "Hello world!"
%
% puts -nonewline $fid "Hello world!"
%
write "Hello world!" + newline
into an open file with channel ID $fid
write "Hello world!" only
(no newline)
% puts stdout "Hello world!"
Hello world!
% puts "Hello world!"
Hello world!
% puts stderr "Error: invalid input!"
Error: invalid input!
% puts stdout "Hello world!"
Hello world!
% puts "Hello world!"
Hello world!
% puts stderr "Error: invalid input!"
Error: invalid input!
write "Hello world!" + newline
to standard terminal output
(stdout channel is the default)
write an error message to standard terminal
error output
Full puts syntax:
Be warned that stdin/out and stderr exist only when there is a terminal window. On
NT stdout and stderr are identical.
puts ?-nonewline? ?channelId? string
7.7
Copyright © 2024 Abdelazeem Tcl Training
File I/O and Program Access (tfp1) 7.7
File Pointer Position
• Files are accessed using an “invisible” file pointer
– Positioned at the beginning when the file is opened
– Moves forward with each file read
• Use seek to set the file pointer to the desired position
T H I
0 1 2 ...
the file origin
has index 0
S
I
S L I N E 1 n T H I S
test1.dat: ...
moves forward as the characters are read
% seek $fid 5 start
% seek $fid 8 current
% seek $fid -10 end
% seek $fid 5 start
% seek $fid 8 current
% seek $fid -10 end
move the file pointer 5 positions AFTER the file origin
move the file pointer 8 positions AFTER the current position
move the file pointer 10 positions BEFORE the end of the file
file pointer offset offset origin
seek syntax seek channelId offset ?origin?
7.8
Copyright © 2024 Abdelazeem Tcl Training
File I/O and Program Access (tfp1) 7.8
Reading Lines
• Use gets to read LINES from an open channel
– There are two alternative forms
• Typical uses
– Processing files and communication channel data line-by-line
– Building INTERACTIVE command-line scripts
% set line [gets $fid]
THIS IS LINE 1
% set chars [gets $fid line]
14
% set line [gets $fid]
THIS IS LINE 1
% set chars [gets $fid line]
14
gets returns the next line read from an open
channel with $fid identifier.
(next line = all characters until the end of line)
gets stores the next line into variable line,
and returns the number of characters read
or -1 if the end of file was reached
set fid [open "test1.dat" r]
while {[gets $fid line] >= 0} {
puts "test1.dat: $line"
}
close $fid
set fid [open "test1.dat" r]
while {[gets $fid line] >= 0} {
puts "test1.dat: $line"
}
close $fid
the while loop will terminate at the end
of file (gets will return -1)
gets syntax gets channelId ?varName?
7.9
Copyright © 2024 Abdelazeem Tcl Training
File I/O and Program Access (tfp1) 7.9
Example: Interactive Command-Line Script
puts "Welcome to a simple interactive script!"
source to_bits.tcl
while {1} {
puts "nCommand:"
gets stdin line
if {$line == ""} {continue}
switch -- [lindex $line 0] {
quit - exit {break}
dec2bits {puts [ to_bits [lindex $line 1] ]}
dir - ls {puts [ glob * ]}
default {puts stderr "Error: unrecognized command"}
}
}
puts "Thank you!"
puts "Welcome to a simple interactive script!"
source to_bits.tcl
while {1} {
puts "nCommand:"
gets stdin line
if {$line == ""} {continue}
switch -- [lindex $line 0] {
quit - exit {break}
dec2bits {puts [ to_bits [lindex $line 1] ]}
dir - ls {puts [ glob * ]}
default {puts stderr "Error: unrecognized command"}
}
}
puts "Thank you!"
file: examples/interactive.tcl
source other scripts if required
enter an indefinite while loop
(can be broken with exit)
print the prompt and collect the
input from the user
parse and execute the commands
skip if no command was supplied by
the user
7.10
Copyright © 2024 Abdelazeem Tcl Training
File I/O and Program Access (tfp1) 7.10
Reading Characters
• Use read to read CHARACTERS from an open channel
– There are two alternative forms
• Typical uses
– Reading the content of an entire file for further processing
– Processing text or binary files character-by-character
– Reading characters from communication channels
% set seven_chars [read $fid 7]
THIS IS
% set seven_chars [read $fid 7]
THIS IS
% set file [read -nonewline $fid]
THIS IS LINE 1
...
THIS IS LINE 9
% set file [read -nonewline $fid]
THIS IS LINE 1
...
THIS IS LINE 9
read next 7 characters from an open
channel $fid
read until the end of the file from an open
channel $fid
discard the last newline, if present
(optional)
read syntax:
read ?-nonewline? channelId
read channelId numBytes
7.11
Copyright © 2024 Abdelazeem Tcl Training
File I/O and Program Access (tfp1) 7.11
Checking for the End of File
• Use eof command to check for the end of file position
– Returns 1 at the end of file, 0 otherwise
– Provides a simple alternative to gets end of file detection
• Example: processing files character-by-character
while {![eof $fid]} {
gets $fid line
puts "test1.dat: $line"
}
while {![eof $fid]} {
gets $fid line
puts "test1.dat: $line"
}
repeat the while loop until the end of file
set src [open "test1.dat" r]
set dest [open "test2.dat" w]
while {![eof $src]} {
set c [read $src 1]
puts -nonewline $dest "$c$c$c"
}
close $src
close $dest
set src [open "test1.dat" r]
set dest [open "test2.dat" w]
while {![eof $src]} {
set c [read $src 1]
puts -nonewline $dest "$c$c$c"
}
close $src
close $dest
read ONE character at the time
write the result to the output file
(e.g. write 3 copies of the input character)
eof syntax: eof channelId
7.12
Copyright © 2024 Abdelazeem Tcl Training
File I/O and Program Access (tfp1) 7.12
Portability Issues
• End-of-line is represented by n on ALL Tcl platforms
– Incompatible end-of-line characters are automatically converted to
the end-of-line characters used by the host platform
• For portable file manipulation
– Avoid code dependent on the case of characters in filenames
– Avoid using special characters (<>:"/|.) in filenames
– Use Tcl file manipulation commands (cd, pwd, glob, file),
NOT the platform-specific commands
proc correct_newlines {src_file dest_file} {
set src [open $src_file r]
set dest [open $dest_file w]
puts $dest [read $src]
close $src
close $dest
}
proc correct_newlines {src_file dest_file} {
set src [open $src_file r]
set dest [open $dest_file w]
puts $dest [read $src]
close $src
close $dest
}
destination file will use end-
of-line characters
of the host platform
file: examples/correct_newlines.tcl
Tcl also supports the compatible subset of the native platform's file path
convention. However, this will only work on one native platform. It is advisable
avoid using this and use portable Tcl file path handling instead.
Although the forward slash is the directory separator, one should use file split and
file join to analyze and construct the filenames.
7.13
Copyright © 2024 Abdelazeem Tcl Training
File I/O and Program Access (tfp1) 7.13
NO
buffering
LINE
buffering
FULL
buffering
T
H
I
S
L
Channel Buffering
puts
1
n
T
I
...
I
N
E
I
S
H
T
THIS IS LINE 1n
THIS IS LINE 2n
THIS IS LINE 1n
THIS IS LINE 2n
THIS IS LINE 3n
...
THIS IS LINE 9n
H
channel buffer
There is an internal buffer associated with each I/O channel. For example, when
puts command puts characters into a channel, the characters are first buffered
and only then send to the channel.
There are three possible methods of channel buffering:
• NO buffering: the characters are not buffered at all. The characters are output
as they are received. This type of buffering is slow due to frequent I/O operations.
Try: source examples/buffering_none.tcl
• LINE buffering: the output is flushed after each end-of-line character. Line
buffering is the default type of buffering for terminal devices (such as stdout).
Try: source examples/buffering_line.tcl
• FULL buffering: the output is flushed after the internal buffer was filled with
characters. Full buffering is the default for file access as this provides a good
performance trade-off (I/O access occurs only after the internal buffer was filled).
Try: source examples/buffering_full.tcl
7.14
Copyright © 2024 Abdelazeem Tcl Training
File I/O and Program Access (tfp1) 7.14
Configuring Channel Buffers
• fconfigure is used to configure the type of channel buffering
• The contents of the channel buffer can be flushed at
ANY TIME using the flush command
...
fconfigure stdout -buffering none
...
...
fconfigure stdout -buffering none
...
buffering mode
none no buffering
line line buffering
full full buffering
file: examples/buffering_none.tcl
...
puts -nonewline "> "
flush stdout
gets stdin line
...
...
puts -nonewline "> "
flush stdout
gets stdin line
...
file: examples/interactive2.tcl
flushes the stdout channel
buffer to print the prompt
Use fconfigure to change properties of an open channel at ANY time during
channel access. Channel properties which can be changed include:
• Automatic end-of-line conversion
• End-of-file character
• Channel blocking and buffering
fconfigure syntax
flush syntax
fconfigure channelId
fconfigure channelId optionName
fconfigure channelId optionName optionValue ?optionName optionValue?
flush channelId
7.15
Copyright © 2024 Abdelazeem Tcl Training
File I/O and Program Access (tfp1) 7.15
Invoking External Programs
• Use exec to invoke external programs
• auto_noexec variable controls whether the interpreter
searches the native shell for unrecognized commands
– If auto_noexec does not exist
– If auto_noexec is defined (contains ANY value)
% exec zip archive.zip test1.dat
adding: test1.dat (92 bytes security) (deflated 72%)
% exec zip archive.zip test1.dat
adding: test1.dat (92 bytes security) (deflated 72%)
% zip archive.zip test1.dat
adding: test1.dat (92 bytes security) (deflated 72%)
% zip archive.zip test1.dat
adding: test1.dat (92 bytes security) (deflated 72%)
% set auto_noexec ""
% zip archive.zip test1.dat
invalid command name "zip"
% set auto_noexec ""
% zip archive.zip test1.dat
invalid command name "zip"
no exec
required
external program ...and its arguments
external program output is returned back to the Tcl interpreter
exec syntax exec ?switches? arg ?arg ...?
7.16
Copyright © 2024 Abdelazeem Tcl Training
File I/O and Program Access (tfp1) 7.16
Problems with Multiple Arguments
• Trying to remove ALL log files, but...
• ...easily solved with eval
– eval will force another round of word separation
and substitutions before the exec command is executed
% glob *.log
simulation.log synthesis.log test.log
% exec rm [glob *.log]
simulation.log synthesis.log test.log: no such file or directory
% glob *.log
simulation.log synthesis.log test.log
% exec rm [glob *.log]
simulation.log synthesis.log test.log: no such file or directory
exec rm simulation.log synthesis.log test.log
WHY?
Treated by rm as ONE file name!
exec rm simulation.log synthesis.log test.log
eval
% eval exec rm [glob *.log]
% eval exec rm [glob *.log]
eval syntax eval arg ?arg ...?
7.17
Copyright © 2024 Abdelazeem Tcl Training
File I/O and Program Access (tfp1) 7.17
Problems Executing External Programs
• tclsh is NOT a UNIX shell (/bin/sh, /bin/tcsh, etc.)
– UNIX shell wildchars, substitution and quoting do NOT work
• tclsh is NOT a Windows/DOS shell (command.com)
– Built-in Windows/DOS commands cannot be executed directly
% exec tar -cvf archive.tar project/*
tar: projects/*: Cannot stat: No such file or directory
...
% eval exec tar -cvf archive.tar [glob project/*]
...
% exec tar -cvf archive.tar project/*
tar: projects/*: Cannot stat: No such file or directory
...
% eval exec tar -cvf archive.tar [glob project/*]
...
UNIX shell wildchars
don’t work in Tcl!
use glob instead
% set dir_list [exec dir C:*.*]
couldn’t execute "dir": no such file or directory
%
% set dir_list [exec COMMAND.COM /C dir C:*.*]
...
% set dir_list [exec dir C:*.*]
couldn’t execute "dir": no such file or directory
%
% set dir_list [exec COMMAND.COM /C dir C:*.*]
...
dir is a built-in command
invoke command.com
with built-in command as
an argument instead
!
!
NOTE!
Similarly to Windows/DOS shell example above, you may also invoke commands
using a UNIX shell directly. For example, an alternative way
of executing the tar command above is
exec /bin/sh -c "tar -cvf archive.tar project/*"
This will execute correctly as the string given to the -c option is executed
by the UNIX shell (/bin/sh).
7.18
Copyright © 2024 Abdelazeem Tcl Training
File I/O and Program Access (tfp1) 7.18
Input/Output Redirection
• Tcl implements a range of I/O redirection operators
– Redirection of standard input, output and error channels
to/from files (overwrite and append modes)
– Receive standard input from a Tcl string
– Piping standard output to standard input between two commands
% exec compress << "Hello world!" > foo.Z
%
% set stats [exec zcat foo.Z | wc]
0 2 12
% exec compress << "Hello world!" > foo.Z
%
% set stats [exec zcat foo.Z | wc]
0 2 12
read from a Tcl string write standard output to a file
pipe standard output from zcat as
standard input to wc
7.19
Copyright © 2024 Abdelazeem Tcl Training
File I/O and Program Access (tfp1) 7.19
Processes in Tcl
• Start a new process with exec and & (ampersand)...
– Returns the process ID on success, an error message otherwise
• ...or using open with a pipe and use the pid command
to retrieve the process ID
% exec notepad.exe &
1476
% exec notepad.exe &
1476
process ID
% set fid [open "| ipconfig" r]
file24
% pid $fid
1164
% set fid [open "| ipconfig" r]
file24
% pid $fid
1164
process ID
external program to invoke
external program to invoke
the standard output from the ipconfig
program can be accessed as a CHANNEL
pipe
pid syntax pid ?field?
7.20
Copyright © 2024 Abdelazeem Tcl Training
File I/O and Program Access (tfp1) 7.20
Multi-Process Communication
HDL
Simulator
HDL
Simulator
Hardware
test rig
Hardware
test rig
commands
results
% set fid [open "| test_rig" r+]
file24
% fconfigure $fid -buffering line
% puts $fid "test1 100"
% gets $fid
test1: 1000
% puts $fid "test2 200"
% gets $fid
test2: 400
% close $fid
% set fid [open "| test_rig" r+]
file24
% fconfigure $fid -buffering line
% puts $fid "test1 100"
% gets $fid
test1: 1000
% puts $fid "test2 200"
% gets $fid
test2: 400
% close $fid
Hardware
test rig
Hardware
test rig
read/write mode (bi-directional communication)
external program
(can be another Tcl script!)
CLIENT SERVER
IMPORTANT: set-up LINE buffering
(FULL buffering is the default for files)
The above is the example of SYNCHRONOUS communication, i.e. the client
application always waits for the response from the server before proceeding
further.
Tcl can be also used to build ASYNCHRONOUS communication channels, which
are typically used in servers and GUI applications.
For more details on writing multi-process and networking applications in Tcl can
be found in Appendix C - Client-Server Applications and Networking.
7.21
Copyright © 2024 Abdelazeem Tcl Training
File I/O and Program Access (tfp1) 7.21
Quiz 7
• What is the contents of test3.dat?
(a) nothing (file test3.dat is an empty file)
(b) Hello
(c) Hellon
(d) Hellon world!
(e) Hellon world!n
(f) file test3.dat does not exist
set fid [open "test3.dat" w]
puts -nonewline $fid "Hellon world!"
set fid [open "test3.dat" w]
puts -nonewline $fid "Hellon world!"
file:
examples/quiz7.tcl
Answer
7.22
Copyright © 2024 Abdelazeem Tcl Training
8.1
Copyright © 2024 Abdelazeem Tcl Training
Tcl Scripting for EDA
Regular Expressions
8.2
Copyright © 2024 Abdelazeem Tcl Training
Regular Expressions (tre1) 8.2
Aims and Topics
• Aim
– To gain proficiency in using regular expressions for advanced
string processing
• Topics
– Regular expressions (REs): what and why?
– Regular expression patterns
– RE-based string searching
– RE-based string replacement
8.3
Copyright © 2024 Abdelazeem Tcl Training
Regular Expressions (tre1) 8.3
Why Regular Expressions?
• String search capabilities already exist in Tcl
– lsearch, string match, switch, etc.
– Inefficient for complex string search/replace operations
• Regular Expressions can handle complex and repetitive
string manipulation tasks efficiently
entity add is
...
a : in std_logic_vector(7 downto 0);
cin : in std_logic;
...
end add;
architecture struct of add is
...
sum <= result(7 downto 0);
cout <= result(8);
...
end struct;
entity add32 is
...
a : in std_logic_vector(0 to 31);
cin : in std_logic;
...
end add32;
architecture struct of add32 is
...
sum <= result(0 to 31);
cout <= result(32);
...
end struct;
transformed using
a set of rules
8.4
Copyright © 2024 Abdelazeem Tcl Training
Regular Expressions (tre1) 8.4
What are Regular Expressions?
• Special string patterns which can match strings using
various rules
– Context-specific
– Generic (will work for many different strings)
• Example
– RE for an output port declaration in a VHDL entity:
entity add is
port (
cin : in std_logic;
a : in std_logic_vector(7 downto 0);
b : in std_logic_vector(7 downto 0);
y : out std_logic_vector(7 downto 0);
cout: out std_logic
);
end add;
*[a-zA-Z][a-zA-Z0-9_]* *: *out [a-zA-Z][a-zA-Z0-9_]*
*[a-zA-Z][a-zA-Z0-9_]* *: *out [a-zA-Z][a-zA-Z0-9_]*
regular expression
string matching the regular expression
NOTE: RE string matching is based on context
(e.g. signal which is a 1-bit output port). Therefore
the matching will work for signals of any name or type.
8.5
Copyright © 2024 Abdelazeem Tcl Training
Regular Expressions (tre1) 8.5
Regular Expression Basics
• Alphabet and digit characters are matched as usual
a matches a SINGLE given character, i.e. character a
VHDL matches a SEQUENCE of given characters, i.e. string VHDL
• Regular expressions use several special characters
. matches ANY SINGLE character
[] matches a SINGLE character from a sequence, e.g.
[abc]
[A-Z]
[^A-Z]
[a-zA-Z0-9_]
* matches 0 or more occurrences of a preceding ATOM
a*
[a-z]*
[A-Z][a-z]*
.*
a or b or c (single character)
an uppercase letter (character range)
a character which is either a letter (lowercase or uppercase),
a digit or an underscore
0 or more characters a, e.g a or aaaaa, but also '' (no character)
0 or more lowercase letters
word with the first letter in uppercase (0 or more lowercase letters)
0 or more occurrences of any character, i.e. ALL characters
a character which is NOT an uppercase letter
8.6
Copyright © 2024 Abdelazeem Tcl Training
Regular Expressions (tre1) 8.6
Searching with Regular Expressions
• Use regexp command for RE-based string search
– regexp returns 1 if the match was found, 0 otherwise
• Use -nocase option for case-insensitive search
• RE patterns always match the LONGEST possible string
of characters
% regexp {[A-Z][A-Z]*} "which is better: VHDL or Verilog?" m_var
1
% set m_var
VHDL
% regexp {[A-Z][A-Z]*} "which is better: VHDL or Verilog?" m_var
1
% set m_var
VHDL
regular expression pattern string to search
variable which will store the
matched string
Enclose RE patterns within {} to protect
patterns from Tcl substitution (unless
the substitution is desired)
% regexp -nocase -- {[A-Z][A-Z]*} "which is better: ..." m_var
1
% set m_var
which
% regexp -nocase -- {[A-Z][A-Z]*} "which is better: ..." m_var
1
% set m_var
which
Always use -- to prevent regexp from
confusing patterns with options.
8.7
Copyright © 2024 Abdelazeem Tcl Training
Regular Expressions (tre1) 8.7
Example: Find the First VHDL Entity Line
set fid [open "adder.vhdl" r]
set add [read $fid]
close $fid
regexp -nocase -- { *entity *[a-z][a-z0-9_]* *is *} $add e_line
puts "$e_line"
set fid [open "adder.vhdl" r]
set add [read $fid]
close $fid
regexp -nocase -- { *entity *[a-z][a-z0-9_]* *is *} $add e_line
puts "$e_line"
file: examples/find_entity_line.tcl
% cd examples
% source find_entity_line.tcl
entity add is
% cd examples
% source find_entity_line.tcl
entity add is
entity add is
port (
...
);
end add;
...
file: examples/adder.vhdl
regexp syntax
regexp ?switches? exp string ?matchVar? ?subMatchVar subMatchVar ...?
8.8
Copyright © 2024 Abdelazeem Tcl Training
Regular Expressions (tre1) 8.8
More RE Symbols
• Characters and strings matching
^ matches the BEGINNING of a line, e.g.
^architecture
$ matches the END of a line, e.g.
;$
• Alternatives
x|y matches ONE of the two possible atoms, e.g.
out|in
[a-z]|[0-9]
• Use () to group atoms together, e.g.
([a-z][a-z]*)|[0-9]
string architecture at the beginning of a line
character ; at the end of line
string out OR string in
lowercase letter OR a digit
lowercase word of 1 or more letters OR a digit
8.9
Copyright © 2024 Abdelazeem Tcl Training
Regular Expressions (tre1) 8.9
More RE Symbols (2)
• Sequence matching
+ matches 1 or more occurrences of a preceding atom
+
[a-z]+
? matches 0 or 1 occurrence of a preceding atom
?
[a-z]?
• Meaning of all special RE characters can be escaped
with a backslash ()
((+?)|-)[0-9]+
• Tcl also provides an advanced version of REs (AREs) which
further simplify string searching
– See re_syntax Tcl manual page for more details (Tcl 8.2 and later)
1 or more spaces, equivalent to *)
1 or more lowercase letters
(a word composed of lowercase letters)
0 or 1 space, equivalent to ( |)
0 or 1 lowercase letter
1 or more digits preceded by either a character - or
optionally character +, i.e. an INTEGER
8.10
Copyright © 2024 Abdelazeem Tcl Training
Regular Expressions (tre1) 8.10
Searching for Strings within Strings
• REs can easily locate a sub-pattern within a pattern
– Use RE sub-expressions for sub-string matching
• Example: extract VHDL entity name
entity add is
...
end add;
...
regexp -nocase -- { *entity +([a-z][a-z0-9_]*) +is *} $add 
e_line e_name
puts "$e_name"
...
regexp -nocase -- { *entity +([a-z][a-z0-9_]*) +is *} $add 
e_line e_name
puts "$e_name"
file: examples/find_entity_name.tcl
% source find_entity_name.tcl
add
% source find_entity_name.tcl
add
file: examples/adder.vhdl
holds the 1st matched
sub-string
holds the entire
matched string
a sub-expression is
enclosed within ()
8.11
Copyright © 2024 Abdelazeem Tcl Training
Regular Expressions (tre1) 8.11
Example: Extracting VHDL Port Direction
entity add is
port (
cin : in std_logic;
a : in std_logic_vector(7 downto 0);
b : in std_logic_vector(7 downto 0);
y : out std_logic_vector(7 downto 0);
cout: out std_logic
);
end add;
...
file: examples/adder.vhdl
...
regexp -nocase -- 
{ *([a-z][a-z0-9_]*) +: +([a-z]+)[^;]*;} $add 
p_line p_name p_dir
puts "$p_name ($p_dir)"
...
regexp -nocase -- 
{ *([a-z][a-z0-9_]*) +: +([a-z]+)[^;]*;} $add 
p_line p_name p_dir
puts "$p_name ($p_dir)"
% source find_port_dir.tcl
cin (in)
% source find_port_dir.tcl
cin (in)
• More than one
sub-pattern can be used
– Add additional sub-pattern
variables as necessary
file: examples/find_port_dir.tcl
8.12
Copyright © 2024 Abdelazeem Tcl Training
Regular Expressions (tre1) 8.12
Using Indices with regexp
• With -indices option regexp will extract string
index range instead of a string
• Typical uses
– Searching for an insertion position
– Repetitive search
– Index-based string manipulation
% regexp -indices -- {[A-Z][a-z]+} "VHDL or Verilog?" idx
1
% set idx
8 14
% string range "VHDL or Verilog? [lindex $idx 0] [lindex $idx 1]
Verilog
% regexp -indices -- {[A-Z][a-z]+} "VHDL or Verilog?" idx
1
% set idx
8 14
% string range "VHDL or Verilog? [lindex $idx 0] [lindex $idx 1]
Verilog
indices or the first and the last character of the matched string
8.13
Copyright © 2024 Abdelazeem Tcl Training
Regular Expressions (tre1) 8.13
Example: Searching for All Occurrences
• Find all entity port lines
– Use matched pattern indices to resize the search buffer
...
set buf $add
set llist ""
while {[regexp -nocase -indices -- <port_RE> $buf idx]} {
# store matched port line
lappend llist [string range $buf [lindex $idx 0] [lindex $idx 1]]
# resize the search buffer
set buf [string range $buf [expr [lindex $idx 1]+1] end]
}
...
...
set buf $add
set llist ""
while {[regexp -nocase -indices -- <port_RE> $buf idx]} {
# store matched port line
lappend llist [string range $buf [lindex $idx 0] [lindex $idx 1]]
# resize the search buffer
set buf [string range $buf [expr [lindex $idx 1]+1] end]
}
...
file: examples/find_all_port_lines.tcl
{ *[a-z][a-z0-9_]* *: *(in|out) +[a-z][a-z0-9_]*(([^()]+))?}
Note that since Tcl version 8.3, regexp provides the -start option, which
allows to move the search pointer without the need to manipulate the search
buffer as above.
8.14
Copyright © 2024 Abdelazeem Tcl Training
Regular Expressions (tre1) 8.14
Example: Filtering Command Logs
• Extract warnings from a Simplicity .srr log file
...
Synthesizing work.interface.rtl
@W:"c:lab6interface.vhd":82:39:82:43|Signal aver2 in the sensitivity list is not used in the process
Post processing for work.interface.rtl
...
file: examples/filtercore.srr
proc extract_warnings {f} {
set in_file [open $f r]
while {[gets $in_file line] >= 0} {
if {[regexp @W $line]} {
regexp -nocase -- 
{([a-z_]+.vhd)[0-9:"|]+([a-z_. 0-9]+)} 
$line buf filename msg
puts "$filenamett$msg"
}
}
close $f
}
proc extract_warnings {f} {
set in_file [open $f r]
while {[gets $in_file line] >= 0} {
if {[regexp @W $line]} {
regexp -nocase -- 
{([a-z_]+.vhd)[0-9:"|]+([a-z_. 0-9]+)} 
$line buf filename msg
puts "$filenamett$msg"
}
}
close $f
}
file: examples/extract_warnings.tcl
extracted output
8.15
Copyright © 2024 Abdelazeem Tcl Training
Regular Expressions (tre1) 8.15
String Substitution
• Use regsub for RE-based string substitution
– regsub does not modify the input string
– Returns the number of matched patterns (0 = no match)
• Useful options
– Use -nocase for case-insensitive search
– Use -all to replace ALL matched patterns (global substitution)
% regsub -- {[a-z]+} "cin : std_logic;" "carry_in" new_str
1
% set new_str
carry_in : std_logic;
% regsub -- {[a-z]+} "cin : std_logic;" "carry_in" new_str
1
% set new_str
carry_in : std_logic;
RE pattern to search for input string
variable which will store the
result
replace the matched
pattern with this
regsub syntax
regsub ?switches? exp string subSpec varName
8.16
Copyright © 2024 Abdelazeem Tcl Training
Regular Expressions (tre1) 8.16
Inserting Matched Sub-Strings
• regsub can re-insert the matched sub-strings
– Uses special positional substitution “commands”:
0 or & insert the entire matched string
1 insert the first matched sub-string
2 insert the second matched sub-string
etc.
• Example: changing the bit width
% regsub -- {[0-9]+ +([a-z]+) +([0-9]+)} "vector(7 downto 0)" 
{(n-1) 1 2} new_str
1
% set new_str
vector((n-1) downto 0)
% regsub -- {[0-9]+ +([a-z]+) +([0-9]+)} "vector(7 downto 0)" 
{(n-1) 1 2} new_str
1
% set new_str
vector((n-1) downto 0)
first sub-pattern = 1 second sub-pattern = 2
8.17
Copyright © 2024 Abdelazeem Tcl Training
Regular Expressions (tre1) 8.17
Using REs for Complex Substitutions
• Two-pass processing (collect & substitute)
– regexp to collect the information
– regsub to substitute
• Consider converting all std_logic_vector(0 downto 0)
signals/ports to std_logic
– First we need to find all 1-bit vector signals/ports
– Then substitute
ports/signals: std_logic_vector(0 downto 0) to std_logic
signal assignments: a(0) to a
a <= (others => '0') to a <= '0'
– See examples/vector_to_bit.tcl
8.18
Copyright © 2024 Abdelazeem Tcl Training
Regular Expressions (tre1) 8.18
Quiz 8
• What is the value of new_line ?
(no options, sorry!)
set line "a_in: in std_logic_vector(31 downto 0);"
regsub {(([0-9]+) +(.*) +([0-9]+));} 
$line {(3 to 1);} new_line
puts $new_line
set line "a_in: in std_logic_vector(31 downto 0);"
regsub {(([0-9]+) +(.*) +([0-9]+));} 
$line {(3 to 1);} new_line
puts $new_line
file: examples/quiz8.tcl
Answer
8.19
Copyright © 2024 Abdelazeem Tcl Training
Regular Expressions (tre1) 8.19
LAB 4: VHDL Netlist Hacking
• Write a procedure find_vector_port which will identify the
FIRST bus port in the VHDL design entity
– An example of a VHDL design file is in adder.vhdl
• Example:
% find_vector_port adder.vhdl
First bus port is a
%
% find_vector_port adder.vhdl
First bus port is a
%
entity add is
port (
cin : in std_logic;
a : in std_logic_vector(7 downto 0);
b : in std_logic_vector(7 downto 0);
cout: out std_logic;
sum : out std_logic_vector(7 downto 0);
)
end add;
entity add is
port (
cin : in std_logic;
a_bus : in std_logic_vector(7 downto 0);
b_bus : in std_logic_vector(7 downto 0);
cout : out std_logic;
sum_bus : out std_logic_vector(7 downto 0);
)
end add;
Stage 2: modify the port names
8.20
Copyright © 2024 Abdelazeem Tcl Training
Regular Expressions (tre1) 8.20
LAB 4: VHDL Netlist Hacking (2)
• Stage 1
– Open and read in the entire adder.vhdl file into a variable
– Use regexp to extract the first entity port name, which is a vector
• Construct a regular expression to identify the port name with the
std_logic_vector type
– Print the port name on the terminal
• Stage 2
– Replace regexp with regsub to append _bus string to ALL vector port
names and save the new adder entity into a new file
– Include port indices into the port names, e.g. ain_bus_7_0
– Replace the port bus signals with a number of single-bit signals
labelled with their respective indices, e.g. ain_7, ain_6, etc.
– Replace ALL design bus signals (in entity and architecture)
with single-bit signals (use adder_full.vhdl)
9.1
Copyright © 2024 Abdelazeem Tcl Training
Tcl Scripting for EDA
Tcl in EDA Tools
9.2
Copyright © 2024 Abdelazeem Tcl Training
Tcl in EDA Tools (tet1) 9.2
Aims and Topics
• Aim
– To gain understanding about how Tcl is used in contemporary
EDA tools
• Topics
– Where you can find Tcl interpreters in EDA tools
– Typical uses of Tcl with various EDA tools
9.3
Copyright © 2024 Abdelazeem Tcl Training
Tcl in EDA Tools (tet1) 9.3
Where is My Tcl Interpreter?
• Tcl interpreter is typically embedded in your EDA tool
command console (GUI or command line)
HERE
HERE
HERE
HERE
HERE
HERE
9.4
Copyright © 2024 Abdelazeem Tcl Training
Tcl in EDA Tools (tet1) 9.4
Finding out More about your EDA Tool
• Check the version of the Tcl interpreter
• Check for EDA tool-specific commands and variables
– For example MTI’s simulator-specific commands and variables start
with the mti_ prefix
• Examine the EDA tool-specific Tcl documentation for
tool-specific Tcl functionality and data structures
% info tclversion
8.0
% info patchlevel
8.0.5
% info tclversion
8.0
% info patchlevel
8.0.5
% info commands mti_*
...
% info globals mti_*
...
% info commands mti_*
...
% info globals mti_*
...
info tclversion provides an alternative way to examining the version
of the Tcl interpreter. The same information can be obtained by examining global
variables tcl_version and tcl_patchLevel.
9.5
Copyright © 2024 Abdelazeem Tcl Training
Tcl in EDA Tools (tet1) 9.5
Examples of Tcl-based EDA Tools
• HDL simulation
– MTI/Mentor Graphics ModelSim
– ...
• HDL synthesis
– Synopsys Design Compiler (dc_shell-t)
– Exemplar Logic LeonardoSpectrum
– Cadence Ambit BuildGates
– Synplify Pro
– ...
• Placement & routing
– Altera Quatrus
– ...
9.6
Copyright © 2024 Abdelazeem Tcl Training
Tcl in EDA Tools (tet1) 9.6
LAB 5: Working with a Tcl-enabled EDA Tool
• Please refer to your exercise book for your tool specific
laboratories.
10.1
Copyright © 2024 Abdelazeem Tcl Training
Next Steps
Tcl Scripting for EDA
10.2
Copyright © 2024 Abdelazeem Tcl Training
Tcl Next Steps (tns1) 10.2
What this Course Covered...
• Main topics
– Tcl scripting basics
– Tcl data structures (strings, lists and arrays)
– File I/O, multi-process communication and simple networking
– Regular expressions
– Building Tcl applications
– EDA Tcl scripting
– Appendix:
• Using expect for interacting with command-line programs
• Following the course...
– Several months “hands-on” work to become experienced
10.3
Copyright © 2024 Abdelazeem Tcl Training
Tcl Next Steps (tns1) 10.3
Object
Orientated
Programming
with [incr_Tcl]
Effective
Tcl/Tk
Programming
Suggested Follow-on Training
• Tcl for EDA Scripting
– This course!
• Building Applications with Tcl/Tk
– Using Tk graphics toolkit to add complex multi-
platform GUI's to Tcl scripts with the minimum
of code
• Effective Tcl/Tk Programming
– More advanced application development using
Tcl/Tk
• Object Orientated Programming with [incr_Tcl]
– Adding object orientated features to Tcl
applications using the [incr_Tcl] extension
Building
Applications
with Tcl/Tk
Tcl for EDA
Scripting
3 day workshop covering the the use of Tcl with Tk - the graphics toolkit
extensions to Tcl. Tk allows the designer to add complex multi-platform Graphical
User Inferfaces (GUI's) to Tcl scripts, using the minimum of code. Tk is used by
many EDA companies to define their tool GUI's.
Effective Tcl/Tk Programming
2 day workshop covering advanced design and coding techniques for creating
complete and effective Tcl/Tk applications
Object Orientated Programming with [incr_Tcl]
[incr_Tcl] is the object orientated extension to Tcl. This workshop examines the
features of [incr_Tcl] and shows how to take advantage of them in your
applications.
10.4
Copyright © 2024 Abdelazeem Tcl Training
Tcl Next Steps (tns1) 10.4
What About Tk ?
• Tk is a simple but powerful Tool Kit for GUI programming
• Supports different window systems
– UNIX
– Windows 95/98/NT/2000
– Macintosh
• Try this:
• Tk provides a set of Tcl commands to create window “widgets”
$ wish
% button .b -text "Hello World!" -command exit
.b
% pack .b -padx 4 -pady 6
%
$ wish
% button .b -text "Hello World!" -command exit
.b
% pack .b -padx 4 -pady 6
%
UNIX (Solaris)
Windows 2000
10.5
Copyright © 2024 Abdelazeem Tcl Training
Tcl Next Steps (tns1) 10.5
Tcl/Tk Resources
• Internet
– Tcl distributions (source & binary), contributed software archive,
discussion lists, books, documentation, tutorials, etc.
• dev.scriptics.com (tcl.activestate.com)
• cui.unige.ch/eao/www/TclTk.html
• www.sco.com/Technology/tcl/Tcl.html
• www.tcltk.com
• www.neosoft.com/tcl
• expect.nist.gov
• www.tclforeda.net
– newsgroup
• comp.lang.tcl
• Books
– tcl.activestate.com/resource/doc/books
There are many resources available to Tcl application developers. Some of the popular
websites are listed here. Feel free to use your favourite Internet search engine to discover
more.
comp.lang.tcl is an on-line discussion forum for Tcl scripting related issues. If your
company does not provide a news server access, you might want to use one of the public
news services, e.g. try Google at
http://groups.google.com/groups?group=comp.lang.tcl
10.6
Copyright © 2024 Abdelazeem Tcl Training
10.7
Copyright © 2024 Abdelazeem Tcl Training
10.8
Copyright © 2024 Abdelazeem Tcl Training
Tcl Next Steps (tns1) 10.8
This slide is left intentionally blank.
11.1
Copyright © 2024 Abdelazeem Tcl Training
Tcl Scripting for EDA
Appendix A:
From Scripts to Applications
11.2
Copyright © 2024 Abdelazeem Tcl Training
From Scripts to Applications (tsa1) 11.2
Aims and Topics
• Aim
– Expand the knowledge of Tcl to enable building complex, robust
and portable scripting applications
• Topics
– Tcl scripts versus applications
– Command-line arguments & environment variables
– Advanced procedures
– Variable scope
– Error handling
– Date & time in Tcl
– Scheduling and delaying command execution
– Script profiling
– Distributing Tcl scripts
11.3
Copyright © 2024 Abdelazeem Tcl Training
From Scripts to Applications (tsa1) 11.3
Tcl Script versus Tcl Application
• Tcl script is simply a collection of Tcl commands, which do
something more or less useful
• Tcl application includes one or more Tcl scripts, which can be
used as a robust stand-alone application
– Invoked similarly to “ordinary” programs
– Handles command-line arguments
– Provides access to native platform’s environment
– Easily distributed and installed
11.4
Copyright © 2024 Abdelazeem Tcl Training
From Scripts to Applications (tsa1) 11.4
• MsWindows/Macintosh Tcl Scripts
– Double-click a Tcl source file to execute it
• UNIX Tcl Scripts
– Use the #!<pathname> to specify the full path to the interpreter...
– ...or for better portability use the UNIX shell to search the $PATH
#!/usr/local/bin/tclsh
puts "Hello World!"
#!/usr/local/bin/tclsh
puts "Hello World!"
#!/bin/sh
# DO NOT REMOVE: 
exec tclsh "$0" "$@"
puts "Hello World!"
#!/bin/sh
# DO NOT REMOVE: 
exec tclsh "$0" "$@"
puts "Hello World!"
Executing Tcl Scripts as Ordinary Programs
full path to the Tcl interpreter
which will execute this Tcl script
full path to the UNIX shell
which will invoke the Tcl
interpreter on this script
Tcl script starts here
IMPORTATNT!
(escaped newline)
On Windows all .tcl files are associated with a Tcl/Tk interpreter called wish. If you
want to use only the plain Tcl interpreter, you may re-define this file association
using the Windows Explorer (File Manager) application.
11.5
Copyright © 2024 Abdelazeem Tcl Training
From Scripts to Applications (tsa1) 11.5
Command-Line Arguments
• Very useful for customizing Tcl script behavior from
a command-line
• Command-line arguments passed to Tcl scripts are stored
in the following special global variables
argv Tcl list of all command-line arguments
argc number of command-line arguments (= llength $argv)
argv0 script name
• Example
% tclsh examples/cmd_line_args -file mp3.vhdl -dir synth_run.12
argv = -file mp3.vhdl -dir synth_run.12
argc = 4
argv0 = examples/cmd_line_args
%
% tclsh examples/cmd_line_args -file mp3.vhdl -dir synth_run.12
argv = -file mp3.vhdl -dir synth_run.12
argc = 4
argv0 = examples/cmd_line_args
%
argv0 argv
11.6
Copyright © 2024 Abdelazeem Tcl Training
From Scripts to Applications (tsa1) 11.6
Dealing with Platform-Specific Code
• Use the global tcl_platform array to obtain information
about the host platform
• Typical
example
proc platform_details {} {
global tcl_platform
puts "Machine:t $tcl_platform(machine)"
puts "Platform:t $tcl_platform(platform)"
puts "OS:tt $tcl_platform(os) $tcl_platform(osVersion)"
puts "Byte order:t $tcl_platform(byteOrder)"
}
proc platform_details {} {
global tcl_platform
puts "Machine:t $tcl_platform(machine)"
puts "Platform:t $tcl_platform(platform)"
puts "OS:tt $tcl_platform(os) $tcl_platform(osVersion)"
puts "Byte order:t $tcl_platform(byteOrder)"
}
file: examples/platform_details.tcl
proc edit {filename} {
global tcl_platform
switch $tcl_platform(platform) {
windows {exec notepad.exe $filename &}
unix - linux {exec nedit $filename &}
}
}
proc edit {filename} {
global tcl_platform
switch $tcl_platform(platform) {
windows {exec notepad.exe $filename &}
unix - linux {exec nedit $filename &}
}
}
file: examples/edit.tcl
11.7
Copyright © 2024 Abdelazeem Tcl Training
From Scripts to Applications (tsa1) 11.7
Accessing Environment Variables
• Use global env array to access system environment variables
• Processes started from the current Tcl interpreter will
inherit the environment variables
– Tcl can be used to customise system variables for invoked
external programs
% set env(PATH)
/usr/bin:/bin/:/usr/local/bin
% set env(LM_LICENSE_FILE)
/nfs/cad/mentor/licenses/license.dat
% set env(PATH)
/usr/bin:/bin/:/usr/local/bin
% set env(LM_LICENSE_FILE)
/nfs/cad/mentor/licenses/license.dat
% info exists env(EDITOR)
0
% set env(EDITOR) "nedit"
nedit
% info exists env(EDITOR)
0
% set env(EDITOR) "nedit"
nedit
check for existence of an environment variable
modify the value of an environment variable
11.8
Copyright © 2024 Abdelazeem Tcl Training
From Scripts to Applications (tsa1) 11.8
Procedures Revisited
• Procedures can have optional arguments
– Possible to write one procedure for many uses
• Using procedures with optional arguments
proc print_log {{fid stdout} {prefix LOG:}} {
global log
foreach line $log {
puts $fid "$prefix $line"
}
}
proc print_log {{fid stdout} {prefix LOG:}} {
global log
foreach line $log {
puts $fid "$prefix $line"
}
}
default value for fid default value for prefix
% print_log
LOG: ...
...
% print_log $open_fid
% print_log $open_fid SYNTH:
% print_log
LOG: ...
...
% print_log $open_fid
% print_log $open_fid SYNTH:
print_log can have 0, 1 or 2 arguments
Use optional procedure arguments
to improve Tcl code re-use,
readability and maintainability.
11.9
Copyright © 2024 Abdelazeem Tcl Training
From Scripts to Applications (tsa1) 11.9
Variable Number of Arguments
• Use special argument args to absorb all argument values not
matched by the preceding arguments
– Useful for parsing command switches, reusing procedure code, etc.
– args is an ordinary Tcl list
proc print_log_args {fid args} {
global log
set prefix "LOG:"; set header "";
foreach {option value} $args {
switch -- $option {
-prefix {set prefix $value}
-header {set header $value}
default {puts "ERROR: Unknown option "$option"."; return;}
}
}
if {$header != ""} {puts $fid $header}
foreach line $log {puts $fid "$prefix $line"}
}
proc print_log_args {fid args} {
global log
set prefix "LOG:"; set header "";
foreach {option value} $args {
switch -- $option {
-prefix {set prefix $value}
-header {set header $value}
default {puts "ERROR: Unknown option "$option"."; return;}
}
}
if {$header != ""} {puts $fid $header}
foreach line $log {puts $fid "$prefix $line"}
}
file: examples/print_log.tcl
args must be the LAST argument
parsing command options stored in the args list
default option values
11.10
Copyright © 2024 Abdelazeem Tcl Training
From Scripts to Applications (tsa1) 11.10
Variable Number of Arguments (2)
• Using print_log with variable arguments
% print_log_args stdout
LOG: ...
...
% print_log_args stdout -prefix "PLACE & ROUTE:"
PLACE & ROUTE: ...
...
% print_log_args stdout -prefix "PLACE & ROUTE:" -header "Design P&R Log"
Design P&R Log
PLACE & ROUTE: ...
...
% print_log_args stdout -bad_option
Unknown option "-bad_option"
% print_log_args stdout
LOG: ...
...
% print_log_args stdout -prefix "PLACE & ROUTE:"
PLACE & ROUTE: ...
...
% print_log_args stdout -prefix "PLACE & ROUTE:" -header "Design P&R Log"
Design P&R Log
PLACE & ROUTE: ...
...
% print_log_args stdout -bad_option
Unknown option "-bad_option"
args (2 elements)
args (4 elements)
args (1 element)
args (0 elements)
fid
11.11
Copyright © 2024 Abdelazeem Tcl Training
From Scripts to Applications (tsa1) 11.11
Variable Scope
• global command provides access to variables at global
level only
• upvar command allows accessing variables at ANY level
– typically used for passing variables by reference
proc print_log_upvar {fid log_var args} {
upvar 1 $log_var log
...
foreach line $log {puts $fid "$prefix $line"}
}
proc print_log_upvar {fid log_var args} {
upvar 1 $log_var log
...
foreach line $log {puts $fid "$prefix $line"}
}
file: examples/print_log_upvar.tcl
sets visibility level, 1 = one level UP (default)
variable $log_var becomes visible via a local variable log
% print_log_upvar stdout sim_log
LOG: ...
...
% print_log_upvar stdout sim_log
LOG: ...
...
variable sim_log becomes visible inside print_log_upvar
11.12
Copyright © 2024 Abdelazeem Tcl Training
From Scripts to Applications (tsa1) 11.12
Generating Application Errors
• Error messages can be generated with puts
• Tcl also provides a robust error reporting mechanism using
the error Tcl command
errorInfo global variable which stores the stack trace
after an error occurred
errorCode global variable which holds the error code
of the last error
proc print_log_error {fid log_var args} {
...
switch -- $option {
-prefix {set prefix $value}
-header {set header $value}
default {error "ERROR: Unknown option "$option".";}
}
}
...
}
proc print_log_error {fid log_var args} {
...
switch -- $option {
-prefix {set prefix $value}
-header {set header $value}
default {error "ERROR: Unknown option "$option".";}
}
}
...
}
file: examples/print_log_error.tcl
terminates immediately and returns the error message.
errorInfo and errorCode variables are set appropriately
11.13
Copyright © 2024 Abdelazeem Tcl Training
From Scripts to Applications (tsa1) 11.13
• Query the current time
• Convert date strings to seconds (mm/dd/yy)
• Convert seconds to date strings:
Handling Date and Time
% clock seconds
1004945376
% clock seconds
1004945376 time measured as seconds from fixed starting time
(usually January 1, 1970)
% clock scan "10/17/00"
971733600
% clock scan "10/17/00"
971733600
clock scan understands many different formats
% clock format 971733600
Tue Oct 17 00:00:00 Romance Daylight Time 2000
% clock format 971733600 -format "%B %d, %Y is in week #%U"
October 17, 2000 is in week #42
% clock format [clock seconds]
Thu Oct 12 16:49:22 Romance Daylight Time 2000
% clock format 971733600
Tue Oct 17 00:00:00 Romance Daylight Time 2000
% clock format 971733600 -format "%B %d, %Y is in week #%U"
October 17, 2000 is in week #42
% clock format [clock seconds]
Thu Oct 12 16:49:22 Romance Daylight Time 2000
11.14
Copyright © 2024 Abdelazeem Tcl Training
From Scripts to Applications (tsa1) 11.14
Inserting Delays
• Use after command to insert delays or to schedule scripts
for execution in the future
• Typical uses
– Wait for another process to complete
– Periodic tasks
– Simulated user input
• Examples
% after 1000
% after 5000 {puts "Job done."}
after#1
% vwait event-loop
Job done.
% after 1000
% after 5000 {puts "Job done."}
after#1
% vwait event-loop
Job done.
sleep for 1000 milliseconds, then return
returns immediately, but schedules execution of
a Tcl script 5000 milliseconds from now
tclsh must enter the EVENT LOOP in order to
execute all pending scripts
11.15
Copyright © 2024 Abdelazeem Tcl Training
From Scripts to Applications (tsa1) 11.15
Script Performance Profiling
• Use time command to evaluate the average execution time
over 1 or more iterations
• Typical uses
– Performance profiling
– Collecting timing statistics
• Examples
% time {my_command}
180000 microseconds per iteration
% time {my_command} 100
256310 microseconds per iteration
% time {my_command}
180000 microseconds per iteration
% time {my_command} 100
256310 microseconds per iteration
time command execution over 1 iteration (default)
time command execution over 100 iterations
11.16
Copyright © 2024 Abdelazeem Tcl Training
From Scripts to Applications (tsa1) 11.16
Tcl Application Distribution
• Tcl application includes the following elements
– Tcl script files
– Any other files (data, setup, etc.)
– Tcl interpreter (?)
• Tcl application can be easily packaged with TclPro
• No need to distribute the Tcl interpreter if a compatible
interpreter is available on the target platform
– Check the Tcl version to guard against unexpected errors
if {![string match 8.* $tcl_version]} {
puts "Error: incompatible Tcl version $tcl_version"
exit
}
if {![string match 8.* $tcl_version]} {
puts "Error: incompatible Tcl version $tcl_version"
exit
}
global variable with Tcl version string (e.g. 8.0)
11.17
Copyright © 2024 Abdelazeem Tcl Training
From Scripts to Applications (tsa1) 11.17
Tcl Packages
• Rather than source-ing each script required for the
application, the scripts can be put into a package
– Request access to the package commands using package require
• Defining packages
– Insert package provide abdelazeem 1.0 in each Tcl script to become
part of the abdelazeem package
– Run pkg_mkIndex . *.tcl in the package directory to create the
package index file (pkgIndex.tcl)
– Update auto_path global variable to include the package directory
1.0
% to_bits 9
1001
%
% package require Abdelazeem
1.0
% to_bits 9
1001
use to_bits from the package
All Tcl scripts in the examples directory, which define procedures were included in
package.
For an example of the package index file, look in examples/pkgIndex.tcl
11.18
Copyright © 2024 Abdelazeem Tcl Training
From Scripts to Applications (tsa1) 11.18
Quiz 9
• What is the number printed by puts ?
(a) none (empty string)
(b) 0
(c) 1
(d) 4
(e) 5
(f) this will generate a syntax error!
proc cell_count {args} {
return [llength $args]
}
set cells [list and2 or2 xor2 inv]
puts "Number of cells: [cell_count $cells]"
proc cell_count {args} {
return [llength $args]
}
set cells [list and2 or2 xor2 inv]
puts "Number of cells: [cell_count $cells]"
file: examples/quiz9.tcl
Answer
12.1
Copyright © 2024 Abdelazeem Tcl Training
Tcl Scripting for EDA
Appendix B:
Binary Files and Strings
12.2
Copyright © 2024 Abdelazeem Tcl Training
Binary Files and Strings (tbf1) 12.2
Aims and Topics
• Aim
– Learn about handling binary data using Tcl
• Topics
– Reading and writing binary files
– Binary strings
12.3
Copyright © 2024 Abdelazeem Tcl Training
Binary Files and Strings () 12.3
Reading and Writing Binary Files
• When accessing binary files, the automatic end-of-line
conversion must be switched off!
• Use fconfigure to change properties
of an open channel
– Automatic end-of-line conversion
– End-of-file character
– Channel blocking and buffering
⇒Channel properties can be changed
at ANY TIME during channel access
set fid [open "bitstream.bit" r]
fconfigure $fid -translation binary
set bitstream [read $fid]
binary scan $bitstream H* bitstream
close $fid
set fid [open "bitstream.bit" r]
fconfigure $fid -translation binary
set bitstream [read $fid]
binary scan $bitstream H* bitstream
close $fid
change the translation
mode for $fid channel to
BINARY (i.e. no newline
conversion)
file: examples/bitstream.tcl
0
0
1
1
0
1 0
1
1
1 0
1
1
0
1
1
0
When accessing binary files in Tcl, it is important to remember to switch off the
default automatic end-of-line translation.
12.4
Copyright © 2024 Abdelazeem Tcl Training
Binary Files and Strings (tbf1) 12.4
• Binary strings can hold characters of ANY value
– Similar to “normal” Tcl strings
– Some string commands don’t work with binary strings
– Use backslash substitution to specify binary values or ...
Binary Strings
% set binary_data "x03x04x05"
♥♦♣
% set binary_data "x03x04x05"
♥♦♣
output will vary depending on the terminal & platform
remember me?
Binary strings can be manipulated in the same way as “usual” text strings, i.e. they
can be constructed using substitution or using the append command and
compared using ==.
However, only the following string commands are guaranteed to work with binary
strings:
string index, string range, string length
It is therefore sometimes desirable to convert binary strings into normal Tcl
strings.
12.5
Copyright © 2024 Abdelazeem Tcl Training
Binary Files and Strings (tbf1) 12.5
Converting Binary Strings
• ... use the binary Tcl command to convert binary values
to/from their equivalent string representation
% set binary_data [binary format H* "030405"]
♥♦♣
% binary scan "x03x04x05" H* hex_data
1
% set hex_data
030405
% set binary_data [binary format H* "030405"]
♥♦♣
% binary scan "x03x04x05" H* hex_data
1
% set hex_data
030405
string → binary conversion
binary → string conversion
returns the number
of conversions performed
hex conversion specifier
(high-to-low order)
binary command can be used to convert binary strings into a variety of text
strings.
binary format syntax:
binary format formatString ?arg arg ...?
12.6
Copyright © 2024 Abdelazeem Tcl Training
Binary Files and Strings (tbf1) 12.6
The Power of binary
• binary command simplifies manipulation of binary values
– Converts binary values to different ASCII formats
• character, string, decimal, hexadecimal, octal, bit
– Converts between different representations of binary values
• little ↔ big endian
• Generic to_bits (LAB 1) using binary
proc to_bits {num} {
binary scan [binary format I $num] B* bits
return [string trimleft $bits 0]
}
proc to_bits {num} {
binary scan [binary format I $num] B* bits
return [string trimleft $bits 0]
}
bit conversion specifier
(high-to-low order)
32-bit integer conversion specifier
(big endian order)
trims away unnecessary leading
0’s
file: examples/to_bits.tcl
binary scan syntax
Use hexdump (provided in examples/hexdump.tcl) to visualize the contents of a
binary string.
binary scan string formatString ?varName varName ...?
13.1
Copyright © 2024 Abdelazeem Tcl Training
Tcl Scripting for EDA
Appendix C:
Client-Server Applications
and Networking
13.2
Copyright © 2024 Abdelazeem Tcl Training
Client-Server Applications and Networking (tcs1) 13.2
Aims and Topics
• Aim
– Expand the knowledge of Tcl multi-process communication to include
client-server and networking applications
• Topics
– Client-server applications
– Safe interpreters
– Simple networking
13.3
Copyright © 2024 Abdelazeem Tcl Training
Client-Server Applications and Networking (tcs1) 13.3
Multi-Process Communication
HDL
Simulator
HDL
Simulator
Hardware
test rig
Hardware
test rig
commands
results
% set fid [open "| test_rig" r+]
file24
% fconfigure $fid -buffering line
% puts $fid "test1 100"
% gets $fid
test1: 1000
% puts $fid "test2 200"
% gets $fid
test2: 400
% close $fid
% set fid [open "| test_rig" r+]
file24
% fconfigure $fid -buffering line
% puts $fid "test1 100"
% gets $fid
test1: 1000
% puts $fid "test2 200"
% gets $fid
test2: 400
% close $fid
Hardware
test rig
Hardware
test rig
read/write mode (bi-directional communication)
external program
(can be another Tcl script!)
CLIENT SERVER
IMPORTANT: set-up LINE buffering
(FULL buffering is the default for files)
The above is the example of SYNCHRONOUS communication, i.e. the client
application always waits for the response from the server before proceeding
further.
Tcl can be also used to build ASYNCHRONOUS communication channels, which
are typically used in servers and GUI applications.
13.4
Copyright © 2024 Abdelazeem Tcl Training
Client-Server Applications and Networking (tcs1) 13.4
Server Application in Tcl
while {[gets stdin line] >= 0} {
set cmd [lindex $line 0]; set data [lindex $line 1]
switch -- $cmd {
test1 {
# perform test1
set result [expr $data * 10]
puts "test1: $result"
}
test2 {
# perform test2
set result [expr $data * 2]
puts "test2: $result"
}
default {
puts "Error: unrecognized command"
}
}
}
while {[gets stdin line] >= 0} {
set cmd [lindex $line 0]; set data [lindex $line 1]
switch -- $cmd {
test1 {
# perform test1
set result [expr $data * 10]
puts "test1: $result"
}
test2 {
# perform test2
set result [expr $data * 2]
puts "test2: $result"
}
default {
puts "Error: unrecognized command"
}
}
}
file: examples/test_rig.tcl
test1 procedure goes here
test2 procedure goes here
Always handle unrecognized
input to avoid server locking.
command-line parsing
Notice that in the above example a considerable amount of Tcl code is used to
parse server commands. In order to improve efficiency, it would be better to define
all server commands as Tcl commands and then use Tcl parsing and error
checking capabilities.
13.5
Copyright © 2024 Abdelazeem Tcl Training
Client-Server Applications and Networking (tcs1) 13.5
Using Tcl as a Command Parser
proc test1 {data} {
# perform test1
set result [expr $data * 10]
return "test1: $result"
}
proc test2 {data} {
# perform test2
set result [expr $data * 2]
return "test2: $result"
}
while {[gets stdin line] >= 0} {
if {[catch $line result] != 0} {
puts "Error: $result"
} else {
puts $result
}
}
proc test1 {data} {
# perform test1
set result [expr $data * 10]
return "test1: $result"
}
proc test2 {data} {
# perform test2
set result [expr $data * 2]
return "test2: $result"
}
while {[gets stdin line] >= 0} {
if {[catch $line result] != 0} {
puts "Error: $result"
} else {
puts $result
}
}
file: examples/test_rig2.tcl
catch will evaluate the Tcl
script in $line and store its
result in result. Returns 0 on
success, 1 otherwise.
Use Tcl interpreter to parse
commands to improve efficiency
there is no need to change the
server's parsing code when new
commands are added
catch syntax catch script ?varName?
13.6
Copyright © 2024 Abdelazeem Tcl Training
Client-Server Applications and Networking (tcs1) 13.6
But How Safe is your Tcl Interpreter?
• SAFE Tcl interpreters provide protection against harmful
scripts
– Create safe interpreters using the interp command
CLIENT
CLIENT SERVER
SERVER
cd ~; file delete -force .
% interp create -safe safe_parser
safe_parser
% safe_parser eval $script
...
% interp create -safe safe_parser
safe_parser
% safe_parser eval $script
... safe_parser
Tcl interpreter
safe_parser
Tcl interpreter
$script
hides all “dangerous” commands
main
Tcl interpreter
main
Tcl interpreter
interp create syntax
slave eval syntax
When attempting to invoke a “dangerous” Tcl command (e.g. exec, file, open) in
a safe interpreter, the command is simply not recognized and the interpreter will
return an error.
It is always a good idea to examine Tcl scripts you receive from your friends and
colleagues by running them in a safe Tcl interpreter. You can use check_script
command from examples/check_script.tcl to do this for you.
% source examples/check_script.tcl
% check_script unknown_script.tcl
invalid command name "file"
% source examples/check_script.tcl
% check_script unknown_script.tcl
invalid command name "file"
interp create ?-safe? ?--? ?path?
slave eval arg ?arg?
13.7
Copyright © 2024 Abdelazeem Tcl Training
Client-Server Applications and Networking (tcs1) 13.7
Safe Server Command Parser
proc test1 {data} {
...
}
proc test2 {data} {
...
}
interp create -safe safe_parser
safe_parser alias test1 test1
safe_parser alias test2 test2
while {[gets stdin line] >= 0} {
if {[catch {safe_parser eval $line} result] != 0} {
puts "Error: $result"
} else {
puts $result
}
}
proc test1 {data} {
...
}
proc test2 {data} {
...
}
interp create -safe safe_parser
safe_parser alias test1 test1
safe_parser alias test2 test2
while {[gets stdin line] >= 0} {
if {[catch {safe_parser eval $line} result] != 0} {
puts "Error: $result"
} else {
puts $result
}
}
file: examples/test_rig_safe.tcl
When receiving Tcl commands from
another process or machine, always
use SAFE interpreters
slave alias syntax
slave alias srcCmd targetCmd ?arg ...?
13.8
Copyright © 2024 Abdelazeem Tcl Training
Client-Server Applications and Networking (tcs1) 13.8
Introduction to TCP/IP Networking
129.14.234.2 10.140.131.21
8111
8111
80
80
33
33
computer's unique IP address
ports
unique
port number
13.9
Copyright © 2024 Abdelazeem Tcl Training
Client-Server Applications and Networking (tcs1) 13.9
More on Networking
• Port numbers
– < 1024 are reserved
– Other ports are available, but could be used by other applications
(e.g. EDA license servers)
– Port numbers between 8100-9999 are usually OK
• Typical uses of Tcl networking in EDA
– Remote design testing and prototyping
– Co-simulation and co-prototyping
– EDA tool servers, priority-based job queuing
– Interaction with Web servers (with http Tcl package)
13.10
Copyright © 2024 Abdelazeem Tcl Training
Client-Server Applications and Networking (tcs1) 13.10
Client-Server Networking in Tcl
• Networking connections are similar to bi-directional pipes
• Setting-up client/server networking
– Use socket to create network connections (server & client)
– Use fileevent to bind Tcl commands to network channel events
(server & client)
– Use vwait enter-mainloop to start the server (server only)
socket -server server_accept 8111
set ch_id [socket $host 8111]
socket -server server_accept 8111
set ch_id [socket $host 8111]
fileevent $ch_id readable "server_handle $ch_id"
fileevent $ch_id readable "server_handle $ch_id"
vwait enter-mainloop
vwait enter-mainloop
SERVER:
CLIENT:
Tcl procedure to be invoked for each client connection
hostname or IP address of the destination server
port numbers
Tcl procedure to be invoked each time there
is something to be READ from $ch_id
channel condition
enter an indefinite loop
(process events until the value of a non-existent
variable enter-mainloop is changed)
Syntax for the commands above:
socket ?-sever? command ?options? port
socket ?options? host port
fileevent channelId readable ?script?
fileevent channelId writable ?script?
vwait varName
13.11
Copyright © 2024 Abdelazeem Tcl Training
Client-Server Applications and Networking (tcs1) 13.11
Example: A Networked Server
...
interp create -safe safe_parser
...
proc server_accept {ch_id addr port} {
fileevent $ch_id readable "server_handle $ch_id"
fconfigure $ch_id -buffering line
}
proc server_handle {ch_id} {
if {[gets $ch_id line] < 0} {
close $ch_id
} else {
if {[catch {safe_parser eval $line} result] != 0} {
puts $ch_id "Error: $result"
} else {
puts $ch_id $result
}
}
}
socket -server server_accept 8111
vwait enter-mainloop
...
interp create -safe safe_parser
...
proc server_accept {ch_id addr port} {
fileevent $ch_id readable "server_handle $ch_id"
fconfigure $ch_id -buffering line
}
proc server_handle {ch_id} {
if {[gets $ch_id line] < 0} {
close $ch_id
} else {
if {[catch {safe_parser eval $line} result] != 0} {
puts $ch_id "Error: $result"
} else {
puts $ch_id $result
}
}
}
socket -server server_accept 8111
vwait enter-mainloop
file: examples/test_rig_net.tcl
enter an indefinite loop
start the server to listen
on port 8111
invoked each time a client connects
to the server
invoked when there is something
to be read from the channel
13.12
Copyright © 2024 Abdelazeem Tcl Training
Client-Server Applications and Networking (tcs1) 13.12
Tcl Shell as a Networked Client
• Very similar to using bi-directional pipes
• TCP/IP server can be tested using any telnet client
– Easy to test & maintain
– Easy to provide various server front-ends
% set ch_id [socket 127.0.0.1 8111]
sock148
% fconfigure $ch_id -buffering line
% puts $ch_id "test1 100"
% gets $ch_id
test1: 1000
% puts $ch_id "test2 200"
% gets $ch_id
test2: 400
% set ch_id [socket 127.0.0.1 8111]
sock148
% fconfigure $ch_id -buffering line
% puts $ch_id "test1 100"
% gets $ch_id
test1: 1000
% puts $ch_id "test2 200"
% gets $ch_id
test2: 400
open a network connection to the
server with IP address 127.0.0.1
at port number 8111
14.1
Copyright © 2024 Abdelazeem Tcl Training
Tcl Scripting for EDA
Appendix D:
Interacting with
Command-Line Programs
14.2
Copyright © 2024 Abdelazeem Tcl Training
Interacting with Command-Line Programs (tep1) 14.2
Aims and Topics
• Aim
– To learn about using Expect for as a tool for communicating between
interactive command-line programs and a Tcl interpreter
• Topics
– What is Expect?
– Simple communication with an interactive program
– Handling errors and loops
– Regular expressions with Expect
– Expect in EDA scripting
14.3
Copyright © 2024 Abdelazeem Tcl Training
Interacting with Command-Line Programs (tep1) 14.3
What is the Problem?
• Some useful tools exists only as interactive
command-line programs
– Limited command set (e.g. no loops or conditionals)
– Require user input
– Difficult to use for repetitive jobs
• Ever tried using command-line ftp or telnet?
14.4
Copyright © 2024 Abdelazeem Tcl Training
Interacting with Command-Line Programs (tep1) 14.4
Expect
• Automates tasks normally performed
through a terminal
– Removes blocking and buffering problems
by emulating an interactive user session
• Provides Tcl scripting to non-Tcl tools
– Networking, hardware testing, software
and machine administration, etc.
Expect
Expect
Tcl script
14.5
Copyright © 2024 Abdelazeem Tcl Training
Interacting with Command-Line Programs (tep1) 14.5
Example: FTP session
secret password
type this
type this
type this
expect this
expect this
expect this
14.6
Copyright © 2024 Abdelazeem Tcl Training
Interacting with Command-Line Programs (tep1) 14.6
Talking to an FTP client with Expect
if {[llength $argv] < 1} {
puts stderr "Usage: expect any_ftp.tcl <hostname>"
}
set host [lindex $argv 0]
exp_spawn ftp $host
expect "Name"
exp_send "anonymousr"
expect "Password:"
exp_send "secret passwordr"
expect "ftp>"
exp_send "cd pubr"
expect "ftp>"
exp_interact
if {[llength $argv] < 1} {
puts stderr "Usage: expect any_ftp.tcl <hostname>"
}
set host [lindex $argv 0]
exp_spawn ftp $host
expect "Name"
exp_send "anonymousr"
expect "Password:"
exp_send "secret passwordr"
expect "ftp>"
exp_send "cd pubr"
expect "ftp>"
exp_interact
file: examples/any_ftp.tcl
start an ftp client, but redirect its
I/O through expect
use r to simulate a raw carriage
return
let user interact with the ftp client
at this point
14.7
Copyright © 2024 Abdelazeem Tcl Training
Interacting with Command-Line Programs (tep1) 14.7
Handling Errors
...
set host [lindex $argv 0]
set timeout 10
exp_spawn ftp $host
expect {
"Name" {exp_send "anonymousr"}
"unknown host" {return 0}
timeout {return 0}
}
...
...
set host [lindex $argv 0]
set timeout 10
exp_spawn ftp $host
expect {
"Name" {exp_send "anonymousr"}
"unknown host" {return 0}
timeout {return 0}
}
...
file: examples/any_ftp2.tcl
controls how long expect waits for
a match (in seconds)
if matches this... ...then do this
if matches this... ...then do this
no match
after 10 seconds?
...then do this
14.8
Copyright © 2024 Abdelazeem Tcl Training
Interacting with Command-Line Programs (tep1) 14.8
Example: Changing Password Remotely
secret old password
type this
expect this
expect this
secret new password
secret new password
type this
expect this
expect this
expect this
type this
type this
14.9
Copyright © 2024 abdelazeem Tcl Training
Interacting with Command-Line Programs (tep1) 14.9
Regular Expressions in Expect
proc change_remote_passwd {machine user old_pass new_pass} {
...
set prompt "#|$|%|>"
expect {
-re $prompt {exp_send "passwdr"}
timeout {return 0}
}
expect {
"assword:" {exp_send "$old_passr"}
timeout {return 0}
}
...
proc change_remote_passwd {machine user old_pass new_pass} {
...
set prompt "#|$|%|>"
expect {
-re $prompt {exp_send "passwdr"}
timeout {return 0}
}
expect {
"assword:" {exp_send "$old_passr"}
timeout {return 0}
}
...
file: examples/rpasswd.tcl
matches any of these
prompt characters
treat $prompt as a regular expression
>
%
$
#
start up UNIX
passwd program
type in the old password
14.10
Copyright © 2024 Abdelazeem Tcl Training
Interacting with Command-Line Programs (tep1) 14.10
Looping in Expect
proc change_remote_passwd {machine user old_pass new_pass} {
...
set times 0
expect {
"new [Pp]assword:" {
incr times
if {$times > 2} {
return 0
}
exp_send "$new_passr"
exp_continue
}
"tokens updated successfullyrn" {return 1}
timeout {return 0}
}
}
proc change_remote_passwd {machine user old_pass new_pass} {
...
set times 0
expect {
"new [Pp]assword:" {
incr times
if {$times > 2} {
return 0
}
exp_send "$new_passr"
exp_continue
}
"tokens updated successfullyrn" {return 1}
timeout {return 0}
}
}
file: examples/rpasswd.tcl
glob-style search pattern
type in new password TWICE
success!
repeat the pattern search
14.11
Copyright © 2024 Abdelazeem Tcl Training
Interacting with Command-Line Programs (tep1) 14.11
Expect in EDA Scripting
• Many EDA tools and utilities are command-line driven
– HDL simulation
– HDL synthesis
– Placement & routing
– Generation & customization of IP cores
– File format conversion, back-annotation, etc.
– Programs for driving test beds, prototyping boards, etc.
• With Expect is it easy to integrate all these tools
– Integrate design & test flows
– Combine EDA tools with standard OS utilities (networking, system
monitoring, backup, job management, etc.)
14.12
Copyright © 2024 Abdelazeem Tcl Training
Interacting with Command-Line Programs (tep1) 14.12
LAB 6: Interaction with a Synthesis Server
• Write a procedure submit_synthesis_job which will FTP the
design file design.vhdl and its synthesis script
design_synthesis.tcl to a server, directory ~/incoming.
• Stage 1
– Choose an FTP server on your local network to which you have access
(localhost will do) and:
• Create directories ~/incoming and ~/results
• Start examples/synth_server on this server
– Test the operation of the FTP client first by hand
• Upload the design files using
ftp> put design_*
• Collect any useful messages you EXPECT
– Write an Expect Tcl script for this job
14.13
Copyright © 2024 Abdelazeem Tcl Training
Interacting with Command-Line Programs (tep1) 14.13
LAB 6: Interaction with a Synth. Server (2)
• Stage 2
– Check in 60-second intervals whether the ~/results directory contains
design_results.log. Once present, download all design_* files from
the /results directory.
• Check for design_results.log using
ftp> get design_results.log
• Use after 60000 to delay script execution for 60 seconds
– After the files were received, start-up an editor with received
design_results.log
– Send user an e-mail message that the job was completed
14.14
Copyright © 2024 Abdelazeem Tcl Training
Have you read "Palestine + 100: Stories from a Century after
the Nakba" edited by Basma Ghalayini?
Tcl Training i
Tcl Scripting for EDA Index
Note: the course is structured such that information on a particular construct is usually
spread over several consecutive pages. Where this occurs, only the first page of the set is
listed in this index
Symbols
"" quotes
grouping, 2-5, 3-14
use of, 3-15
$ dollar
variable substitution, 2-11
& ampersand
process, 7-19
() parentheses
expressions, 3-5
math functions, 3-7
regular expression, 8-8, 8-9
* asterisk
regular expression, 8-5
/ slash
directory separator, 3-12
[] brackets
command substitution, 2-16
grouping, 2-18
regular expression, 8-5
 backslash
b backspace, 2-14
n newline, 2-14, 7-12
regular expression, 8-9
special characters, 2-14
substitution, 2-13
{} braces
grouping, 2-5, 3-14
if, 4-16
use of, 3-15
| pipe
process, 7-19
regular expression, 8-8, 8-9
A
after, 11-14
append, 5-4
argc, 11-5
args, 11-9, 11-10
argv, 11-5
argv0, 11-5
array, 6-17
multi-dimensional, 6-20, 6-22
versus list, 6-23
array exists, 6-21
array get, 6-19
array names, 6-21
array set, 6-19, 6-22
array size, 6-21
auto_noexec, 7-15
auto_path
package, 11-17
B
backslash
substitution, 2-13
binary, 12-5
file, 12-3
string, 12-4
bit-wise
operators, 3-5
break, 4-3, 4-14, 4-15
buffering, 7-13
process, 7-20, 13-3
C
catch, 7-5, 13-5
cd, 3-12
channel
buffering, 7-13
identifier, 7-4
characters
special, 2-14
client-server, 13-10
clock, 11-13
close, 7-4
command
Tcl Training ii
evaluation, 2-9, 2-19, 2-20
substitution, 2-16
comparison
operators, 3-5
concat, 6-8
continue, 4-3, 4-14, 4-15
D
decrement, 3-8
default, 4-7
E
else, 4-5, 4-6
elseif, 4-6
end of file (eof), 7-11
env, 11-7
eof, 7-11
error, 11-12
eval, 7-16, 7-17
exact
lsearch, 6-12, 6-13
switch, 4-8
exec, 7-15, 7-16, 7-17
exp_interact, 14-6
exp_send, 14-6
exp_spawn, 14-6
expect, 14-4, 14-6, 14-11
loop, 14-10
regular expressions, 14-9
expr, 3-4
expression
regular, 8-3
F
fconfigure, 7-14, 7-20, 12-3, 13-3
file
binary, 12-3
command, 7-3
descriptor, 7-4
id, 7-4
pointer, 7-7
portability, 7-12
read, 7-8, 7-10
translation, 12-3
write, 7-6
fileevent, 13-10
flush, 7-14
for, 4-3, 4-10, 4-11, 4-15
foreach, 4-3, 4-11, 4-12, 4-15
format
clock, 11-13
string, 5-10
functions
mathematical, 3-7
G
gets, 7-8
glob, 3-12, 5-7, 7-16, 7-17
lsearch, 6-12, 6-13
switch, 4-8
global variable, 3-11, 11-11
grouping
"", 2-5, 3-14
[], 2-18
{}, 2-5, 3-14
use of "" and {}, 3-15
I
if, 4-3, 4-4, 4-5, 4-6, 4-15
incr, 3-8
increment, 3-8
index file
package, 11-17
indices
regular expression, 8-12
info, 1-11, 9-4
interp, 13-6
interpretation, 2-4, 3-13
J
join, 6-11
L
lappend, 6-7
lindex, 6-4
linsert, 6-9
list, 6-3, 6-6
nested, 6-5
reversal, 6-10
summary, 6-16
versus array, 6-23
Tcl Training iii
llength, 6-4
logical
operators, 3-5
lrange, 6-4
lreplace, 6-9
lsearch, 6-12, 6-13
lsort, 6-14, 6-15
M
mathematical
functions, 3-7
operators, 3-3, 3-5
N
networking, 13-8
newline, 2-14, 7-12
nonewline, 7-6
O
open, 7-4, 7-19, 7-20, 13-3
operators, 3-5
bit-wise, 3-5
comparison, 3-5
logical, 3-5
mathematical, 3-3
P
package, 11-17
pid, 7-19
pipe, 7-18
pipe |, 7-19
precision, 3-9
procedure, 11-8
arguments, 11-9, 11-10
procedures, 3-10
process, 7-19
communication, 7-20, 13-3
provide
package, 11-17
puts, 2-5
write to file, 7-6
pwd, 3-12
R
random numbers, 3-8
read, 7-10
real numbers, 3-4
redirection, 7-18
regexp, 8-6, 8-17
indices, 8-12
lsearch, 6-12, 6-13
nocase, 8-6
switch, 4-8
regsub, 8-15, 8-17
regular expression, 8-3
sub-expression, 8-10
regular expressions
expect, 14-9
require
package, 11-17
resources, 10-5
result, 7-5
S
safe interpreter, 13-6
scan
clock, 11-13
string, 5-11
script, 1-8, 1-9
scripts, 11-3
seconds, 11-13
Seek, 7-7
set, 2-7, 5-4
shift
operators, 3-5
socket, 13-10
split, 6-11
stderr, 7-6
stdin, 7-6
stdout, 7-6
string, 5-3
binary, 12-4
formatting, 5-10
scanning, 5-11
string compare, 5-5, 5-9
string first, 5-12
string index, 5-12
string last, 5-12
string length, 5-12
string match, 5-6, 5-9
string range, 5-12
Tcl Training iv
string tolower, 5-8
string toupper, 5-8
string trim, 5-8
substitution, 2-9, 2-10, 2-12, 2-17
backslash, 2-13
command, 2-16
variable, 2-11
switch, 4-9
switch, 4-3, 4-7, 4-15
multiple pattern match, 4-8
options, 4-8
variable substitution, 4-9
T
tcl_platform, 11-6
tcl_precision, 3-9
tcp/ip, 13-8
time, 11-15
Tk, 10-4
U
unset, 2-7
upvar, 11-11
V
variable, 2-7
environmental, 11-7
global, 3-11, 11-11
name, 2-8
substitution, 2-11
switch, 4-9
upvar, 11-11
value, 2-8
vwait, 11-14, 13-10
W
while, 4-3, 4-13, 4-15
Tcl Scripting for EDA
TCL Lab Exercises
and Case Studies
Contents
INTRODUCTION..............................................................................................................................1
Tool Specific Information...............................................................................................................................1
Conventions....................................................................................................................................................2
Icons ................................................................................................................................................................2
Overview of Labs............................................................................................................................................3
Lab Summary.................................................................................................................................................3
LAB 1 – GENERIC TCL, SYNTHESIS REPORT FILE PARSING................................................4
Looking at the script design ..........................................................................................................................5
Modifying the get_message procedure..........................................................................................................5
LAB 2 – GENERIC TCL, TEST HARNESS BUILDER ..................................................................6
Looking at the script design ..........................................................................................................................9
Adding the ‘findPorts’ procedure...................................................................................................................9
Modifying the ‘entity’ pattern .....................................................................................................................10
LAB 3 – MODELSIM DYNAMIC POWER ESTIMATION...........................................................11
Looking at the script design ........................................................................................................................14
Adding the ‘monitorSingnals’ procedure ....................................................................................................15
Optional ........................................................................................................................................................15
LAB 3 – LEONARDO MULTI-PASS SYNTHESIS .......................................................................16
Looking at the script design ........................................................................................................................20
Completing the procedures..........................................................................................................................21
LAB 4 – SYNPLIFY MULTI-PASS SYNTHESIS..........................................................................22
Looking at the script design ........................................................................................................................25
Completing the procedures..........................................................................................................................26
TCL Scripting Lab Exercises - 1 - © Abdelazeem
2024 Revision
TCL/1.0
Introduction
These lab exercises are designed to make you more familiar with TCL scripting
by using it in some typical EDA scripting situations. They are organized in a
way that takes you step by step through what to do first, and then let you alter
the code to achieve the desired functionality.
Tool Specific Information
The Lab exercises are designed to suit individual requirements. A number of
EDA tools are proposed with corresponding Labs. You can choose which tool
you want to use when you attend a TCL Workshop. Alternatively you can
choose to work on one of the EDA tool-independent Labs. The later Labs will
illustrate the powers of TCL for file/data processing.
TCL Scripting Lab Exercises - 2 - © Abdelazeem
2024 Revision
TCL/1.0
Conventions
Certain conventions are followed in the exercises, that are worth mentioning
before you start.
Icons
Each exercise starts on a new page and is divided into separate clear sections
using icons:
Goals The aims of the exercise.
Scenario
Explains the function of the
script to be created.
Background Info
Discusses specific TCL language
issues that you will need to
understand to write the model.
Recommendations
Explains how to go about writing
the procedures in terms of
arguments, types, etc. Read these
before you move on to.....
Action
This is what you actually do!!
Two additional symbols are used
within the main text, to represent:
i Additional information
? A question to be answered.
TCL Scripting Lab Exercises - 3 - © Abdelazeem
2024 Revision
TCL/1.0
Overview of Labs
The labs are not in any specific sequence. Choose a specific lab according to
your requirements. If time permits, you are welcomed to experiment with any
of the other labs presented in this lab book.
The labs will involve, understanding of the supplied code and the addition of
new functionalities to the existing code. The data structure as well as the
subprograms’ functionality will be explained inside the ‘background info’ and
‘recommendation’ sections of each individual lab.
Lab Summary
Lab 1 : Generic TCL, synthesis report file parsing - an example of the use
of TCL to parse a simple report file and log the error, warning and note
messages.
Lab 2 : Generic TCL, test harness builder - automatically creating a VHDL
test harness template from a top level design.
Lab 3 : ModelSim, dynamic power estimation - performing an analysis of
internal signal toggle count during a simulation.
Lab 4 : Leonardo Spectrum - executing a multi-pass synthesis
Lab 5 : Synplify - executing a multi-pass synthesis
TCL Scripting Lab Exercises - 4 - © Abdelazeem
2024 Revision
TCL/1.0
Lab 1 – Generic TCL, synthesis report file parsing
Goals
The goals of the lab exercise are to familiarize yourself with a typical example
file parsing and information gathering. This example uses a Synplify ‘.srr’ file
however this example can be extended to any synthesis tool with a limited
amount of alterations.
Scenario
Commonly, EDA tools generate lengthy ASCII report files summarizing their
activity. Although the created reports are very thorough, the amount of
information available is often overwhelming for the human eye. As a result, the
user at times overlooks important messages.
The proposed lab example consists in creating a procedure that will be used to
extract specific information from a report file and display them on the screen.
The output value is displayed on the screen (standard output). Alternatively,
the output strings can be directed to a result file.
standard output
file_name
message_type
get_message
TCL Scripting Lab Exercises - 5 - © Abdelazeem
2024 Revision
TCL/1.0
Recommendations
! Data types:
- message_type : (string) notes, warnings, errors
- file_name : (string) filtercore.srr
- standard output : (string)
! ‘Notes’ pattern sample:
@N:"thresh_mux.vhd":106:15:106:26|Removed redundant assignment
! ‘Warnings’ pattern sample:
@W:"nsmask.vhd":31:11:31:19|Input middle_in is unused
! ‘Errors’ pattern sample:
@E:"nsmask.vhd":31:11:31:19|Expecting <=
! Procedure usage: get_message filtercore.srr warnings
Action
Looking at the script design
❏ Files Location: the lab files will are stored in the following directories:
Workstation Users:
<install_path>/tclscript/labs/generictcl
PC Users:
<install_path>tclscriptlabsgenerictcl
Your trainer will tell you the location of the lab files installation
<install_path>
❏ We will work on the file warnings_errors.tcl. Take a look at the file's
contents using a text editor. Check with your instructor to see which text
editors are available, or use your favorite editor.
Modifying the get_message procedure
❏ Complete the ‘get_message’ procedure and test it on the ‘filtercore.srr’
synthesis report file.
❏ Add to the ‘get_message’ procedure a routine that will prevent the same
message to be printed more than once.
TCL Scripting Lab Exercises - 6 - © Abdelazeem
2024 Revision
TCL/1.0
findEntity
Lab 2 – Generic TCL, test harness builder
Goals
The goal of this exercise is to become familiar with how to create complex
parsing patterns for language processing. This example uses a VHDL design as
a source. Once the principles of language processing are understood, the same
techniques can be used for a variety of other languages such as Verilog, EDIF,
and HTML.
No prior knowledge of the VHDL language is required for this lab.
Scenario
Hardware programming languages like VHDL or Verilog require the creation of
test harnesses for the verification of specific designs. The designer usually
creates those test harnesses manually. However, in most cases a large part of
the creation process of a test harness can be automated by gathering
information contained inside the design to be tested.
The proposed lab example consists in improving an existing script to extend its
semantics coverage and the creation of a procedure used to find the ports of a
given design. The general structure of the script is as follows:
findPorts
createTb vhdlDesign
buildTestBench
filtercore.vhd
t_filtercore.vhd
status
(entity)
(ports)
(ports)
(entity)
(line)
(line)
(line)
Procedure call :
Data transfer :
TCL Scripting Lab Exercises - 7 - © Abdelazeem
2024 Revision
TCL/1.0
The ‘createTb’ procedure is the top-level procedure. It implements a state
machine that directs the text line ($line) read from the input file to ether the
procedure ‘findEntity’ or the procedure ‘findPorts’ according to the state, the
state machine is in. The variable ‘status’ is the state variable. The values held
in the variable ‘status’ can be : ‘entity’ ‘ports’ ‘finish’.
The procedure ‘findEntity’, searches the ‘line’ variable for the entity name of the
design. Once the name has been found, it is stored in the variable
‘vhdlDesign(entity)’.
The procedure ‘findPorts’ searches the line variable for ports patterns. Once
ports have been identified, the procedure append the variable list
‘vhdlDesign(ports)’ with the following information: name, direction and type of
the port . For more information, see the ‘Data structure’ topic in the
‘Recommendations’ section.
The procedure ‘buildTestBench’ simply creates the output file from the
information gathered inside the ‘vhdlDesign’ variable. You are welcomed to look
at this procedure although, you will not be asked to do any work on it.
Recommendations
! Data structures:
The main data structure used in this script is called: ‘vhdlDesign’. This variable
is used to hold the name of the entity declared in the original design file
(filtercore.vhd) as well as the port details. The following diagram represents
how the design information is stored inside the vhdlDesign variable.
# Variable declaration
global vhdlDesign
set vhdlDesign(entity) {}
set vhdlDesign(ports) {}
# Variable assignment
set vhdlDesign(entity) “decoder”
lappend vhdlDesign(ports) “a in integer”
lappend vhdlDesign(ports) “b out bit”
entity decoder is
port (a : in integer;
b : out bit);
end decoder;
decoder
a in integer
(entity)
(ports)
vhdlDesign
b out bit
TCL Scripting Lab Exercises - 8 - © Abdelazeem
2024 Revision
TCL/1.0
! VHDL Tokens:
Tokens are commonly used in scanners/parsers to facilitate the building of
complex regular expressions. Here are the tokens defined for this TCL script:
set separator {s}
set nameIdentifier {[a-z][_a-z0-9]*}
set typeIdentifier {[a-z][a-z0-9_ ]*(([a-z0-9_ ]*))*}
set portMode "in|out|inout|buffer"
! VHDL Grammar:
The grammar part of a scanner/parser is used to define a valid set of token
sequences. This is used in regular expressions to extract specific information
from code. Here are the grammar rules defined in the TCL script.
set portPattern "($nameIdentifier)$separator*:$separator*!
($portMode)+$separator+($typeIdentifier)"
This pattern is used to match VHDL port declarations such as :
clk4 : IN STD_LOGIC;
edge_fs : OUT STD_LOGIC;
fs : IN STD_LOGIC;
ack : OUT STD_LOGIC;
enable : IN STD_LOGIC;
wr_nrd : IN STD_LOGIC;
edge : OUT STD_LOGIC;
coef : IN bit_vector(14 downto 0)
Other patterns used in this script are used to detect entity declarations such as:
set entityHead "^$separator*entity$separator+!
($nameIdentifier)$separator+is"
set entityEnd1 "$separator+$nameIdentifier"
set entityEnd "^$separator*end($entityEnd1)?$separator*;"
These patterns will respectively match the following declarations:
entityHead
entityEnd
entity decoder is
port (a : in integer;
b : out bit);
end decoder;
TCL Scripting Lab Exercises - 9 - © Abdelazeem
2024 Revision
TCL/1.0
Action
Looking at the script design
❏ Files Location: the lab files will are stored in the following directories:
Workstation Users:
<install_path>/tclscript/labs/generictcl
PC Users:
<install_path>tclscriptlabsgenerictcl
Your trainer will tell you the location of the lab files installation
<install_path>
❏ We will work on the file testbench.tcl. Take a look at the file's
contents using a text editor. Check with your instructor to see which text
editors are available, or use your favorite editor.
❏ Familiarize yourself with the script. Before modifying the script, you can
execute it to see what it does (look at the generated ‘t_filtercore.vhd’).
Adding the ‘findPorts’ procedure
❏ The first part of this lab consists in adding a procedure called ‘findPorts’
that will be used to store the ports information inside the variable
‘vhdlDesign’. The following diagram represents the data flow for that
function:
The ‘line’ variable is passed from the procedure ‘createTb’. Its value is a
text line (ASCII) extracted from input file currently processed
(filtercore.vhd).
findPorts vhdlDesign
status
(ports)
(line)
TCL Scripting Lab Exercises - 10 - © Abdelazeem
2024 Revision
TCL/1.0
In this procedure you will have to process the ‘line’ to define if it is a port
declaration or not. If so, you will have to store the ports information inside
the variable ‘vhdlDesign’. The processing information has been described
in the recommendation section.
The second operation performed by the ‘findPorts’ procedure is to set the
value of the ‘status’ variable to: ‘finish’ when it detects the end of the
entity declaration such as:
By setting the value of ‘status’ to ‘finish’, this will force the state machine
implemented inside the procedure ‘createTb’ to stop.
❏ One you have made the modifications, run the script and observe the
differences in the resut file ‘t_filtercore.vhd’.
Modifying the ‘entity’ pattern
❏ Although the current ‘entityEnd’ pattern works with the current example,
this grammar can only match two type of entity ending:
‘END;’ Or ‘END filtercore;’
The VHDL language reference manual defines that an entity ending can
also be of the following form:
‘END ENTITY;’ Or ‘END ENTITY filtercore;’
❏ Modify the ‘entityEnd’ pattern to include those two extra kinds of endings.
❏ Modify the ‘filtercore’ entity ending inside the ‘filtercore.vhd’ file to be:
‘END ENTITY;’ or END ENTITY filtercore;’ and validate your new
script.
...
ls : IN STD_LOGIC;
reset : IN STD_LOGIC;
);
END filtercore;
...
ls : IN STD_LOGIC;
reset : IN STD_LOGIC;
);
END ENTITY filtercore;
...
ls : IN STD_LOGIC;
reset : IN STD_LOGIC;
);
END filtercore; entityEnd
portPattern
TCL Scripting Lab Exercises - 11 - © Abdelazeem
2024 Revision
TCL/1.0
Lab 3 – ModelSim Dynamic Power Estimation
Goals
The goal of this exercise is to become familiar with some of the features of
ModelSim’s API. This example is based on a VHDL simulation; this script will
be used to log signal activity during a simulation and report the results of its
analysis.
No prior knowledge of the VHDL language is required for this lab.
Scenario
A large number of current ASIC/FPGA designs require careful considerations of
power consumption aspects. Although a number of specialized EDA tools are
available for dynamic and static power analysis, a simple script run during
simulation can already indicate what are the critical areas of a design. This
estimation is based on the principles of CMOS transistors consumption. The
theory tells us that CMOS based circuit only consume energy during a charge
transfer; in other words during a change of state.
The proposed lab example consists in creating a procedure that will be used to
monitor signals activity at a given hierarchical level of the design during a
simulation. Once the simulation is over the script will display the results using
a graph.
The procedure ‘monitorSignal’ is the top level procedure. It is called with an
argument ‘hierarchy’ that indicates the hierarchy level you want to monitor
inside the design. The procedure ‘monitorSignal’ will extract all the signal
names contained at the specified hierarchical level using the ‘find’ API
command. Once the signal names have been extracted, the procedure will
create an array of counters ‘expendedList’ that will be used to record all the
signals toggle activity. Lastly the procedure will set an individual ‘when’
command for each of the signals encountered at the specified hierarchical level.
This ‘when command is used to record all the signals toggle activity
(concurrently).
The procedure ‘reportSignals’ is used to query the variable ‘expendedList’ and
display the ten most toggled signals.
The following diagram illustrates the script’s architecture:
TCL Scripting Lab Exercises - 12 - © Abdelazeem
2024 Revision
TCL/1.0
describe
reportSignals
Procedure call :
Data transfer :
API Procedure :
monitorSignals
find
signalList signalType
sortedList resultList
expendedList
API
graph.tcl
(hierarchy)
(signal)
(hierarchy)
(maxValue)
(mostLeast)
(toggled signal)
result.txt
when
TCL Scripting Lab Exercises - 13 - © Abdelazeem
2024 Revision
TCL/1.0
Recommendations
! ModelSim’s API:
ModelSim features a large amount of TCL API commands described in
detail in the simulator’s documentation. This script will only feature a few
of those to give you a feel for what you can achieve with scripting.
This is the list of ModelSim commands used in this lab:
- find : This command is used to find objects in the design
o ‘find signal <path>/*’ will return a list of all the
signals at the specified level of hierarchy.
o ‘find signal –r /*’ will extract all the signals of the
design, recursively.
o ‘find nets –in /top/clk*’ will extract all the input
signals at the ‘top’ level starting with a ‘clk’.
- when : Allows to perform commands when a specific condition is
met.
o ‘when { result = “1100”} {puts “error”}’ prints
the message ‘error’ when the value of result reaches
“1100”.
o ‘when {clk’event} {incr a}’ increases the value
of ‘a’ when the signal ‘clk’ has had an event.
- nowhen : This command disable when commands.
o ‘nowhen *’ disables all whens
o ‘nowhen xxx’ disable the ‘when’ labeled xxx
- discribe : Displays information about a specific VHDL item.
o ‘describe clk’ will return the string:
Enum: ('U','X','0','1','Z','W','L','H','-')
When clk is of a std_logic type.
o ‘desicribe dataio’ will return :
Array(15 downto 0) of
Enum: ('U','X','0','1','Z','W','L','H','-')
When dataio is of a std_logic_vector(15 downto 0) type;
! Data types:
- signalList : (list of strings) signal names.
- signalType : (string) type information of a signal (see previous
section ‘describe’ command).
- expendedList : (array) Signal names are used as indexes whilst
the toggle amount is the value.
- resultList: (list of ‘toggle value/ signal’ name pair) a list version of
the values contained in the variable ‘expendedList’.
TCL Scripting Lab Exercises - 14 - © Abdelazeem
2024 Revision
TCL/1.0
- sortedList : numerically sorted version of the variable ‘resultList’.
Action
Looking at the script design
❏ Files Location: the lab files will are stored in the following directories:
Workstation Users:
<install_path>/tclscript/labs/modelsimtcl
PC Users:
<install_path>tclscriptlabsmodelsimtcl
Your trainer will tell you the location of the lab files installation
<install_path>
❏ We will work on the file signalcount.tcl. Take a look at the file's
contents using a text editor. Check with your instructor to see which text
editors are available, or use your favorite editor.
signal a : integer := 0;
signal b : std_logic := ‘0’;
signal c : Boolean := false;
0
0
(a)
(b)
ExpendedList()
0
(c)
incr expendedList(a)
wait for 10 ns;
a <= not a;
wait;
1
0
ExpendedList()
0
(a)
(b)
(c)
Activity on signal ‘a’ results in an increase of its toggle count.
counter
TCL Scripting Lab Exercises - 15 - © Abdelazeem
2024 Revision
TCL/1.0
Adding the ‘monitorSignals’ procedure
❏ Complete the ‘monitorSignals’ procedure using the comments found inside
the script file.
❏ Test the resulting script on the filtercore.srr synthesis report file.
❏ Add to the get_message procedure a routine that will prevent the same
message to be printed more than once.
Optional
❏ If you have some time left, try to improve the ‘monitorSignals’ procedure
by checking if a signal (inside the ‘signalList’ variable) is of an array type;
if so, expend the signal into individual values so that you can create
individual counters for each of the bits of a vector. The following diagram
explains the procedure.
sig_a
dataio
signalList
clk
describe dataio
Array(3 downto 0) of
Enum:
('U','X','0','1','Z','W','L','H','-')
0
0
(sig_a)
(dataio(0))
ExpendedList()
0
(dataio(1))
(dataio(2))
(dataio(3))
(dataio)
(clk)
0
0
0
0
Added
TCL Scripting Lab Exercises - 16 - © Abdelazeem
2024 Revision
TCL/1.0
Lab 3 – Leonardo Multi-pass Synthesis
Goals
The goal of this exercise is to become familiar with some of the features of
Leonardo’s API. This example is based on a VHDL synthesis; this script will be
used to perform a multi-pass synthesis and report the results of its analysis.
No prior knowledge of the VHDL language is required for this lab.
Scenario
Synthesis is often viewed as a simple push-button process. In most cases this
approach is sufficient to achieve the required results. However when dealing
with designs with tight constrains such as area or timing, synthesis becomes a
more involved process. Commonly designers find themselves engaged in
countless synthesis runs involving different sets of synthesis constraints.
Unfortunately, due to the increasing level of complexity of synthesis
algorithms, synthesis constraints combinations that used to lead to specific
improvements are no longer valid.
The proposed lab example consists in creating a procedure that will be used to
initiate synthesis runs over a range of constraint variations. This type of script
would typically run overnight since they are inherently long. Once the multi-
pass synthesis is complete, the script will display the results using a graph. The
following diagram illustrates the script’s architecture:
TCL Scripting Lab Exercises - 17 - © Abdelazeem
2024 Revision
TCL/1.0
compile
synResult
newRun
config Leonardo’s
variables
vhdlFileList
report_delay
read
load_library
pre_optimize
report_area
optimize_timing
delay.txt area.txt
result.txt
maxFreq
args
Procedure call :
Data transfer :
API Procedure :
API
optimize
TCL Scripting Lab Exercises - 18 - © Abdelazeem
2024 Revision
TCL/1.0
The ‘compile’ procedure is the top-level procedure. This procedure reads all the
files located inside the current directory and initiate successive synthesis runs
on each of those files. When calling the procedure, the user has to specify a
required frequency value in MHz. Optionally, if the VHDL files require
packages to be analyzed prior to synthesis, the user will specify the required
files as part of the procedure’s arguments.
The procedure ‘newRun’ is invoked by the procedure ‘compile’ whenever there is
a new synthesis run to perform. This procedure will configure the synthesis
tool’s variables from the information located inside the ‘config’ variable. Once
the variable have been set-up, the procedure ‘newRun’ will call a number of
Leonardo’s API functions to perform a synthesis. Finally, the procedure will
browse the report files to create a concise summary file ‘result.txt’.
Recommendations
! Leonardo Spectrum’s API:
Leonardo Spectrum features a large amount of TCL API commands
described in detail in the synthesis tool’s documentation. This script will
only feature a few of those to give you a feel for what you can achieve with
scripting.
This is the list of Leonardo Spectrum’s commands used in this lab:
- read : This command is used to analyze an HDL file
o ‘read -format vhdl <file name>’ will analyze the
given file and return any errors or warning related to the
semantics of that file.
- load_library : This command loads a pre-compiled technology
library.
o ‘load_library flex10’ will load the Altera Flex 10K
primitive library.
- pre-optimize : This procedure does a number of high level
optimizations, such as: operator sharing, redundant logic
removal, macros extraction.
o ‘pre_optimize –common_logic –unused_logic !
–boudary –xor_comparator_optimize –extract’
will use all the pre optimization options.
- optimize : Optimizes and map a design to a target technology.
o ‘optimize’ will run the optimization process, using the
constraint information located inside the synthesis tool’s
global variables (see Leonardo’s global variables).
- optimize_timing : Performs critical path optimization on the
design.
TCL Scripting Lab Exercises - 19 - © Abdelazeem
2024 Revision
TCL/1.0
o ‘optimize_timing’: Optimize the critical paths using
the timing constraints found in Leonardo’s global
variables (see Leonardo’s global variables).
- report_delay : Writes out a report file containing timing
information.
- report_area : Writes out a report file containing area
information.
! Leonardo Spectrum’s global variables:
Leonardo Spectrum features a large amount of variables used to configure
the synthesis engine. This script will only feature a few of those.
This is the list of Leonardo Spectrum’s global variables used in this lab:
- output_file : This variable indicates the name of the resulting
netlist.
o ‘set output_file decode.edf’ will assign the name
‘decode.edf’ to the resulting netlist.
- part : This variable indicates the part name in the chosen target
family.
o ‘set part EPF10K30RC208’ will set the part to the
specified value.
- process : This indicates the grade of the device.
o ‘set process 3’ will set the process to 3
- register2register : This variable indicates the delay
requirement (ns) between registers inside your design.
o ‘set register2register 25’ will force Leonardo
Spectrum to try to meet a 25 ns delay between any
register in the design.
- input2register : This variable indicates the delay requirement
(ns) between any input and register inside your design.
o ‘set input2register 25’ will force Leonardo
Spectrum to try to meet a 25 ns delay between any input
and register in the design.
- output2register : This variable indicates the delay requirement
(ns) between any output and register inside your design.
o ‘set output2register 25’ will force Leonardo
Spectrum to try to meet a 25 ns delay between any output
and register in the design.
- resource_sharing : This indicate if the synthesis tool tries to
resource share operators or not.
o ‘set resource_sharing TRUE’ will force Leonardo
Spectrum to try to implement resource sharing.
TCL Scripting Lab Exercises - 20 - © Abdelazeem
2024 Revision
TCL/1.0
- encoding : This variable is used to set the encoding style of state
machines.
o ‘set encoding Binary’ will force Leonardo Spectrum
to use the binary style for the state machines contained
inside the current design.
If you require more information about specific variables, you can type the
command ‘help –v’ inside the Leonardo Spectrum’s console window.
! Data types:
- config : (array) Constraint names are used as indexes.
- vhdlFileList : (list of stings) List of all the vhdl files contained
inside the current directory.
Action
Looking at the script design
❏ Files Location: the lab files will are stored in the following directories:
Workstation Users:
<install_path>/tclscript/labs/leonardotcl
PC Users:
<install_path>tclscriptlabsleonardotcl
Your trainer will tell you the location of the lab files installation
<install_path>
100
100
(register2register)
(input2register)
config()
100
TRUE
Binary
(output2register)
(resource_sharing)
(encoding)
nano seconds
TCL Scripting Lab Exercises - 21 - © Abdelazeem
2024 Revision
TCL/1.0
❏ We will work on the file complile.tcl. Take a look at the file's contents
using a text editor. Check with your instructor to see which text editors
are available, or use your favorite editor.
Completing the procedures
❏ Complete the procedures using the comments found inside the script file.
❏ Test the resulting script on the vhdl files found in the lab directory. This
can be achieved by typing the following commands in Leonardo Spectrum.
cd <install_path>/tclscript/labs/leonardotcl
source compile.tcl
compile 40 mask_types.vhd
TCL Scripting Lab Exercises - 22 - © Abdelazeem
2024 Revision
TCL/1.0
Lab 4 – Synplify Multi-pass Synthesis
Goals
The goal of this exercise is to become familiar with some of the features of
Synplify’s API. This example is based on a VHDL synthesis; this script will be
used to perform a multi-pass synthesis and report the results of its analysis.
No prior knowledge of the VHDL language is required for this lab.
Scenario
Synthesis is often viewed as a simple push-button process. In most cases this
approach is sufficient to achieve the required results. However when dealing
with designs with tight constrains such as area or timing, synthesis become a
more involved process. Commonly designers find themselves engaged in
countless synthesis runs involving different sets of synthesis constraints.
Unfortunately, due to the increasing level of complexity of synthesis
algorithms, synthesis constraints combinations that used to lead to specific
improvements are no longer valid.
The proposed lab example consists in creating a procedure that will be used to
initiate synthesis runs over a range of constraint variations. This type of script
would typically run overnight since they are inherently long. Once the multi-
pass synthesis is complete, the script will display the results using a graph. The
following diagram illustrates the script’s architecture:
TCL Scripting Lab Exercises - 23 - © Abdelazeem
2024 Revision
TCL/1.0
compile
newRun
vhdlFileList
add_file
set_option
result.txt
<name>.srr
maxFreq
args
Procedure call :
Data transfer :
API Procedure :
API
project
config
TCL Scripting Lab Exercises - 24 - © Abdelazeem
2024 Revision
TCL/1.0
The ‘compile’ procedure is the top-level procedure. This procedure reads all the
files located inside the current directory and initiate successive synthesis runs
on each of those files. When calling the procedure, the user has to specify a
required frequency value in MHz. Optionally, if the VHDL files require
packages to be analyzed prior to synthesis, the user will specify the required
files as part of the procedure’s arguments.
The procedure ‘newRun’ is invoked by the procedure ‘compile’ whenever there is
a new synthesis run to perform. This procedure will configure the synthesis
tool’s variables from the information located inside the ‘config’ variable. Once
the variable has been set-up, the procedure ‘newRun’ will call a Synplify API
functions to perform a synthesis. Finally, the procedure will browse the report
files to create a concise summary file ‘result.txt’.
Recommendations
! Synplify’s API:
Synplify features a large amount of TCL API commands described in
detail in the synthesis tool’s documentation. This script will only feature a
few of those to give you a feel for what you can achieve with scripting.
This is the list of Synplify ’s commands used in this lab:
- project : This command is used by Synplify for a number of
applications. In this script, ‘project’ is used to set-up a new
project, specify a log file and run the synthesis engine.
o ‘project -new’ will initialize the synthesis tool and
prepare a new project.
o ‘project –log_file <name>.srr’ will specify the
name of the log file to be generated after synthesis.
o ‘project –run synthesis’ will initiate a synthesis run.
- add_file : This command is used to analyze an HDL file.
o ‘add_file –vhdl decode.vhd’ will compile the
decode.vhd file.
- set_option : This procedure is used to set the design constraints
as well as synthesis options.
o ‘set_option –technology FLEX10K’ will select the
Altera FLEX technology.
o ‘set_option –part EFP10K30’ will specify the part to
be used within the Altera FLEX family
o ‘set_option frequency 40’ will specify the required
frequency for the current design (in MHz).
o ‘set_option resource_sharing 1’will indicate to the
synthesis engine to try to resource share logic.
o ‘set_option symbolic_fsm_compiler 1’ will to the
synthesis engine to use dedicated algorithms for state
machine optimization.
TCL Scripting Lab Exercises - 25 - © Abdelazeem
2024 Revision
TCL/1.0
o ‘set_option default_enum_encoding sequential’
will indicate Synplify to use a sequential (binary) encoding
style for the state machines inside the current design.
Alternatively, the user can specify ‘onehot’ for a one-hot
coding style.
! Data types:
- config : (array) Constraint names are used as indexes.
- vhdlFileList : (list of stings) List of all the vhdl files contained
inside the current directory.
Action
Looking at the script design
❏ Files Location: the lab files will are stored in the following directories:
Workstation Users:
<install_path>/tclscript/labs/Synplifytcl
PC Users:
<install_path>tclscriptlabsSynplifytcl
Your trainer will tell you the location of the lab files installation
<install_path>
❏ We will work on the file complile.tcl. Take a look at the file's contents
using a text editor. Check with your instructor to see which text editors
are available, or use your favorite editor.
sequential
0
(default_enum_encoding)
(symbolic_fsm_compiler)
config()
0
0
(resource_sharing)
(frequency)
TCL Scripting Lab Exercises - 26 - © 2024
Abdelazeem
Revision TCL/1.0
Completing the procedures
❏ Complete the procedures using the comments found inside the script file.
❏ Test the resulting script on the vhdl files found in the lab directory. This
can be achieved by performing the following steps.
Click on: run > run script
Select: compile.tcl

More Related Content

PDF
[Back2School] STA Methodology- Chapter 7pdf
PDF
[Back2School] Crosstalk and Noise- Chapter 6.pdf
PDF
[Back2School] Timing Checks- Chapter 5.pdf
PDF
[Back2School] Timing Verification- Chapter 4
PDF
[Back2School] Constraint Develop.pdf- Chapter 3
PDF
[Back2School] Delay Calculation- Chapter 2
PDF
[Back2School] STA Basic Concepts- Chapter 1.pdf
PDF
Digital Design Flow.pdf
[Back2School] STA Methodology- Chapter 7pdf
[Back2School] Crosstalk and Noise- Chapter 6.pdf
[Back2School] Timing Checks- Chapter 5.pdf
[Back2School] Timing Verification- Chapter 4
[Back2School] Constraint Develop.pdf- Chapter 3
[Back2School] Delay Calculation- Chapter 2
[Back2School] STA Basic Concepts- Chapter 1.pdf
Digital Design Flow.pdf

More from Ahmed Abdelazeem (12)

PDF
Electromigration and IR Voltage Drop- EMIR.pdf
PDF
1. Introduction to PnR.pdf
PDF
IO Pad Insertion.pdf
PDF
EMIR: May Your Chips Live Forever.pdf
PDF
Physical Verification.pdf
PDF
Routing.pdf
PDF
Clock Tree Synthesis.pdf
PDF
Placement
PDF
PowerPlanning.pdf
PDF
Floorplanning
PDF
Static Time Analysis
PDF
ASIC Design Flow
Electromigration and IR Voltage Drop- EMIR.pdf
1. Introduction to PnR.pdf
IO Pad Insertion.pdf
EMIR: May Your Chips Live Forever.pdf
Physical Verification.pdf
Routing.pdf
Clock Tree Synthesis.pdf
Placement
PowerPlanning.pdf
Floorplanning
Static Time Analysis
ASIC Design Flow
Ad

Recently uploaded (20)

PPT
chapter_1_a.ppthduushshwhwbshshshsbbsbsbsbsh
PPTX
Embeded System for Artificial intelligence 2.pptx
PPT
Lines and angles cbse class 9 math chemistry
PDF
How NGOs Save Costs with Affordable IT Rentals
PPTX
making presentation that do no stick.pptx
PPTX
quadraticequations-111211090004-phpapp02.pptx
PPTX
ERP good ERP good ERP good ERP good good ERP good ERP good
PPTX
Operating System Processes_Scheduler OSS
PPTX
了解新西兰毕业证(Wintec毕业证书)怀卡托理工学院毕业证存档可查的
PDF
Dynamic Checkweighers and Automatic Weighing Machine Solutions
PPTX
DEATH AUDIT MAY 2025.pptxurjrjejektjtjyjjy
PPTX
code of ethics.pptxdvhwbssssSAssscasascc
PPTX
Computers and mobile device: Evaluating options for home and work
DOCX
A PROPOSAL ON IoT climate sensor 2.docx
PDF
PPT Determiners.pdf.......................
PPTX
material for studying about lift elevators escalation
PPT
FABRICATION OF MOS FET BJT DEVICES IN NANOMETER
PPTX
Sem-8 project ppt fortvfvmat uyyjhuj.pptx
DOCX
fsdffdghjjgfxfdghjvhjvgfdfcbchghgghgcbjghf
PPTX
Prograce_Present.....ggation_Simple.pptx
chapter_1_a.ppthduushshwhwbshshshsbbsbsbsbsh
Embeded System for Artificial intelligence 2.pptx
Lines and angles cbse class 9 math chemistry
How NGOs Save Costs with Affordable IT Rentals
making presentation that do no stick.pptx
quadraticequations-111211090004-phpapp02.pptx
ERP good ERP good ERP good ERP good good ERP good ERP good
Operating System Processes_Scheduler OSS
了解新西兰毕业证(Wintec毕业证书)怀卡托理工学院毕业证存档可查的
Dynamic Checkweighers and Automatic Weighing Machine Solutions
DEATH AUDIT MAY 2025.pptxurjrjejektjtjyjjy
code of ethics.pptxdvhwbssssSAssscasascc
Computers and mobile device: Evaluating options for home and work
A PROPOSAL ON IoT climate sensor 2.docx
PPT Determiners.pdf.......................
material for studying about lift elevators escalation
FABRICATION OF MOS FET BJT DEVICES IN NANOMETER
Sem-8 project ppt fortvfvmat uyyjhuj.pptx
fsdffdghjjgfxfdghjvhjvgfdfcbchghgghgcbjghf
Prograce_Present.....ggation_Simple.pptx
Ad

Tcl Scripting for EDA.pdf

  • 1. Tcl Scripting for EDA Ahmed Abdelazeem
  • 2. ii © 2024 Abdelazeem Tcl Scripting for EDA Never forget the story of Palestine
  • 3. ©2024Abdelazeem iii Tcl Scripting for EDA Palestinian trail of Blood.
  • 4. iv © 2024 Abdelazeem Tcl Scripting for EDA To the People of Palestine This work is humbly dedicated to the people of Palestine - to every mother who has buried a child, to every father who has carried the weight of loss, to every child who has learned the meaning of fear before the meaning of play. Your courage in the face of cruelty, your steadfastness in the shadow of siege, and your unyielding grip on hope are a testament to the strength of the human spirit. You are not forgotten. Your pain is carried in the hearts of millions, and your story will echo through history until justice calls your name. May the day come when your skies are free, your lands are whole, and your children know nothing but peace.
  • 5. ©2024Abdelazeem v Tcl Scripting for EDA
  • 6. vi © 2024 Abdelazeem Tcl Scripting for EDA This page intentionally blank
  • 7. ©2024Abdelazeem vii Tcl Scripting for EDA
  • 8. viii © 2024 Abdelazeem Tcl Scripting for EDA
  • 9. ©2024Abdelazeem ix Tcl Scripting for EDA Tcl Scripting for EDA Agenda Day 1 Introduction to Tcl . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 Tcl Basics 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 Tcl Basics 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 Lab 1 - Extracting Bits From Integers Control Flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 Lab 2 - Working with a String Bitstream Day 2 Lists & Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 Lab 3 - Sorting Design Blocks File I/O and Program Access . . . . . . . . . . . . . . . . . . . . . . . . . 7 Regular Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 Lab 4 - Netlist Hacking Tcl in EDA Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 Lab 5 - Working with a Tcl-enabled EDA tool Next Steps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 Appendices A - From Scripts to Applications . . . . . . . . . . . . . . . . . . . . . 11 B - Binary Files and Strings. . . . . . . . . . . . . . . . . . . . . . . . . 12 C - Client-Server Allplications and Networking . . . . . . . . . 13 D - Expect - Interacting with Command-Line Programs . 14 Index Tcl Lab Exercises and Case Studies
  • 10. x © 2024 Abdelazeem Tcl Scripting for EDA
  • 11. 1.1 © 2024 Abdelazeem Tcl Training Tcl Training Tcl Scripting for EDA
  • 12. 1.2 © 2024 Abdelazeem Tcl Training Tcl Scripting for EDA (tse1) 1.2 Workshop Overview • Objectives – Introduce Tcl – Understand Tcl uses and strengths – Learn how to write simple Tcl scripts – Demonstrate how Tcl can be used for EDA scripting • Format – Lectures & labs – Regular breaks (morning, lunch, and afternoon) – Interactive classroom, encouraging interruptions & questions, quizzes – Difficult concepts explained several times – Real-world EDA Tcl scripting examples Welcome to Tcl Scripting Workshop by Abdelazeem!
  • 13. 1.3 Copyright © 2024 Abdelazeem Tcl Training Tcl Scripting for EDA (tse1) 1.3 Workshop Plan DAY TWO List & Arrays LAB 3: Sorting Design Blocks File I/O & Program Access Regular Expressions LAB 4: VHDL Netlist Hacking Tcl in EDA tools LAB 5: Working with a Tcl-enabled EDA tool Next Steps DAY ONE Introduction to Tcl Tcl Basics 1 & 2 LAB 1: Extracting Bits from Integers Control Flow Strings LAB 2: Working with a String Bitstream The Workshop material provides additional Appendices covering various advanced Tcl topics: • From Scripts to Applications How do you present, package and distribute your Tcl scripts to your colleagues and customers? This Appendix covers various Tcl commands useful for building robust and portable Tcl applications. • Binary Files and Strings Summary of Tcl commands and examples for manipulation of binary files and strings. Tcl can read, write and process these similarly to “ordinary” Tcl strings. • Client-Server Applications and Networking Does your application require communication with other programs on the same machine or over the network? Client-server communication applications can be built easily with Tcl as this Appendix demonstrates on a practical example. • Interaction with Command-Line Programs Does your application require to communicate with old interactive command-line programs (network clients, test hardware terminals, etc.)? Tcl Expect extension is an ideal tool for this job. With Expect, any interactive command-line application can be enhanced to provide Tcl scripting capabilities, allowing automation of many repetitive tasks. An introduction to Expect is provided in this Appendix.
  • 14. 1.4 Copyright © 2024 Abdelazeem Tcl Training Tcl Scripting for EDA (tse1) 1.4 Why Tcl? • Productivity • Portability – Ms Windows, UNIX variants, Macintosh, OpenVMS, BeOS, … • Availability – Download, use, modify and re-distribute without royalties • Interfacing between the tools – Can bridge incompatible interfaces, platforms, distant locations • Many available extensions – GUI programming (Tk, Tix, BLT, Togl, ...) – Interaction with command-line applications (expect, …) – Database (OraTcl), object-oriented programming ([incr Tcl]), ... Tcl stands for “Tool Command Language”. Tcl was originally developed to replace ad-hoc scripting languages used by research VLSI tools at UC Berkeley. While it started as an EDA scripting language, Tcl popularity grew fast and today it has been reported to be used in many different applications ranging from hand-held devices to mission-critical systems. Tcl is now a mature and very powerful portable scripting language with many extensions available for various application areas. Commercial support for Tcl has been provided by a variety of companies, including Sun Microsystems, Scriptics and at the present day ActiveState Corporation. Future developments of Tcl are being overseen by an independent body - a Tcl Core Team.
  • 15. 1.5 Copyright © 2024 Abdelazeem Tcl Training Tcl Scripting for EDA (tse1) 1.5 Tcl: Main Features • Rapid application development • Embeddable • Extendible • Flexible integration • Easy to learn Tk Tcl expect My extension . . . Tcl My application Application B (e.g. WinNT) Application A (e.g. Solaris) Tcl Tcl allows for complex applications to be developed quickly. An interactive nature of the Tcl development environment provides immediate feedback on the operation of the developed application. Tcl scripting can be easily embedded into applications written in C or C++. This allows for application’s internal functions to become visible as Tcl commands. Furthermore, build-in Tcl command set provides a powerful facilities for controlling the execution of these new commands, analysis of data, arithmetic functions, data input/output and others. This is the approach used by many EDA vendors today. Tcl was designed to be extendible. New functionality can be added easily by defining new Tcl commands using Tcl or C/C++.. Tcl is an ideal tool for solving application integration problems, involving for example incompatible interfaces, different operating systems, applications running on different machines across the network, etc. Tcl has a simple syntax and few basic language rules, which makes it easy to learn.
  • 16. 1.6 Copyright © 2024 Abdelazeem Tcl Training Tcl Scripting for EDA (tse1) 1.6 Tcl in EDA • Quickly becoming the standard EDA scripting language • Typical uses – simulation, synthesis and test automation scripting – data analysis and visualization – design flow integration – netlist conversion, analysis and hacking – linking incompatible tools running on different platforms – scripting front-ends for command-line based applications – IP core customization scripting – automated test benches, regression testing, HW/SW co-verification – portable system demonstrators/applications – project/EDA system administration (installation, backup, etc.) Only recently, Tcl was adopted by the EDA industrial community as a “standard” scripting language for EDA tool scripting. Availability of a common language eases design tool integration, reduces training costs, but also accelerates EDA tool development as a common standarized Tcl support may be implemented using freely downloadable sources.
  • 17. 1.7 Copyright © 2024 Abdelazeem Tcl Training Tcl Scripting for EDA (tse1) 1.7 Tcl shell (tclsh) • Command-line interface – Interactive incremental testing (try & see) • Available within many modern EDA tools • Executable file names – For example for Tcl 8.3: tclsh8.3, tclsh83.exe – During this course: tclsh $ tclsh % puts "Hello world!" Hello world! % info commands tell socket subst open eof pwd glob list exec pid auto_load_index time unknown eval lrange fblocked lsearch auto_import ... % exit $ $ tclsh % puts "Hello world!" Hello world! % info commands tell socket subst open eof pwd glob list exec pid auto_load_index time unknown eval lrange fblocked lsearch auto_import ... % exit $ Command prompt (UNIX or Ms Windows) Tcl command prompt Standard output (UNIX terminal) Leave tclsh Recognized Tcl commands ! ! Try this: Try this: This course is based on Tcl version 8.0, which is currently the most common version available with EDA tools. You may also come across tools which use Tcl versions 7.6, 8.2 and beyond. There are significant differences between these versions (new commands and new command options) and therefore it is advisable to consult tool documentation for any incompatibilities. tclsh syntax tclsh ?fileName arg arg ...?
  • 18. 1.8 Copyright © 2024 Abdelazeem Tcl Training Tcl Scripting for EDA (tse1) 1.8 $ tclsh % source my_script.tcl Hello world! % !! Hello world! ... % exit $ tclsh % source my_script.tcl Hello world! % !! Hello world! ... % exit $ tclsh my_script.tcl Hello world! $ !! Hello world! ... $ tclsh my_script.tcl Hello world! $ !! Hello world! ... 1. EDIT From a UNIX shell: From a Tcl interpreter: 2. TEST Working with Tcl scripts (UNIX) • Interactive & iterative process Repeat last UNIX command Repeat last Tcl command Writing a Tcl script typically involves an iterative process of editing and testing Tcl script files. This process is identical for all platforms supported by Tcl.
  • 19. 1.9 Copyright © 2024 Abdelazeem Tcl Training Tcl Scripting for EDA (tse1) 1.9 C:> tclsh % source my_script.tcl Hello world! % !! Hello world! ... % exit C:> tclsh % source my_script.tcl Hello world! % !! Hello world! ... % exit C:> tclsh my_script.tcl Hello world! C:> tclsh my_script.tcl Hello world! ... C:> tclsh my_script.tcl Hello world! C:> tclsh my_script.tcl Hello world! ... 1. EDIT From Command/MSDOS Prompt: From a Tcl interpreter: 2. TEST Working with Tcl scripts (Ms Windows) • Interactive & iterative process Press to repeat last command Repeat last Tcl command Or use ↑ ↑ While a command-line Tcl interpreter is a typical interface available to an EDA tool Tcl script writer, there are also other Tcl development tools which provide more advanced features. One example of such a tool is TclPro, which provides Tcl debugging, syntax checking, Tcl application packaging and other features. For more information on TclPro, please visit dev.scriptics.com. Debugger controls Command stack Tcl script display Breakpoints Command return value and error code Variable traces
  • 20. 1.10 Copyright © 2024 Abdelazeem Tcl Training Tcl Scripting for EDA (tse1) 1.10 Tcl Interpreter in EDA Tools • Tcl interpreter is typically embedded in your EDA tool command console (GUI or command line) – Try invoking info commands in your favourite EDA tool! HERE HERE HERE HERE HERE HERE Tcl-enabled EDA tools will be discussed in more detail later in this Workshop.
  • 21. 1.11 Copyright © 2024 Abdelazeem Tcl Training Tcl Scripting for EDA (tse1) 1.11 % info wrong # args: should be "info option ?arg arg ...?" % info xyzzy bad option "xyzzy": should be args, body, cmdcount, commands, complete, default, exists, globals, level, library, locals, patchlevel, procs, script, tclversion, or vars % info commands tell socket subst open eof pwd glob list exec pid auto_load_index time unknown eval lrange fblocked lsearch auto_import ... % man info % info wrong # args: should be "info option ?arg arg ...?" % info xyzzy bad option "xyzzy": should be args, body, cmdcount, commands, complete, default, exists, globals, level, library, locals, patchlevel, procs, script, tclversion, or vars % info commands tell socket subst open eof pwd glob list exec pid auto_load_index time unknown eval lrange fblocked lsearch auto_import ... % man info Help! • Command hints and manual pages UNIX only! Command-line hints provide quick feedback on the command syntax and available options. Manual pages are the best source of information for each Tcl command. They are well written and updated with each release of Tcl distribution. Manual page browsing using man command works only on UNIX platforms (Tcl interpreter actually invokes man command from the native UNIX environment). On UNIX, Tcl manual pages are typically located in section n of the on-line UNIX manual. You may use -S option to select this section in case of command name conflict with another UNIX application, for example man -S n file will retrieve manual page for Tcl file command and not for the UNIX file command. Microsoft Windows users may use Windows help file provided with the Windows Tcl distribution. The help file contains manual pages identical to those in the UNIX distribution. Furthermore, manual pages may be downloaded from http://dev.scriptics.com/ in HTML format for both platforms. EDA vendors distribute proprietary documentation for additional Tcl commands provided by their EDA tools.
  • 22. 1.12 Copyright © 2024 Abdelazeem Tcl Training Tcl Scripting for EDA (tse1) 1.12 Quiz 1 • What categories of EDA tools support Tcl? (a) high-level synthesis (b) HDL simulation (c) automatic placement & routing (d) prototyping & testing tools (e) all of the above Answer
  • 23. 2.1 Copyright © 2024 Abdelazeem Tcl Training Tcl Scripting for EDA Tcl Basics 1
  • 24. 2.2 Copyright © 2024 Abdelazeem Tcl Training Tcl Basics 1 (tb11) 2.2 Aims and Topics • Aim – To familiarize with Tcl syntax and operation of a Tcl interpreter • Topics – Tcl syntax – Variables – Substitution – Command evaluation
  • 25. 2.3 Copyright © 2024 Abdelazeem Tcl Training Tcl Basics 1 (tb11) 2.3 Tcl Commands • Tcl is CASE SENSITIVE • Tcl script is composed of “commands” • Tcl command is composed of “words” Tcl commands Tcl script info commands Enter ↵ info commands spaces or tabs separate command words newline terminates the command Command name 1st argument 2nd argument 3rd argument ... Tcl interpreter first breaks the command into words
  • 26. 2.4 Copyright © 2024 Abdelazeem Tcl Training Tcl Basics 1 (tb11) 2.4 Tcl Script Processing Summary Word Grouping Substitution Command Evaluation Command Separation Each line of a Tcl script is processed in four steps indicated above. If you want to be able to write effective Tcl scripts you need to understand how this process works. The previous slide outlined command separation. In the following we will look at the steps which follow next.
  • 27. 2.5 Copyright © 2024 Abdelazeem Tcl Training puts "Hello { world! }} " puts "Hello " world! "" " puts "Hello " world! " " puts "Hello "world!" " puts {Hello { world! }} } puts {Hello " world! "" } puts {Hello }world!{ } puts "Hello { world! }} " puts "Hello " world! "" " puts "Hello " world! " " puts "Hello "world!" " puts {Hello { world! }} } puts {Hello " world! "" } puts {Hello }world!{ } Tcl Basics 1 (tb11) 2.5 • Use "" or {} to group words together • ""/{} inside {} and {} inside "" are treated as ordinary characters • "" inside "" are pair-matched Word Grouping With "" and {} puts "Hello world!" puts Hello world! puts {Hello world!} puts Hello world! spaces, tabs and newlines are preserved within "" or {} quote characters are discarded brace characters are discarded Note that there are other differences between grouping with "" and {} (more later!). Word grouping examples: puts Hello { world! }} puts Hello " world! " SyntaxError! puts Hello { world! }} puts Hello " world! "" SyntaxError! escape " with a backslash having a space or a tab might be important! SyntaxError!
  • 28. 2.6 Copyright © 2024 Abdelazeem Tcl Training Tcl Basics 1 (tb11) 2.6 # This is a comment cmdName arg arg arg ... cmdName arg arg arg ...; cmdName arg arg arg ... cmdName arg arg arg ...; # This is an inline comment cmdName arg arg arg ... # Even a comment can be split across multiple lines! # This is a comment cmdName arg arg arg ... cmdName arg arg arg ...; cmdName arg arg arg ... cmdName arg arg arg ...; # This is an inline comment cmdName arg arg arg ... # Even a comment can be split across multiple lines! Tcl Syntax Summary • Other elements of Tcl syntax – Comments start with # – In-line commands are separated with ; – All characters with special meaning can be escaped with both newline and semicolon (;) terminate the command command must be terminated before an in-line comment Enter ↵ escape a newline to continue on subsequent lines
  • 29. 2.7 Copyright © 2024 Abdelazeem Tcl Training Tcl Basics 1 (tb11) 2.7 Variables • No need to declare variables – Use set to create a variable and assign/retrieve its value – Use unset to delete one or more variables • Tcl is typeless—variables store STRING values % set a "Hello world!" Hello world! % set a Hello world! % set b can’t read "b": no such variable % set b 123 123 % unset a b % % set a "Hello world!" Hello world! % set a Hello world! % set b can’t read "b": no such variable % set b 123 123 % unset a b % assigns Hello world! to variable a and returns this new value with no value, set returns the value of the named variable deletes variables a and b from the Tcl interpreter (deleting variable which wasn’t previously defined is an error) reading variable which wasn’t previously defined is an error value 123 is a string containing characters 1, 2 and 3 set and unset syntax set varName ?value? unset varName ?varName varName ...?
  • 30. 2.8 Copyright © 2024 Abdelazeem Tcl Training Tcl Basics 1 (tb11) 2.8 Variable Names and Values • Variable names – Are CASE SENSITIVE – May be composed of ANY characters • Strings can also represent numeric values: – Integers: 123 (decimal), 0x7b or 0x7B (hexadecimal), 0173 (octal) – Real numbers: 3.14159, 1.23e+2 or 1.23E2, 123.0 – Boolean: 0 (false), 1 (true) % set a 123; set A 456 456 % set a 123 % set !£%^&* "bad idea!" bad idea! % set !£%^&* bad idea! % set a 123; set A 456 456 % set a 123 % set !£%^&* "bad idea!" bad idea! % set !£%^&* bad idea! % set reg 0173 0173 % set reg 0x7b 0x7b % set pi 3.14159 3.14159 % set match_found 1 1 % set reg 0173 0173 % set reg 0x7b 0x7b % set pi 3.14159 3.14159 % set match_found 1 1 a and A are different variables in Tcl this is a valid variable name! integer (octal) integer (hex) real number Boolean Use only letters, digits and underscores in variable names to maintain readability!
  • 31. 2.9 Copyright © 2024 Abdelazeem Tcl Training Tcl Basics 1 (tb11) 2.9 Substitution and Command Evaluation • After separating commands and word grouping, Tcl command is processed in further two stages: Word Grouping Substitution Command Evaluation Command Separation remember me? variable command backslash
  • 32. 2.10 Copyright © 2024 Abdelazeem Tcl Training Tcl Basics 1 (tb11) 2.10 Substitution • All command words are searched for special constructs which trigger substitution – Words are examined from left to right, character by character • Each character is processed exactly ONCE start $
  • 33. 2.11 Copyright © 2024 Abdelazeem Tcl Training Tcl Basics 1 (tb11) 2.11 Variable Substitution ($) • Each occurrence of $varName is replaced with the corresponding variable value – Except where $ is escaped ($) % set d 10; set p 2 2 % puts "Time = $d ns" Time = 10 ns % set d 10; set p 2 2 % puts "Time = $d ns" Time = 10 ns puts Time = 10 ns puts Time = $d ns $d is replaced by its value (10) NOTE: word boundaries remain unchanged!
  • 34. 2.12 Copyright © 2024 Abdelazeem Tcl Training Tcl Basics 1 (tb11) 2.12 More on Variable Substitution • Use ${varName} to indicate variable name when – No space is required after the variable’s value – Name contains characters other than letters, digits or underscores • $ followed by a character which is not a letter, digit or underscore is treated as an ordinary character ⇒Constructs such as $$a are allowed % puts "Time = $dns" can’t read ”dns": no such variable % puts "Time = ${d}ns or $p%" Time = 10ns or 2% % puts "This is $!£%^&*" This is $!£%^&* % puts "This is a ${!£%^&*}" This is a bad idea! % puts "The price is $$d." The price is $10. % puts "Time = $dns" can’t read ”dns": no such variable % puts "Time = ${d}ns or $p%" Time = 10ns or 2% % puts "This is $!£%^&*" This is $!£%^&* % puts "This is a ${!£%^&*}" This is a bad idea! % puts "The price is $$d." The price is $10. use ${} to indicate the variable name $ is treated as an ordinary character (doesn’t need to be escaped) no space after variable’s value ($p% doesn’t need ${}!)
  • 35. 2.13 Copyright © 2024 Abdelazeem Tcl Training Tcl Basics 1 (tb11) 2.13 Backslash Substitution () • Replaces <character> with its substitution equivalent – Except where is escaped () % puts "Flagt"rst" on" Flag "rst" on % puts "Flagt"rst" on" Flag "rst" on puts puts Flagt"rst" on Flag "rst" on tab quotes quotes NOTE: word boundaries remain unchanged!
  • 36. 2.14 Copyright © 2024 Abdelazeem Tcl Training Tcl Basics 1 (tb11) 2.14 More on Backslash Substitution • Backslash substitution can be used to insert – Special terminal characters • n (newline), t (tab), b (backspace), a (audible alert), ... – Any character using its binary value • x4f or x4F (hexadecimal value), 117 (octal value) – Escape special characters or just replicate other characters • $ (dollar), (backslash), " (quotes), } (brace), (space) • i (character i), ... % puts "Synthesis done. aaa" Synthesis done. % puts "ABC = x41102x43" ABC = ABC % puts "Some specials: $"" Some specials: $" % puts "Synthesis done. aaa" Synthesis done. % puts "ABC = x41102x43" ABC = ABC % puts "Some specials: $"" Some specials: $" beeps 3 times inserting binary values into a Tcl string escaping special characters $, “ and
  • 37. 2.15 Copyright © 2024 Abdelazeem Tcl Training Tcl Basics 1 (tb11) 2.15 Everyone’s Favourite: The Newline • Inserting newlines • Avoiding newlines – If you don’t want the space, use b % puts "Line 1nLine 2" Line 1 Line 2 % % puts "Line 1nLine 2" Line 1 Line 2 % % puts "Line 1 Line 2" Line 1 Line 2 % % puts "Line 1 Line 2" Line 1 Line 2 % % puts "Line 1 Line 2" Line 1 Line 2 % % puts "Line 1 Line 2" Line 1 Line 2 % escaped newline + zero or more spaces or tabs are replaced with a space! newlines within "" or {} are reserved insert a newline with n % puts "No bSpace" NoSpace % % puts "No bSpace" NoSpace % 2nd newline inserted by puts delete the substituted space with a backspace Newlines are very useful for improving readability of user messages, simulation data, serial bitstream, formatting raw data strings, etc. The above examples demonstrate some of the typical uses of newlines in Tcl scripts.
  • 38. 2.16 Copyright © 2024 Abdelazeem Tcl Training Tcl Basics 1 (tb11) 2.16 Command Substitution ([]) • Each occurrence of [<commands>] is replaced with the value returned from the last command executed in <commands> – Except where [] are escaped ([ and ]) % set d 10 10 % puts "Time = [set d]ns" Time = 10ns % set d 10 10 % puts "Time = [set d]ns" Time = 10ns puts puts Time = [set d]ns Time = 10ns NOTE: word boundaries remain unchanged! Word Grouping Substitution Command Evaluation Command Separation 10 set d
  • 39. 2.17 Copyright © 2024 Abdelazeem Tcl Training Tcl Basics 1 (tb11) 2.17 Nested Command Substitution • Command substitution can be nested – Each occurrence of [] will trigger a new command substitution % set a "eggs" eggs % puts "Two nested [set b [set a]]" Two nested eggs % set a "eggs" eggs % puts "Two nested [set b [set a]]" Two nested eggs puts "Two nested [set b [set a]]" puts Two nested eggs eggs set a eggs set b eggs set b [set a] ! "
  • 40. 2.18 Copyright © 2024 Abdelazeem Tcl Training Tcl Basics 1 (tb11) 2.18 Word Grouping with [] • [] can be used for word grouping too! – Do not escape word separators and grouping quotes within [] % puts [set b "No [set a "escapes here"]"] No escapes here % puts [set b "No [set a "escapes here"]"] No escapes here puts [set b "No [set a "escapes here"]"] puts No escapes here escapes here set a "escapes here" No escapes here set b "No escapes here" [] group the argument to puts ! "
  • 41. 2.19 Copyright © 2024 Abdelazeem Tcl Training Tcl Basics 1 (tb11) 2.19 Command Evaluation Word Grouping Substitution Command Evaluation Command Separation variable command backslash ?
  • 42. 2.20 Copyright © 2024 Abdelazeem Tcl Training Tcl Basics 1 (tb11) 2.20 Command Evaluation • Tcl interpreter searches for a matching Tcl command (command name is the 1st word) and then passes all arguments to it • Next the command will execute – Can interpret arguments in any way (strings, numbers, etc.) • When done, the command will return a result back to the interpreter • Commands – Built-in – User-defined puts No escapes here No escapes here puts set
  • 43. 2.21 Copyright © 2024 Abdelazeem Tcl Training Tcl Basics 1 (tb11) 2.21 Quiz 2 • What is the value stored in b? (a) {10}{ (b) 10{ #14 (c) {10}{ #[set c 14] (d) $a{ #14 (e) {10}{ #14 (f) {$a}{ #[set c 14] (g) {$a}{ #14 (h) This will generate a syntax error! set a 10 set b "{$a}{ #[set c 14]" puts "$b" set a 10 set b "{$a}{ #[set c 14]" puts "$b" space file: examples/quiz2.tcl Answer set a 10 set b "{$a}{ #[set c 14]" Part A: [set c 14] => 14 Part B: {# => { # Part C: {$a} => {10} puts "$b" sol: {10}{ #14
  • 44. 2.22 Copyright © 2024 Abdelazeem Tcl Training Palestine will live
  • 45. 3.1 Copyright © 2024 Abdelazeem Tcl Training Tcl Scripting for EDA Tcl Basics 2
  • 46. 3.2 Copyright © 2024 Abdelazeem Tcl Training Tcl Basics 2 (tb21) 3.2 Aims and Topics • Aim – To learn about using Tcl for arithmetic calculations, basics of file manipulation and structured scripting • Topics – Mathematical operations – Basic file manipulation – Basic procedures
  • 47. 3.3 Copyright © 2024 Abdelazeem Tcl Training Tcl Basics 2 (tb21) 3.3 Mathematical Operations • Tcl supports all usual operators and functions • Mathematical – Arithmetic – Relational – Logical – Bit-wise – Various functions • But also – String pattern matching – List, array, string manipulation – File I/O, inter-process, network – ... (more later)
  • 48. 3.4 Copyright © 2024 Abdelazeem Tcl Training Tcl Basics 2 (tb21) 3.4 Tcl as a Calculator • Use expr command to evaluate mathematical expressions • Use real number strings to invoke real number operators % expr 1 + 1 2 % set a 10; set b 20 20 % expr $a - $b -10 % expr {$a - $b} -10 % expr 1 + 1 2 % set a 10; set b 20 20 % expr $a - $b -10 % expr {$a - $b} -10 % expr 9 / 2 4 % expr 9 / 2.0 4.5 % expr 9 / 2 4 % expr 9 / 2.0 4.5 substitution performed only by the expr command! $a - $b expr integer division real number division Enclose the expression in braces for efficiency If a variable may contain integers AND real numbers, consider adding + 0.0 in the expression, e.g. set a [expr {$a + 0.0}] substitution performed first by the Tcl interpreter and then by the expr command 10 expr - 20 expr syntax The improved speed of calculation when the expression is enclosed in braces can be observed even on a simple example above. expr {$a -$b} executes 7 times faster than expr $a - $b Try: source examples/expr_speed.tcl expr arg ?arg arg ...? Execution time Relative execution time expr $a - $b 7µs 7 expr {$a -$b} 1µs 1 Tcl 8.0.5 on Pentium III/1GHz PC, 256MB RAM, Windows 2000
  • 49. 3.5 Copyright © 2024 Abdelazeem Tcl Training Tcl Basics 2 (tb21) 3.5 Available Operators highest precedence lowest precedence -a, !a, ~a a*b, a/b, a%b a+b, a-b a<<b, a>>b a<b, a>b, a<=b, a>=b a==b, a!=b a&b a^b a|b a&&b a||b a?b:c • Arithmetic operators accept integers and reals • Relational operators accept integers, reals and strings • Logical operators accept integers and reals – non-zero = true – zero = false • Bit-wise operators accept integers only • Evaluated from left to right in the order from highest to lowest precedence Operator Description Operands -a !a ~a negative of a logical NOT: 1 if a is zero, 0 otherwise bit-wise complement of a integer, real integer, real integer a*b, a/b a%b multiply a and b, divide a by b remainder after integer division of a by b integer, real integer a+b, a-b add a and b, subtract b from a integer, real a<<b, a>>b left-shift a by b bits, right-shift a by b bits integer a<b, a>b, a<=b, a>=b 1 if the comparison is true: a less than b, a greater than b, a less than or equal to b, a greater than or equal to b integer, real, string a==b, a!=b 1 if the comparison is true: a is equal to b, a is not equal to b integer, real, string a&b bit-wise AND of a and b integer a^b bit-wise exclusive OR of a and b integer a|b bit-wise OR of a and b integer a&&b logical AND: 1 if both a and b are non- zero, 0 otherwise integer, real a||b logical OR: 1 if either a or b is non-zero, 0 otherwise integer, real a?b:c if a is non-zero then evaluates to b, otherwise evaluates to c integer, real (for a)
  • 50. 3.6 Copyright © 2024 Abdelazeem Tcl Training Tcl Basics 2 (tb21) 3.6 Examples: Tcl Operators % set a 2 2 % expr $a > 0 && $a <= 3 1 % expr !(($a == 1) || ($a == 2)) 0 % expr $a || 0 1 % set a 2 2 % expr $a > 0 && $a <= 3 1 % expr !(($a == 1) || ($a == 2)) 0 % expr $a || 0 1 OK because > and <= have higher precedence than && Always use parentheses () to ensure readability. 1 = true 0 = false non-zero evaluates to true 1st 2nd 3rd % set a 0x07 0x07 % expr $a & 0x04 4 % set a [expr $a | 0x08] 15 % set a_neg [expr ~$a + 1] -15 % set a 0x07 0x07 % expr $a & 0x04 4 % set a [expr $a | 0x08] 15 % set a_neg [expr ~$a + 1] -15 read bit 2 bits 7 6 5 4 3 2 1 0 0000 0111 (7) AND 0000 0100 (4) 0000 0100 (4) 0000 0111 (7) OR 0000 1000 (8) 0000 1111 (15) INV 0000 1111 (15) 1111 0000 (-16) 1111 0001 (-15) + 0000 0001 (1) set bit 3 to 1 change the sign (2's complement) NB: equivalent to set a_neg -$a % expr "Tcl" == "Tcl" syntax error in expression "Tcl == Tcl" % expr {"Tcl" == "Tcl"} 1 % expr {$a > 2.3 ? "over" : "under"} under % expr {"TCL" < "Tcl"} 1 % expr {"0x0" == "000"} 1 % expr "Tcl" == "Tcl" syntax error in expression "Tcl == Tcl" % expr {"Tcl" == "Tcl"} 1 % expr {$a > 2.3 ? "over" : "under"} under % expr {"TCL" < "Tcl"} 1 % expr {"0x0" == "000"} 1 When using strings in expressions: • enclose strings within "" or {} • enclose the entire expression in {} ! Avoid using ==, !=, >, <, >=, <= for string comparison if the strings could resemble numerical values! lexicographical comparison (Tcl is AFTER TCL, i.e. it has GREATER index) % expr $a << 2 60 % expr $a >> 1 7 % expr $a_neg >> 1 -8 % expr $a << 2 60 % expr $a >> 1 7 % expr $a_neg >> 1 -8 shift LEFT by 2 bits 0011 1100 (60) 0001 1110 0 0000 1111 0 shift RIGHT by 1 bit 0000 0111 (7) 0000 1111 right shift always propagates the sign bit! 1111 1000 (-8) 1111 0001 left shift always inserts 0
  • 51. 3.7 Copyright © 2024 Abdelazeem Tcl Training Tcl Basics 2 (tb21) 3.7 Mathematical Functions • These functions can be used INSIDE math expressions exp(x) log(x) log10(x) pow(x,y) sqrt(x) fmod(x,y) hypot(x,y) acos(x) asin(x) atan(x) atan2(x,y) cos(x) cosh(x) sin(x) sinh(x) tan(x) tanh(x) abs(x) ceil(x) floor(x) round(x) int(x) double(x) srand(x) rand() expr Although Tcl was not built as a language for mathematical computations, it provides a number of useful mathematical functions. All these functions have to be used inside expressions formed using the expr command (consult expr manual page for more details on supported functions). Examples: % expr sin(3.1415927 / 2.0) 1.0 % expr pow(2, 16) 65536.0 % expr int(pow(2, 16)) 65536 % expr ceil(sqrt(2)) 2.0 % expr floor(sqrt(2)) 1.0 % expr fmod(4.57, 2.0) 0.57 % expr int(rand()*10) 6 % expr sin(3.1415927 / 2.0) 1.0 % expr pow(2, 16) 65536.0 % expr int(pow(2, 16)) 65536 % expr ceil(sqrt(2)) 2.0 % expr floor(sqrt(2)) 1.0 % expr fmod(4.57, 2.0) 0.57 % expr int(rand()*10) 6 π trigonometric functions expect arguments in RADIANS returns real number even when the arguments are integers... ...but this can be easily converted back to integer, if needed returns nearest integer GREATER than √2 returns nearest integer LESS than √2 returns a FLOATING-POINT reminder after the division of 4.57 by 2.0 returns a random integer in the interval 0-9 (inclusive) rand() returns a random real number in the interval 0 (inclusive) to 1 (exclusive)
  • 52. 3.8 Copyright © 2024 Abdelazeem Tcl Training Tcl Basics 2 (tb21) 3.8 Incrementing and Decrementing • Can be done using expr command... • ...but Tcl also provides an efficient replacement: incr % set a 10 10 % set a [expr $a + 1] 11 % set a [expr $a - 5] 6 % set a 10 10 % set a [expr $a + 1] 11 % set a [expr $a - 5] 6 % set a 10 10 % incr a 11 % incr a -5 6 % set a 10 10 % incr a 11 % incr a -5 6 increment constant is optional (defaults to 1) decrement by using a negative increment constant incr syntax Generating random numbers in Tcl: Random numbers can be used during testing to generate random events or noise signals. Tcl provides a better number random generator than that provided by a typical C math library. Tcl uses a “minimal” generator of Park and Miller with the period of 231 - 2 (around 2.1 x 109 ). If you need to generate more than about 1,000,000,000 reliable random numbers in your scripting application, consider writing your own random number generator. An excellent reference for various random generation and test algorithms is Chapter 7 in the following book: Numerical Recepies in C: The Art of Scientific Computing by W.H.Press et al., Cambridge University Press, 1992, second edition, ISBN 0-521-43108-5 incr varName ?increment?
  • 53. 3.9 Copyright © 2024 Abdelazeem Tcl Training Tcl Basics 2 (tb21) 3.9 • In math calculations, the variable values are converted from strings to numbers and then back to strings – Integers are converted accurately – Real numbers (floating-point) • Default conversion precision is 12 • Set using the tcl_precision variable • Internal number representation is platform dependent – Typically: integer: 32 bits, floating-point: 64 bits % expr 1.0 / 300.0 0.00333333333333 % set tcl_precision 17 17 % expr 1.0 / 300.0 0.0033333333333333335 % expr 1.0 / 300.0 0.00333333333333 % set tcl_precision 17 17 % expr 1.0 / 300.0 0.0033333333333333335 default floating-point precision is 12 (i.e. 12 significant digits) with the precision set to 17, the automatic rounding is DISABLED Set precision to 17 to avoid loss of accuracy during the conversion (assuming IEEE floating-point ALU). Numerical Accuracy Tcl interpreter is written in C, therefore the numerical accuracy depends on the accuracy of underlying C implementation. Tcl integers are implemented as long C data types and real numbers are implemented as double C data types.
  • 54. 3.10 Copyright © 2024 Abdelazeem Tcl Training Tcl Basics 2 (tb21) 3.10 Basic Procedures • Use proc command to create new Tcl commands – New commands look and behave just like built-in commands • Why should I use procedures? – Store frequently used algorithms (code reuse, productivity gain) – Structure your scripts (better readability, easier maintenance) proc name arguments body % proc average {n1 n2 n3 n4} { set sum [expr {($n1+$n2+$n3+$n4)/4.0}] return $sum } % average 1 2 3 4 2.5 % average -10 10 -50 3 -11.75 % proc average {n1 n2 n3 n4} { set sum [expr {($n1+$n2+$n3+$n4)/4.0}] return $sum } % average 1 2 3 4 2.5 % average -10 10 -50 3 -11.75 variables n1, n2, n3, n4 and sum are available only INSIDE the procedure, i.e they are local variables without return the procedure returns the value returned by the last executed command proc average average 1 2 3 4
  • 55. 3.11 Copyright © 2024 Abdelazeem Tcl Basics 2 (tb21) 3.11 Global Variables • Sometimes it is necessary to access variables OUTSIDE the procedure body • global command allows to access variables defined at global scope from inside a procedure body % set appname "My script" My script % proc print_error {msg} { global appname puts "$appname: $msg" } % set appname "My script" My script % proc print_error {msg} { global appname puts "$appname: $msg" } variable appname is available globally - both INSIDE and OUTSIDE the procedure. This is a global variable. Minimize the use of GLOBAL variables to improve script readability and to ease the maintenance. global syntax global varname ?varname ...?
  • 56. 3.12 Copyright © 2024 Abdelazeem Tcl Training Tcl Basics 2 (tb21) 3.12 Basic File Manipulation • Tcl provides portable file system operations – Print working directory (pwd) – Change current directory (cd) – List files and directories matching a pattern (glob) • Directory separator is / (forward slash) on ALL platforms! % pwd % pwd % glob * examples labs solutions % glob examples/*.tcl bitwidth.tcl hello.tcl ... % pwd /home /home /use /use r r s/mil s/mil an an% cd /esperan/tcl % cd /abdelazeem/ tcl % pwd Abdelazeem % glob * examples labs solutions % glob examples/*.tcl bitwidth.tcl hello.tcl ... change to /Abdelazeem/tcl directory (returns no value) list ALL files and directories in the current directory list files and directories with extension .tcl in directory examples Syntax for the commands above glob command and its pattern matching will be covered in more detail in Section 5 - “Strings” pwd cd ?dirName? glob ?switches? pattern ?pattern?
  • 57. 3.13 Copyright © 2024 Abdelazeem Tcl Training Tcl Basics 2 (tb21) 3.13 Tcl Interpreter Summary Word Grouping Substitution Command Evaluation Command Separation variable command backslash cd set puts pwd glob average proc ... incr expr
  • 58. 3.14 Copyright © 2024 Abdelazeem Tcl Training Tcl Basics 2 (tb21) 3.14 Grouping with {} and "" Revisited • Quotes ("") enable substitution – [], $, substitutions performed as usual • Braces ({}) disable substitution – No substitutions are performed – Special substitution characters ([], $, ) are treated as ordinary characters (no special interpretation) – BUT escaping the newline character with is allowed % set a xyz xyz % puts "Substituting as usual: x41, $a, number = [set b 123]" Substituting as usual: A, xyz, number = 123 % puts {Substitution disabled: x41, $a, number = [set b 123]} Substitution disabled: x41, $a, number = [set b 123] % set a xyz xyz % puts "Substituting as usual: x41, $a, number = [set b 123]" Substituting as usual: A, xyz, number = 123 % puts {Substitution disabled: x41, $a, number = [set b 123]} Substitution disabled: x41, $a, number = [set b 123] all substitutions performed as usual substitutions disabled, BUT <newline> substitution is allowed
  • 59. 3.15 Copyright © 2024 Abdelazeem Tcl Training Tcl Basics 2 (tb21) 3.15 When Do I Use "" and when Do I Use {}? • Use "" for – Quoting string values – Immediate processing • Substitutions performed BEFORE the command is executed • Use {} for – Avoiding substitution – Deferred processing • Delay substitutions until “LATER” % set cost {$a*0.1 + $b*0.6 + $c*0.3} $a*0.1 + $b*0.6 + $c*0.3 % set a 100; set b 200; set c 300 300 % expr $cost 220.0 % set cost {$a*0.1 + $b*0.6 + $c*0.3} $a*0.1 + $b*0.6 + $c*0.3 % set a 100; set b 200; set c 300 300 % expr $cost 220.0 store frequently-used expressions, which will be used later evaluate the previously stored expression with the current variable values NOTE: No braces! use braces to avoid substituting the values of $a, $b, $c immediately Note that in the last command, the $cost argument must not be enclosed in braces! This is because two rounds of substitutions are required to be performed on the argument to expr. First the Tcl interpreter substitutes $cost for the expression $a*0.1 + $b*0.6 $c*0.3 and then the expr command substitutes values for $a, $b and $c.
  • 60. 3.16 Copyright © 2024 Abdelazeem Tcl Training Tcl Basics 2 (tb21) 3.16 Quiz 3 • What value will print_q and print_b print? (a) both will print 3 (b) print_q will print 2, print_b will print 3 (c) print_q will print 3, print_b will print 2 (d) both will print 2 % set a 2 2 % proc print_q {a} "puts {Value = $a}" % proc print_b {a} {puts "Value = $a"} % print_q 3 Value = ??? % print_b 3 Value = ??? % set a 2 2 % proc print_q {a} "puts {Value = $a}" % proc print_b {a} {puts "Value = $a"} % print_q 3 Value = ??? % print_b 3 Value = ??? file: examples/quiz3.tcl Answer
  • 61. 3.17 Copyright © 2024 Abdelazeem Tcl Training Tcl Basics 2 (tb21) 3.17 LAB 1: Extracting Bits from Integers • Using a Tcl interpreter in an interactive mode, extract 4 least significant bits from a positive integer number between 0 to 15. • Example: % set a 9 9 % set b0 [ ... ] 1 ... ... ... % set b "$b3$b2$b1$b0" 1001 % set a 9 9 % set b0 [ ... ] 1 ... ... ... % set b "$b3$b2$b1$b0" 1001 0 0 1 1 ... LSB insert your code here % set a 9 9 % set b0 [expr {$a & 1}] 1 % set b1 [expr {($a >> 1) & 1}] 0 % set b2 [expr {($a >> 2) & 1}] 0 % set b3 [expr {($a >> 3) & 1}] 1 % set b "$b3$b2$b1$b0" 1001
  • 62. 3.18 Copyright © 2024 Abdelazeem Tcl Training Tcl Basics 2 (tb21) 3.18 LAB 1: Extracting Bits from Integers (2) • Stage 1 – Use expr Tcl command with the following arithmetic operators $a >> 1 shift content of variable a right by 1 bit $a & 1 apply bit-wise AND on the contents of variable a to extract the least significant bit – Use command substitution []to assign individual bits to four variables, e.g. b0, b1, b2 and b3, and then store the result in b – Do NOT use if or other control flow commands (not covered yet)! • Stage 2 – Store the algorithm as a new Tcl command to_bits (returns the result) – Print b after the result to indicate binary format, e.g. 1010b – Print a warning message if the input value is outside the valid 0-15 range • use the a?b:c operator to test whether input falls within the valid range # Define the to_bits procedure proc to_bits {a} { # Check if the input value is within the valid range 0-15 if {($a < 0) || ($a > 15)} { puts "Warning: Input value $a is outside the valid range of 0-15" return } # Extract individual bits set b0 [expr {$a & 1}] set b1 [expr {($a >> 1) & 1}] set b2 [expr {($a >> 2) & 1}] set b3 [expr {($a >> 3) & 1}] # Concatenate bits to form the binary representation set b "$b3$b2$b1$b0" # Print the result in binary format puts "${b}b" } 1001 1 ------- 1 0100 1 ------ 0
  • 63. 4.1 Copyright © 2024 Abdelazeem Tcl Training Tcl Scripting for EDA Control Flow
  • 64. 4.2 Copyright © 2024 Abdelazeem Tcl Training Control Flow (tcf1) 4.2 Aims and Topics • Aim – To learn how to control command execution in Tcl • Topics – What is control flow? – Conditional commands – Looping commands – Loop control
  • 65. 4.3 Copyright © 2024 Abdelazeem Tcl Training Control Flow (tcf1) 4.3 What is Control Flow? • A collection of Tcl commands which can be used to control when and how many times commands are executed conditionally execute or skip commands repeat commands • Conditional command execution – if – switch • Looping commands – for – foreach – while • Loop control – break – continue
  • 66. 4.4 Copyright © 2024 Abdelazeem Tcl Training Control Flow (tcf1) 4.4 Conditional Execution: if • Execute commands IF the condition is true – Condition is evaluated in the same way as expr expression – Enclose the condition and if command body in {} unless you require substitution if {$area < $area_desired} then { puts "Desired area constraint met." } if {$area < $area_desired} then { puts "Desired area constraint met." } then is optional condition if body Use indentation to improve readability! if condition 1 (true) 0 (false) if body
  • 67. 4.5 Copyright © 2024 Abdelazeem Tcl Training Control Flow (tcf1) 4.5 Conditional Execution: if-else • Execute if body commands IF the condition is true, ELSE execute else body if {$area < $area_desired} then { puts "Desired area constraint met." } else { puts "Area constraint VIOLATED." } if {$area < $area_desired} then { puts "Desired area constraint met." } else { puts "Area constraint VIOLATED." } else is optional else body if condition 1 (true) 0 (false) if body else body
  • 68. 4.6 Copyright © 2024 Abdelazeem Tcl Training Control Flow (tcf1) 4.6 Conditional Execution: if-elseif-else • Test for more than one condition with elseif – Any number of elseif’s can be used if {$area < $area_desired} then { puts "Desired area constraint met." } elseif {$area < $area_max} then { puts "Maximum area constraint met." } else { puts "Area constraints VIOLATED." } if {$area < $area_desired} then { puts "Desired area constraint met." } elseif {$area < $area_max} then { puts "Maximum area constraint met." } else { puts "Area constraints VIOLATED." } then is optional if condition 1 (true) 0 (false) if body elseif condition 1 (true) 0 (false) elseif body else body Complete if syntax if expr1 ?then? body1 elseif expr2 ?then? body2 elseif ... ?else? ?bodyN?
  • 69. 4.7 Copyright © 2024 Abdelazeem Tcl Training Control Flow (tcf1) 4.7 Conditional Execution: switch • Useful for command branching – Similar to if with many elseif’s • default pattern matches all strings switch -- $cellName { AND {incr and_count} OR {incr or_count} INV {incr inv_count} } switch -- $cellName { AND {incr and_count} OR {incr or_count} INV {incr inv_count} } string == pattern 1 1 (true) 0 (false) pattern 1 body string == pattern 2 1 (true) 0 (false) pattern 2 body string == pattern 3 1 (true) 0 (false) pattern 3 body switch -- $cellName { AND {incr and_count} OR {incr or_count} INV {incr inv_count} default {puts "Unrecognized cell."} } switch -- $cellName { AND {incr and_count} OR {incr or_count} INV {incr inv_count} default {puts "Unrecognized cell."} } default body -- is optional (more later) string (stored in cellName’s value) patterns pattern bodies default must be the LAST pattern Always provide default pattern to capture unexpected errors. switch command syntax (variant 1) The above are trivial examples. Pattern bodies may contain more than one command. If default is not the last pattern, it will be matched as an ordinary string "default". switch ?options? string {pattern1 body1 ?pattern2 body2 ...?}
  • 70. 4.8 Copyright © 2024 Abdelazeem Tcl Training Control Flow (tcf1) 4.8 Matching Multiple Patterns with switch • To match several different patterns use ‘-’ separator... • ...or select how patterns should be matched: -exact exactly (default) -glob glob-style matching -regexp regular expressions switch -- $cellName { AND2 - AND3 {incr and_count} OR2 - OR3 {incr or_count} INV {incr inv_count} default {puts "Unrecognized cell."} } switch -- $cellName { AND2 - AND3 {incr and_count} OR2 - OR3 {incr or_count} INV {incr inv_count} default {puts "Unrecognized cell."} } switch -glob -- $cellName { AND* {incr and_count} OR* {incr or_count} INV {incr inv_count} default { puts "Unrecognized cell."} } switch -glob -- $cellName { AND* {incr and_count} OR* {incr or_count} INV {incr inv_count} default { puts "Unrecognized cell."} } incr and_count will be executed when $cellName is AND2 or AND3 Use one line for each pattern to improve readability! Always use -- to prevent switch from confusing strings with options. match patterns using glob-style pattern matching Regular expression pattern matching will be discussed later in Session 8 - Regular Expressions.
  • 71. 4.9 Copyright © 2024 Abdelazeem Tcl Training Control Flow (tcf1) 4.9 Changing Patterns during Run-Time • switch patterns can be changed during run-time! – DO NOT enclose switch command body in {} to ALLOW substitution BEFORE the switch command is executed set hier_path "/DecoderModule/mp3/U*" switch -glob -- $cellName ${hier_path}AND* {incr and_count} ${hier_path}OR* {incr or_count} ${hier_path}INV {incr inv_count} default {puts "Unrecognized cell."} set hier_path "/DecoderModule/mp3/U*" switch -glob -- $cellName ${hier_path}AND* {incr and_count} ${hier_path}OR* {incr or_count} ${hier_path}INV {incr inv_count} default {puts "Unrecognized cell."} patterns defined during run-time using substitution newlines must be escaped switch command syntax (variant 2 - allows substitution) switch matching patterns can be changed during the run-time. For example, the switch statement above allows to define the path for the cells to be searched for by changing the value of the hier_path variable. Patterns searched for in the above command are: • /DecoderModule/mp3/U*AND* • /DecoderModule/mp3/U*OR* • /DecoderModule/mp3/U*INV switch ?options? string pattern1 body1 ?pattern2 body2 ...?
  • 72. 4.10 Copyright © 2024 Abdelazeem Tcl Training Control Flow (tcf1) 4.10 Looping: for • Use for to execute commands specified number of times – LAB 1 revisited • test is evaluated in the same way as expr expression • Enclose start, test, next and body in {} unless you require substitution set a 9; set b "" for {set i 0} {$i < 4} {incr i} { set bit [expr ($a >> $i) & 0x1] set b "$bit$b" } set a 9; set b "" for {set i 0} {$i < 4} {incr i} { set bit [expr ($a >> $i) & 0x1] set b "$bit$b" } evaluate test 1 (true) 0 (false) execute body execute start execute next start test next body for syntax for start test next body
  • 73. 4.11 Copyright © 2024 Abdelazeem Tcl Training Control Flow (tcf1) 4.11 Looping: foreach • Use foreach to execute loop body for each element in a list – Elements are processed from left to right – Number of iterations is equal to the number of elements – using 2 loop variables % foreach cell $lib_cells { puts "Found library cell: $cell" } Found library cell: INV Found library cell: AND Found library cell: OR % % foreach cell $lib_cells { puts "Found library cell: $cell" } Found library cell: INV Found library cell: AND Found library cell: OR % next element available ? 1 (true) 0 (false) assign next elements to the loop variables execute body loop variable name list of elements to iterate through body % set lib_cells "INV AND OR" INV AND OR % set lib_cells "INV AND OR" INV AND OR
  • 74. 4.12 Copyright © 2024 Abdelazeem Tcl Training Control Flow (tcf1) 4.12 Multiple Loop Variables with foreach • Useful for parsing results returned from other commands % foreach {cell quantity} $cell_counts { puts "Found library cell: $cell $quantity times" } Found library cell: INV 55 times Found library cell: AND 10 times Found library cell: OR 20 times % % foreach {cell quantity} $cell_counts { puts "Found library cell: $cell $quantity times" } Found library cell: INV 55 times Found library cell: AND 10 times Found library cell: OR 20 times % two loop variables group loop variables into a single Tcl word % set cell_counts "INV 55 AND 10 OR 20" INV 55 AND 10 OR 20 % set cell_counts "INV 55 AND 10 OR 20" INV 55 AND 10 OR 20 foreach syntax or for multiple loop variables foreach varName list body foreach varList1 list1 ?varList2 list2 ...? body
  • 75. 4.13 Copyright © 2024 Abdelazeem Tcl Training Control Flow (tcf1) 4.13 Looping: while • Use while loop to execute commands in a loop which – Terminates by meeting a certain condition – Never terminates (indefinite loop) set number 20 set bits 1 while {(pow(2, $bits) - 1) < $number} { incr bits } set number 20 set bits 1 while {(pow(2, $bits) - 1) < $number} { incr bits } while {1} { puts "Tcl forever!" } while {1} { puts "Tcl forever!" } evaluate test 1 (true) 0 (false) execute body test body while syntax while test body
  • 76. 4.14 Copyright © 2024 Abdelazeem Tcl Training Control Flow (tcf1) 4.14 Loop Control: break and continue • Use break to terminate the loop – Usually used together with conditional commands • Use continue to advance the loop to the next iteration immediately – Skips the rest of the current iteration while {1} { puts "Tcl is NOT forever..." if {rand() > 0.9} {break} } while {1} { puts "Tcl is NOT forever..." if {rand() > 0.9} {break} } foreach cell $lib_cells { if {$cell == "INV"} {continue} puts "Found cell with 2+ inputs: $cell" } foreach cell $lib_cells { if {$cell == "INV"} {continue} puts "Found cell with 2+ inputs: $cell" } when rand() > 0.9, terminate the loop skip the loop iteration for INV cell (puts is not executed for INV cell) break and continue Tcl commands do not take any arguments.
  • 77. 4.15 Copyright © 2024 Abdelazeem Tcl Training Control Flow (tcf1) 4.15 Control Flow: Syntax Summary if {condition} then { for {start} {test} {next} { body body } } if {condition1} then { foreach varName list { body1 body } elseif {condition2} { } body2 } elseif {condition3} { body3 while {test} { } body } switch string { pattern1 {body1} break pattern2 {body2} pattern3 - continue pattern4 {body4} default {default body} } if {condition} then { for {start} {test} {next} { body body } } if {condition1} then { foreach varName list { body1 body } elseif {condition2} { } body2 } elseif {condition3} { body3 while {test} { } body } switch string { pattern1 {body1} break pattern2 {body2} pattern3 - continue pattern4 {body4} default {default body} } Group conditions, tests and bodies with {} unless you require substitution. match pattern3 OR pattern4 if present, default must be the LAST pattern terminate the loop skip the current iteration
  • 78. 4.16 Copyright © 2024 Abdelazeem Tcl Training Control Flow (tcf1) 4.16 if {$a > 0} {puts "positive"} if {$a > 0} { puts "positive" } if {$a > 0} {puts "positive"} if {$a > 0} { puts "positive" } else { puts "negative" } if {$a > 0} {puts "positive"} if {$a > 0} { puts "positive" } if {$a > 0} {puts "positive"} if {$a > 0} { puts "positive" } else { puts "negative" } Braces & Spaces (Grouping Mistakes) WRONG RIGHT if {$a > 0} puts "positive" if {$a > 0}{ puts "positive" } if $a > 0 {puts "positive"} if {$a > 0} { puts "positive" } else { puts "negative" } if {$a > 0} puts "positive" if {$a > 0}{ puts "positive" } if $a > 0 {puts "positive"} if {$a > 0} { puts "positive" } else { puts "negative" } body NOT grouped! TWO commands! missing space between }{ ! condition NOT grouped! Use braces and you won't need to worry about spaces!
  • 79. 4.17 Copyright © 2024 Abdelazeem Tcl Training Control Flow (tcf1) 4.17 Quiz 4 • What is the value of a ? (a) 150 (b) 100 (c) 140 (d) 300 (e) 200 set a 0 while {$a < 150} { incr a switch $a { 100 {continue} 140 {set a 300} 200 {break} } } puts "Value of a = $a" set a 0 while {$a < 150} { incr a switch $a { 100 {continue} 140 {set a 300} 200 {break} } } puts "Value of a = $a" file: examples/quiz4.tcl Answer 1. Initialization: set a 0: Initializes a to 0. 2. While Loop: while {$a < 150}: The loop continues as long as a is less than 150. incr a: Increments the value of a by 1 in each iteration. 3. Switch Statement: switch $a checks the value of a and performs the following actions: 100 {continue}: If a is 100, it uses the continue command, which skips the rest of the loop iteration and starts the next iteration. 140 {set a 300}: If a is 140, it sets a to 300. This will cause the while loop to terminate because a is no longer less than 150. 200 {break}: If a is 200 (which it won't be in this case because the loop stops when a is set to 300), it would break out of the loop. 4. Output: puts "Value of a = $a": Prints the final value of a.
  • 80. 4.18 Copyright © 2024 Abdelazeem Tcl Training Never...
  • 81. 5.1 Copyright © 2024 Abdelazeem Tcl Training Tcl Scripting for EDA Strings
  • 82. 5.2 Copyright © 2024 Abdelazeem Tcl Training Strings (tst1) 5.2 Aims and Topics • Aim – To learn about how to work with strings in Tcl • Topics – Constructing strings – String operations – Extracting information from strings – Binary strings
  • 83. 5.3 Copyright © 2024 Abdelazeem Tcl Training Strings (tst1) 5.3 What is a String? • Any collection of characters – Letters, digits, special characters, binary characters, etc. • In Tcl, everything is a string – Universal data type from/to which everything can be converted – Easy to manipulate ! d l r o H e l l o w
  • 84. 5.4 Copyright © 2024 Abdelazeem Tcl Training Strings (tst1) 5.4 Constructing Strings • Strings in Tcl can be constructed in a variety of ways – Typing the string characters – Substitution and set – Tcl append command • append command is optimised for speed % set a "Hello"; set b "world"; world % set c "$a $b!" Hello world! % append d $a " " $b "!" Hello world! % set a "Hello"; set b "world"; world % set c "$a $b!" Hello world! % append d $a " " $b "!" Hello world! % set test_files test/test0.tcl ... test/test9999.tcl % foreach f $test_files {append test_script "source $fn"} % set test_script source test/test0.tcl ... source test/test9999.tcl % set test_files test/test0.tcl ... test/test9999.tcl % foreach f $test_files {append test_script "source $fn"} % set test_script source test/test0.tcl ... source test/test9999.tcl variable d will be created if it doesn't exist Use append when constructing long strings! append syntax It might seem that there is no justification for having append, when the same effect can be achieved using substitution. However, the append command is significantly faster when constructing long strings. In the above example, if the body of the foreach loop is replaced with set test_script "${test_script}source $fn" the loop will be 200 times slower! Try: source examples/append_vs_set.tcl append varName ?value value ...? Execution time Relative execution time substitution 7.76s 204 append 38.1ms 1 Tcl 8.0.5 on Pentium III/1GHz PC, 256MB RAM, Windows 2000
  • 85. 5.5 Copyright © 2024 Abdelazeem Tcl Training Strings (tst1) 5.5 • Can be done with ==, but this can fail when string characters resemble numbers • Use string compare instead (robust string comparison) • Return value: 0 strings str1 and str2 are IDENTICAL 1 string str1 is lexicographically AFTER string str2 -1 string str1 is lexicographically BEFORE string str2 % expr {"0x0" == "000"} 1 % expr {"0x0" == "000"} 1 ! % expr {[string compare "0x0" "000"] == 0} 0 % expr {[string compare "0x0" "000"] == 0} 0 Comparing Strings string compare syntax string compare str1 str2
  • 86. 5.6 Copyright © 2024 Abdelazeem Tcl Training Strings (tst1) 5.6 • Similar to comparison, but allows the first string to contain match patterns • Return value: 0 pattern does NOT match string 1 pattern matches string String Matching % string match "*/mp3/*" "/DecoderModule/mp3/U4" 1 % string match "*/mp3/*" "/DecoderModule/mpeg2/U12" 0 % string match "*/mp3/*" "/DecoderModule/mp3/U4" 1 % string match "*/mp3/*" "/DecoderModule/mpeg2/U12" 0 string match pattern string glob-style match pattern
  • 87. 5.7 Copyright © 2024 Abdelazeem Tcl Training Strings (tst1) 5.7 Glob-style Match Patterns • glob-style patterns are similar to UNIX shell wildchar patterns • glob-style patterns use the following special characters ? matches any SINGLE character * matches any sequence of zero or more characters c matches the SINGLE (escaped) character c [abc] matches any SINGLE character in abc [a-b] matches any SINGLE character between a-b (inclusive) {abc,xyz,...} matches any of the strings abc, xyz, etc. • glob also understands UNIX shell tilde substitution ~ login user’s home directory ~user specified user's home directory (UNIX only!) ~user is limited to UNIX platforms only.
  • 88. 5.8 Copyright © 2024 Abdelazeem Tcl Training Strings (tst1) 5.8 Other Useful String Commands % string toupper "Vhdl Edif Tcl" VHDL EDIF TCL % string tolower "DECODER.VHD" decoder.vhd % string trim " Area: 2345 " Area: 2345 % string trim "((a+b)))" ")(" a+b % string trimleft "../mp3/" "/." mp3/ % string trimright "../mp3/" "/" ../mp3 % string toupper "Vhdl Edif Tcl" VHDL EDIF TCL % string tolower "DECODER.VHD" decoder.vhd % string trim " Area: 2345 " Area: 2345 % string trim "((a+b)))" ")(" a+b % string trimleft "../mp3/" "/." mp3/ % string trimright "../mp3/" "/" ../mp3 convert lowercase characters to UPPERCASE convert UPPERCASE characters to lowercase remove white spaces (spaces, tabs, newlines, carriage returns) from the beginning and the end of the string remove only the specified characters, e.g. ) and ( in this case remove only the specified characters (/ and .) and only from the BEGINNING of the string remove only the specified characters (/) and only from the END of the string • string is a mega-command with many useful functions – Takes an input string and returns its modified value – string does NOT modify the input string Full syntax for the commands above: string toupper string string tolower string string trim string ?chars? string trimleft string ?chars? string trimright string ?chars?
  • 89. 5.9 Copyright © 2024 Abdelazeem Tcl Training Strings (tst1) 5.9 • Be aware of lexicographical rules • Typical use of string comparison/matching Examples: Comparing/Matching Strings % string compare "A" "a" -1 % string compare "Z" "a" -1 % string compare "Z" [string toupper "a"] 1 % string compare "A" "a" -1 % string compare "Z" "a" -1 % string compare "Z" [string toupper "a"] 1 UPPERCASE characters are always BEFORE lowercase characters... Convert strings to either lowercase or UPPERCASE if you want to compare alphabetically. if {[string match *.edif $file]} { puts "Found EDIF file: $file (.edif)" } elseif {[string match *.edn [string tolower $file]]} { puts "Found EDIF file: $file (.edn or .EDN)" } elseif {![string compare "README.txt" $file]} { puts "Found the README file!" } if {[string match *.edif $file]} { puts "Found EDIF file: $file (.edif)" } elseif {[string match *.edn [string tolower $file]]} { puts "Found EDIF file: $file (.edn or .EDN)" } elseif {![string compare "README.txt" $file]} { puts "Found the README file!" } ... which might not be what you expect! returns 1 if there is a match returns 0 if the strings are identical
  • 90. 5.10 Copyright © 2024 Abdelazeem Tcl Training Strings (tst1) 5.10 String Formatting • Strings can be formatted into various forms using the format command – Printing numbers in hexadecimal, octal or decimal format – Aligning text and numbers in columns – Generating text in the format expected by other tools • Typical examples % format "Max period:%15.2e (%f) seconds" $period $period Max period: 4.62e-006 (0.000005) seconds % format "Max period:%15.2e (%f) seconds" $period $period Max period: 4.62e-006 (0.000005) seconds default precision is 6 set number precision to 2 and (min) field width to 15 % set add 65365; set d 31; set period .00000462 .00000462 % format "Writing %d (%#x, %#o) to address %#x" $d $d $d $add Writing 31 (0x1f, 037) to address 0xff55 % set add 65365; set d 31; set period .00000462 .00000462 % format "Writing %d (%#x, %#o) to address %#x" $d $d $d $add Writing 31 (0x1f, 037) to address 0xff55 format syntax format command is similar in capabilities to printf family of functions in C. format formatString ?arg arg ...?
  • 91. 5.11 Copyright © 2024 Abdelazeem Tcl Training Strings (tst1) 5.11 Scanning Strings • scan command extract values from a string according to a format specification – No need to know the character indices – Useful for • Extracting data from error messages and report logs • Parsing input text from the user, and more... – BUT regular expressions are more powerful (more later) • Typical example % set report "Total size: 12345 cells; Clock: 24 MHz" Total size: 12345 cells; Clock: 24 MHz % scan $report "%s%s%d" w1 w2 cells 3 % set cells 12345 % set report "Total size: 12345 cells; Clock: 24 MHz" Total size: 12345 cells; Clock: 24 MHz % scan $report "%s%s%d" w1 w2 cells 3 % set cells 12345 conversion specifiers: string, string, integer variables into which the matching strings will be assigned returns the number of matched strings scan syntax While scan is a useful command for scanning simple string patterns, regular expressions offer more powerful method for scanning strings (Session 8). scan string format varName ?varName ...?
  • 92. 5.12 Copyright © 2024 Abdelazeem Tcl Training Strings (tst1) 5.12 Using Character Indices • Individual characters can be manipulated using their index values with the string command • Character index retrieval – string first and string last search for the first or the last position of character sequences • Accessing characters using indices – string index retrieves a character with a given index – string range retrieves characters within the specified range – string length counts the number of characters H e l l o w o r l d ! 0 1 2 ..................... 11 the first character has index 0
  • 93. 5.13 Copyright © 2024 Abdelazeem Tcl Training Strings (tst1) 5.13 • Retrieve the data packet between two FF2 marks Examples: Character Indices % string first "FF2" $data 7 % string last "FF2" $data 22 % string length $data 33 % string first "FF2" $data 7 % string last "FF2" $data 22 % string length $data 33 % set mark "FF2" FF2 % set packet [ string range $data [expr [string first $mark $data] + [string length $mark]] [expr [string last $mark $data] - 1] ] 0001600B7914 % set mark "FF2" FF2 % set packet [ string range $data [expr [string first $mark $data] + [string length $mark]] [expr [string last $mark $data] - 1] ] 0001600B7914 % string index $data 13 1 % string range $data 10 21 0001600B7914 % string range $data 25 end 03C899FE % string index $data 13 1 % string range $data 10 21 0001600B7914 % string range $data 25 end 03C899FE returns the index of the first character in the match 090FF00FF20001600B7914FF203C899FE 012345678901234567890123456789012 1 2 3 data = end = index of the last character Syntax for the above commands: string first string1 string2 string last string1 string2 string index string charIndex string range string firstIndex lastIndex string length string
  • 94. 5.14 Copyright © 2024 Abdelazeem Tcl Training Strings (tst1) 5.14 Quiz 5 file: examples/quiz5.tcl Answer • What is the value of secret_msg ? Tis great set msg "T eciga lsrt" set code "0 4 9" set i 0 set j 0 while {$i != ([string length $msg]-1)} { foreach k $code { set i [expr $k+$j] append secret_msg [string index $msg $i ] } incr j } puts $secret_msg
  • 95. 5.15 Copyright © 2024 Abdelazeem Tcl Training Strings (tst1) 5.15 LAB 2: Working with a String Bitstream • Write a procedure get_filename which will extract the design file name from a Xilinx FPGA bitstream file (.bit). • Example: • Xilinx bitstream file has the following format % source bitstream.tcl % get_filename $bitstream % source bitstream.tcl % get_filename $bitstream abdelazeem_a d d .ncd .ncd ... 0x61 length (2 bytes) 0x00 0x62 length (2 bytes) part name 0x00 0x63 length (2 bytes) date 0x00 0x64 length (2 bytes) time 0x00 0x65 length (4 bytes) FPGA configuration data little-endian order (most significant byte on the left), unsigned, length includes the trailing 0x00 may contain 0x00, but not 0x61-0x65 design file name this will read the FPGA bitstream and store it in the Tcl variable bitstream Variable bitstream contains bitstream is string in hexadecimal format.
  • 96. 5.16 Copyright © 2024 Abdelazeem Tcl Training Strings (tst1) 5.16 LAB 2: Working with a String Bitstream (2) • Stage 1 – Search for the file name field markers using string first, e.g. set first_marker_index [string first 61 $bitstream] – Extract the file name hex characters from $bitstream using the string range command (from/to indices need to be adjusted) – Use a for loop to extract ASCII characters from the extracted file name string (in hexadecimal format) using the format command, e.g. set ascii_char [format "%c" "0x$hex_character"] – Return the file name • Stage 2 – Extract the other fields from the bitstream header • NOTE: the field data may also contain characters 0x61-0x65 (a-e) ! – Check whether the file name field has the correct length
  • 97. 6.1 Copyright © 2024 Abdelazeem Tcl Training Tcl Scripting for EDA Lists and Arrays
  • 98. 6.2 Copyright © 2024 Abdelazeem Tcl Training Lists and Arrays (tla1) 6.2 Aims and Topics • Aim – To learn how to use Tcl lists and arrays • Topics – Lists • building lists • manipulating lists – Arrays • building arrays • manipulating arrays – Lists versus Arrays
  • 99. 6.3 Copyright © 2024 Abdelazeem Tcl Training Lists and Arrays (tla1) 6.3 What is a List? • List is a collection of ORDERED elements – List elements are strings • Can represent anything (string values, other lists, other Tcl data structures, etc.) – List elements are separated by whitespaces • Spaces, tabs, newlines • Tcl list of 5 elements: % set fruits "apple lemon banana pear grapes" apple lemon banana pear grapes % set fruits "apple lemon banana pear grapes" apple lemon banana pear grapes list element "lemon" separator
  • 100. 6.4 Copyright © 2024 Abdelazeem Tcl Training Lists and Arrays (tla1) 6.4 Manipulating List Elements • Use llength to count the number of elements in a list • Retrieving list elements using indices – lindex returns an element with a given index – lrange returns elements within the given index range – Both return an empty string if the elements could not be found % llength $fruits 5 % llength $fruits 5 apple lemon banana pear grapes 0 1 ....................... 4 the first element has index 0 fruits = % lindex $fruits 1 lemon % lindex $fruits end grapes % lindex $fruits 1 lemon % lindex $fruits end grapes % lrange $fruits 0 2 apple lemon banana % lrange $fruits 3 end pear grapes % lrange $fruits 0 2 apple lemon banana % lrange $fruits 3 end pear grapes index of the last element end = Syntax for the commands above llength list lindex list index lrange list firstIndex lastIndex
  • 101. 6.5 Copyright © 2024 Abdelazeem Tcl Training Lists and Arrays (tla1) 6.5 Nested Lists • Lists can be nested – Use {}’s to define lists within lists • Useful for storing complex data structures, e.g. % set cells "inv {and2 or2} {and3 or3} or4" inv {and2 or2} {and3 or3} or4 % set cells "inv {and2 or2} {and3 or3} or4" inv {and2 or2} {and3 or3} or4 % set library "ams.vhdl {and 2 100} {or 2 120} {inv 1 20}" ams.vhdl {and 2 100} {or 2 120} {inv 1 20} % set library "ams.vhdl {and 2 100} {or 2 120} {inv 1 20}" ams.vhdl {and 2 100} {or 2 120} {inv 1 20} library source file cell data cell name number of inputs cell area % set cells "inv {{and2 nand2} {or2 nor2}}" inv {{and2 nand2} {or2 nor2}} % set cells "inv {{and2 nand2} {or2 nor2}}" inv {{and2 nand2} {or2 nor2}} Tcl returns {}'s to indicate list grouping. The {}'s are NOT part of the list! lists within the cells list lists within the 2nd element of the cells list
  • 102. 6.6 Copyright © 2024 Abdelazeem Tcl Training Lists and Arrays (tla1) 6.6 Building Lists (1) • Use word grouping with "" (or {}) • Use list command • list command respects the list grouping, while "" remove one level of grouping % set fruits [list apple lemon banana pear grapes] apple lemon banana pear grapes % set fruits [list apple lemon banana pear grapes] apple lemon banana pear grapes % set basket "apple lemon" apple lemon % set fruits_list [list $basket banana pear grapes] {apple lemon} banana pear grapes % set fruits_quotes "$basket banana pear grapes" apple lemon banana pear grapes % set basket "apple lemon" apple lemon % set fruits_list [list $basket banana pear grapes] {apple lemon} banana pear grapes % set fruits_quotes "$basket banana pear grapes" apple lemon banana pear grapes compare! 4 elements 5 elements all arguments become list elements list syntax list ?arg arg ...?
  • 103. 6.7 Copyright © 2024 Abdelazeem Tcl Training Lists and Arrays (tla1) 6.7 Building Lists (2) • Use lappend to insert new list elements at the END – Optimised for speed – Will create the list variable if it does not exist • Equivalent to – Slow, but simple! % lappend fruits strawberry orange apple lemon banana pear grapes strawberry orange % lappend fruits strawberry orange apple lemon banana pear grapes strawberry orange name of the list to append (not $fruits!) one or more elements to append % set fruits "$fruits strawberry orange" apple lemon banana pear grapes strawberry orange % set fruits "$fruits strawberry orange" apple lemon banana pear grapes strawberry orange Use lappend when building long lists! lappend syntax lappend is significantly faster then substitution when constructing long lists. Let’s demonstrate the performance difference between using substitution and lappend when constructing lists of various sizes. In the following, list a is constructed in a for loop. The body of the loop contains either set a "$a item" or lappend a "item" Try: source examples/lappend_vs_set.tcl lappend varName ?value value ...? List size 1000 10000 100000 substitution 4 ms 214 ms 193 s lappend 3 ms 30 ms 314 ms speed-up 1.3 7.1 615 Tcl 8.0.5 on Pentium III/1GHz PC, 256MB RAM, Windows 2000
  • 104. 6.8 Copyright © 2024 Abdelazeem Tcl Training Lists and Arrays (tla1) 6.8 Building Lists (3) • Join two or more lists together with concat – Returns a new list – Removes one level of list grouping (same effect as with "") – Eliminates leading and trailing spaces % set basket "apple pear grapes" apple pear grapes % set basket_exotic "lemon banana" lemon banana % set fruits [concat $basket $basket_exotic] apple pear grapes lemon banana % set fruits [list $basket $basket_exotic] {apple pear grapes} {lemon banana} % set basket "apple pear grapes" apple pear grapes % set basket_exotic "lemon banana" lemon banana % set fruits [concat $basket $basket_exotic] apple pear grapes lemon banana % set fruits [list $basket $basket_exotic] {apple pear grapes} {lemon banana} % set fruits [concat $basket_exotic { orange }] lemon banana orange % set fruits "$basket_exotic { orange }" lemon banana { orange } % set fruits [concat $basket_exotic { orange }] lemon banana orange % set fruits "$basket_exotic { orange }" lemon banana { orange } compare! compare! spaces are removed 5 elements 2 elements = lists within a list concat syntax concat ?arg arg ...?
  • 105. 6.9 Copyright © 2024 Abdelazeem Tcl Training Lists and Arrays (tla1) 6.9 Inserting and Replacing List Elements • Use linsert to insert new list elements at ANY position • Use lreplace to replace or delete existing list elements % set fruits "apple lemon banana pear grapes" apple lemon banana pear grapes % set fruits [linsert $fruits 1 apricot] apple apricot lemon banana pear grapes % set fruits [linsert $fruits 4 cherry plum] apple apricot lemon banana cherry plum pear grapes % set fruits "apple lemon banana pear grapes" apple lemon banana pear grapes % set fruits [linsert $fruits 1 apricot] apple apricot lemon banana pear grapes % set fruits [linsert $fruits 4 cherry plum] apple apricot lemon banana cherry plum pear grapes % set fruits [lreplace $fruits 0 1 pineapple peach] pineapple peach lemon banana cherry plum pear grapes % set fruits [lreplace $fruits 3 end] pineapple peach lemon % set fruits [lreplace $fruits 0 1 pineapple peach] pineapple peach lemon banana cherry plum pear grapes % set fruits [lreplace $fruits 3 end] pineapple peach lemon % set fruits [lreplace $fruits 1 1 orange] pineapple orange lemon % set fruits [lreplace $fruits 0 0] orange lemon % set fruits [lreplace $fruits 1 1 orange] pineapple orange lemon % set fruits [lreplace $fruits 0 0] orange lemon insert BEFORE the element with index 1 linsert can insert one or more elements replace elements within this index range (from-to) delete elements within the index range use IDENTICAL indices if only ONE element is to be replaced (or deleted) Syntax for the commands above: linsert list index element ?element element ...? lreplace list firstIndex lastIndex ?element element ...?
  • 106. 6.10 Copyright © 2024 Abdelazeem Tcl Training Lists and Arrays (tla1) 6.10 Example: Reversing the List • Tcl does not provide a command which could reverse the order of elements in a list – Easy to write using the existing list commands • Then use as an ordinary Tcl command proc lreverse {l} { set reversed_l "" foreach element $l { set reversed_l [linsert $reversed_l 0 $element] } return $reversed_l } proc lreverse {l} { set reversed_l "" foreach element $l { set reversed_l [linsert $reversed_l 0 $element] } return $reversed_l } % set fruits "apple lemon banana pear grapes" apple lemon banana pear grapes % set reversed_fruits [lreverse $fruits] grapes pear banana lemon apple % set fruits "apple lemon banana pear grapes" apple lemon banana pear grapes % set reversed_fruits [lreverse $fruits] grapes pear banana lemon apple
  • 107. 6.11 Copyright © 2024 Abdelazeem Tcl Training Lists and Arrays (tla1) 6.11 % set dir_list [split "/Decoder/mp3/buffer/gnd" "/"] {} Decoder mp3 buffer gnd % set dir_list [lreplace $dir_list end end "GND"] {} Decoder mp3 buffer GND % set new_path [join $dir_list "::"] ::Decoder::mp3::buffer::GND % set dir_list [split "/Decoder/mp3/buffer/gnd" "/"] {} Decoder mp3 buffer gnd % set dir_list [lreplace $dir_list end end "GND"] {} Decoder mp3 buffer GND % set new_path [join $dir_list "::"] ::Decoder::mp3::buffer::GND list element separator characters (1 or more) capitalize the name of the last element reconstruct the path using the :: separator Converting between Lists and Strings • It is easy to convert between strings and lists – split splits the string into a set of list elements – join joins the list element into a string – List element separator can be any string (1 space is the default) • Typical uses – Manipulate hierarchical paths (rename elements, change the separator, determine the depth of hierarchy, etc.) – Extract useful information from strings, and more... split the path string into list elements empty element Syntax for the commands above: split string ?splitChars? join list ?joinString?
  • 108. 6.12 Copyright © 2024 Abdelazeem Tcl Training Lists and Arrays (tla1) 6.12 Searching Lists • Use lsearch to search the list for the FIRST element matching the search pattern • Search mode (?mode?) can be -exact exact matching -glob glob-style pattern matching, this is the DEFAULT -regexp regular expression pattern matching (more later) • Return value -1 pattern does NOT match any elements in the list 0-end index of the first element matching the pattern lsearch ?mode? list pattern
  • 109. 6.13 Copyright © 2024 Abdelazeem Tcl Training Lists and Arrays (tla1) 6.13 Examples: Searching Lists • Glob-style pattern matching • Exact matching % set cell_list "inv and2 or2 and3 or3 or4" inv and2 or2 and3 or3 or4 % lsearch $cell_list or* 2 % lsearch -glob $cell_list xor* -1 % set cell_list "inv and2 or2 and3 or3 or4" inv and2 or2 and3 or3 or4 % lsearch $cell_list or* 2 % lsearch -glob $cell_list xor* -1 % lsearch -exact $cell_list or4 5 % lsearch -exact $cell_list and -1 % lsearch -exact $cell_list or4 5 % lsearch -exact $cell_list and -1 optional (-glob is the default) glob-style search patterns exact strings to be matched or2 found at index 2 -1 = not found
  • 110. 6.14 Copyright © 2024 Abdelazeem Tcl Training Lists and Arrays (tla1) 6.14 Sorting Lists • Use lsort to sort list elements • lsort is a very powerful sorting command; various features are available through lsort options – Sort in increasing (default) or decreasing order – Sort strings using ASCII (default) or dictionary comparison – Sort numbers using integer or real number comparison – Sort using a custom comparison command % set sorted_cmds [lsort [info commands]] after append array auto_execok auto_import auto_load auto_load_index auto_mkindex auto_mkindex_old auto_qualify auto_reset binary break case catch cd clock close concat ... % set sorted_cmds [lsort [info commands]] after append array auto_execok auto_import auto_load auto_load_index auto_mkindex auto_mkindex_old auto_qualify auto_reset binary break case catch cd clock close concat ... returns the list of Tcl commands (UNSORTED) SORTED list of commands lsort syntax lsort ?options? list
  • 111. 6.15 Copyright © 2024 Abdelazeem Tcl Training Lists and Arrays (tla1) 6.15 Example: Sorting Blocks in a Hierarchy • Sort design blocks using their hierarchical position – Top-level first, bottom-level least • First define a custom hierarchy comparison command • Then use lsort to sort the blocks set blocks "/Decoder/mp3/u1 /Decoder/mp3/buffer/u1 /Decoder/mp3/u2 /Decoder /Decoder/mp3 /Decoder/GND" set blocks "/Decoder/mp3/u1 /Decoder/mp3/buffer/u1 /Decoder/mp3/u2 /Decoder /Decoder/mp3 /Decoder/GND" proc hier_cmp {p1 p2} { set p1_list [split $p1 "/"] set p2_list [split $p2 "/"] expr {[llength $p1_list] - [llength $p2_list]} } proc hier_cmp {p1 p2} { set p1_list [split $p1 "/"] set p2_list [split $p2 "/"] expr {[llength $p1_list] - [llength $p2_list]} } % lsort -command hier_cmp $blocks /Decoder /Decoder/mp3 /Decoder/GND /Decoder/mp3/u1 /Decoder/mp3/u2 /Decoder/mp3/buffer/u1 % lsort -command hier_cmp $blocks /Decoder /Decoder/mp3 /Decoder/GND /Decoder/mp3/u1 /Decoder/mp3/u2 /Decoder/mp3/buffer/u1 Decoder mp3 GND u1 u2 buffer u1 custom comparison command should return: +int when p1 > p2 0 when p1 = p2 -int when p1 < p2 compare using the custom comparison command (hier_cmp) sorting order The above example demonstrates one of the main features of Tcl—productivity. Tcl allows for complex tasks to be coded rapidly.
  • 112. 6.16 Copyright © 2024 Abdelazeem Tcl Training Lists and Arrays (tla1) 6.16 Lists: Summary • A powerful Tcl data object, which maintains the order of its elements • Can be created using a variety of methods – substitution – concatenation – append • List elements can be accessed using an integer index • Tcl provides commands for list manipulation – Creating lists – Inserting/deleting list elements – Searching for elements matching a pattern – Sorting list elements
  • 113. 6.17 Copyright © 2024 Abdelazeem Tcl Training Lists and Arrays (tla1) 6.17 What is an Array? • An array is a collection of LABELLED elements – Tcl arrays are associative; each element is identified by a key (also called ‘index’, ‘label’ or ‘address’) – Array element values and keys are STRINGS • Assigning/reading the value of an array element key value array variable name % set IT_people(john) memo memo % set IT_people(john) memo % set IT_people(john) memo memo % set IT_people(john) memo array variable name key value enclose the key within parenthesis will return an ERROR if the key cannot be found All keys in the array must be defined before the key is to be accessed. For example, set IT_people(edward) will generate an error message.
  • 114. 6.18 Copyright © 2024 Abdelazeem Tcl Training Lists and Arrays (tla1) 6.18 Basic Array Operations • Arrays and their elements can be manipulated as other Tcl variables – Retrieve element’s value using variable substitution – Remove the element or the entire array • Element key can be also stored in a variable % puts "John received a $IT_people(john)." John received a memo. % puts "John received a $IT_people(john)." John received a memo. % unset IT_people(john) % unset IT_people % unset IT_people(john) % unset IT_people % set name "john" john % puts "John received a $IT_people($name)." John received a memo. % set name "john" john % puts "John received a $IT_people($name)." John received a memo.
  • 115. 6.19 Copyright © 2024 Abdelazeem Tcl Training Lists and Arrays (tla1) 6.19 Manipulating Arrays • New array elements can be added – One at a time – One or more elements in one command using array set • Use array get to retrieve the entire contents of the array % set IT_people(phil) "fax message" fax message % set IT_people(phil) "fax message" fax message % array set IT_people { bill "vacancy notice" angela "pay slip" } % array set IT_people { bill "vacancy notice" angela "pay slip" } % array get IT_people angela {pay slip} phil {fax message} bill {vacancy notice} john memo % array get IT_people angela {pay slip} phil {fax message} bill {vacancy notice} john memo key value key value array set and array get are useful when converting between arrays and lists Syntax for the commands above array set arrayName list array get arrayName ?pattern? use optional pattern to retrieve only those elements which match the glob-style pattern
  • 116. 6.20 Copyright © 2024 Abdelazeem Tcl Training Lists and Arrays (tla1) 6.20 Multi-dimensional Arrays • Arrays may represent multi-dimensional objects – Use keys which ‘look’ like multi-dimensional indices – Keys are still STRINGS, only they contain special characters (e.g. commas) % set image(0,0) 255 255 % set image(0,1) 33 33 % puts "Pixel intensity at (0,1) is $image(0,1)." Pixel intensity at (0,1) is 33. % set image(0,0) 255 255 % set image(0,1) 33 33 % puts "Pixel intensity at (0,1) is $image(0,1)." Pixel intensity at (0,1) is 33. 2D array looks like two indices (0, 0), but this is really a string "0,0"! % set frame_set(10,100,2) 250 250 % set synthesis_results(smallest,23ns) 34mW 34mW % set image(filename) lena.rgb lena.rgb % set frame_set(10,100,2) 250 250 % set synthesis_results(smallest,23ns) 34mW 34mW % set image(filename) lena.rgb lena.rgb string! 3D array easy to combine 1D, 2D, 3D, ... elements in ONE array! Avoid spaces in array keys! image(0,0) and image(0, 0) are two DIFFERENT array elements!
  • 117. 6.21 Copyright © 2024 Abdelazeem Tcl Training Lists and Arrays (tla1) 6.21 Examining Arrays • Use array mega-command to obtain information about array variables – Check for the existence of the array variable • Returns 0 if the variable is not an array or it does not exist • Returns 1 otherwise – Retrieve the number of elements in the array – Retrieve the list of array keys % array exists IT_people 1 % array exists IT_people 1 % array size IT_people 4 % array size IT_people 4 % array names IT_people angela phil bill john % array names IT_people angela phil bill john Syntax for the above commands array mega-command provides other useful functions. For example it is possible to retrieve array elements sequentially using array startsearch, array nextelement, array anymore, and array donesearch. For more details, consult array manual page. array exists arrayName array size arrayName array names arrayName ?pattern? use optional pattern to retrieve only the keys matching the glob-style pattern
  • 118. 6.22 Copyright © 2024 Abdelazeem Tcl Training Lists and Arrays (tla1) 6.22 Examples: Using Arrays • Look-up table • 2D image data storage % array set ports { and2 {i1 i2 o1} or2 {i1 i2 o1} inv {i1 o1} half_add {i1 i2 o1 cout} full_add {i1 i2 cin o1 cout} } % set cell "and2" and2 % puts "Cell $cell has ports: $ports($cell)" Cell and2 has ports: i1 i2 o1 % array set ports { and2 {i1 i2 o1} or2 {i1 i2 o1} inv {i1 o1} half_add {i1 i2 o1 cout} full_add {i1 i2 cin o1 cout} } % set cell "and2" and2 % puts "Cell $cell has ports: $ports($cell)" Cell and2 has ports: i1 i2 o1 % for {set x 0} {$x < 256} {incr x} { for {set y 0} {$y < 256} {incr y} { set image($x,$y) $y } } % for {set x 0} {$x < 256} {incr x} { for {set y 0} {$y < 256} {incr y} { set image($x,$y) $y } } (0,0) (255,255)
  • 119. 6.23 Copyright © 2024 Abdelazeem Tcl Training Lists and Arrays (tla1) 6.23 Lists versus Arrays LISTS • Can store various elements • Order of elements is preserved • Elements are retrieved using an INTEGER index • Lists are manipulated using the list value ARRAYS • Can store various elements • Order of elements if NOT preserved • Elements are retrieved using a STRING key • Arrays are manipulated using the name of the array variable • Since Tcl 8.0 there is NO PERFORMANCE DIFFERENCE between Tcl lists and arrays % set l [list r g b] r g b % llength $l 3 % set l [list r g b] r g b % llength $l 3 % array set a { r RED g GREEN b BLUE } % array names a b r g % array set a { r RED g GREEN b BLUE } % array names a b r g list l is accessed by its value $l (not l) array a is accessed by the name of array variable a (not $a) order is NOT preserved order is preserved Lists and arrays provide two ways of storing multiple data elements. When deciding between the two, it is best to choose a data structure which is the most natural representation of the data. For example, a phone book is most naturally represented in an array as names can be used as array keys. A list of files is usually represented using lists, as this allows easy file browsing, sorting and manipulation. Before Tcl 8.0 lists access was much slower than array access. Since Tcl 8.0 both lists and arrays are internally represented using similar data structures. Tcl then provides advantages of using linked lists, but with the performance of array access.
  • 120. 6.24 Copyright © 2024 Abdelazeem Tcl Training Lists and Arrays (tla1) 6.24 Quiz 6 • What are the values stored in b and c? (a) b = "" and c = "" (both are empty strings) (b) b = pear and c = pear (c) b = pear, but c assignment generates an error (d) b = apple, but c assignment generates an error (e) b = "", but c assignment generates an error (f) b assignment generates an error and c = "" set a_list {apple lemon pear} array set a_array {0 apple 1 lemon 2 pear} set b [lindex $a_list 3] puts "b = "$b"" set c [$a_array(3)] puts "c = "$c"" set a_list {apple lemon pear} array set a_array {0 apple 1 lemon 2 pear} set b [lindex $a_list 3] puts "b = "$b"" set c [$a_array(3)] puts "c = "$c"" file: examples/quiz6.tcl Answer
  • 121. 6.25 Copyright © 2024 Abdelazeem Tcl Training Lists and Arrays (tla1) 6.25 LAB 3: Sorting Design Blocks • Write a procedure sort_by_area which will sort the design blocks according to their area – decoder is a global list which contains the list of design blocks – block_area is a global array which stores areas of all leaf blocks • For example $block_area(/Decoder/mp3/u1) is the area of the /Decoder/mp3/u1 block • Example: % source decoder.tcl % sort_by_area $decoder /Decoder/GND /Decoder/buffer/u1 /Decoder/mp3/u1 /Decoder/mp3/u2 % source decoder.tcl % sort_by_area $decoder /Decoder/GND /Decoder/buffer/u1 /Decoder/mp3/u1 /Decoder/mp3/u2 Decoder mp3 GND u1 u2 buffer u1
  • 122. 6.26 Copyright © 2024 Abdelazeem Tcl Training Lists and Arrays (tla1) 6.26 LAB 3: Sorting Design Blocks (2) • Stage 1 – Sort the decoder list using a custom sorting command • Use global block_area to allow access to the block_area global variable from within the custom comparison command • Stage 2 – Include both the sorted block names and their respective areas in the returned result • Each element is a list with 2 elements: block name & area – Construct a sub-list containing only the leaf blocks extracted from the list of all design cells available in the decoder_full variable • Use lsearch [array names block_area] $block_name to check whether an area figure can be obtained for the block – Calculate the total area for all blocks in the decoder list, including the hierarchical blocks (mp3 and Decoder)
  • 123. 7.1 Copyright © 2024 Abdelazeem Tcl Training Tcl Scripting for EDA File I/O and Program Access
  • 124. 7.2 Copyright © 2024 Abdelazeem Tcl Training File I/O and Program Access (tfp1) 7.2 Aims and Topics • Aim – To learn about how to access files, execute programs and create simple networking applications • Topics – Reading from and writing to files – Invoking external programs – Multi-process communication
  • 125. 7.3 Copyright © 2024 Abdelazeem Tcl Training File I/O and Program Access (tfp1) 7.3 File Manipulation Revisited • Simple file manipulation with cd, pwd and glob • file command provides many other operations, e.g.: % file mkdir ~/project/daily_backup % file copy add_v2.vhdl ~/project/daily_backup % file rename sub_v4.vhdl sub.vhd % file rename sub.vhd ~/project/archive % file delete compile.log % file mkdir ~/project/daily_backup % file copy add_v2.vhdl ~/project/daily_backup % file rename sub_v4.vhdl sub.vhd % file rename sub.vhd ~/project/archive % file delete compile.log % file isdirectory ~/project 1 % file dirname ~/project/README ~/project % file mtime add_v2.vhdl 994776518 % file exists add_v3.vhdl 0 % file readable add_v2.vhdl 1 % file isdirectory ~/project 1 % file dirname ~/project/README ~/project % file mtime add_v2.vhdl 994776518 % file exists add_v3.vhdl 0 % file readable add_v2.vhdl 1 CREATE a directory COPY a file/directory RENAME a file/directory MOVE a file/directory DELETE a file/directory test whether the file is a directory extract only the directory name from the path Prefer using file Tcl command to platform- specific file commands to improve portability. test whether the file exists test whether the file is readable extract file modification time (more on time later) Full syntax for the commands above: file mkdir dir ?dir ...? file copy ?-force? ?--? source target file copy ?-force? ?--? source ?source ...? targetDir file rename ?-force? ?--? source target file rename ?-force? ?--? source ?source ...? targetDir file delete ?-force? ?--? pathName ?pathName ...? file isdirectory name file dirname name file mtime name file exists name file readable name
  • 126. 7.4 Copyright © 2024 Abdelazeem Tcl Training File I/O and Program Access (tfp1) 7.4 Opening and Closing Files • Use open to open a file for access – Returns a channel identifier (also called a file id or descriptor) which is UNIQUE for each opened file • After you finish accessing the file, close it with close – Channel identifier is invalidated after the file was closed % set fid [open test1.dat w] file24 % set fid [open test1.dat w] file24 % close $fid % close $fid To improve performance, do not leave files open when they are not being used. file24 is the channel identifier file name access mode r read only (default) r+ read/write (file must already exist) w write only w+ read/write a append only a+ read/append open syntax close syntax open fileName close channelId open fileName access open fileName access permissions
  • 127. 7.5 Copyright © 2024 Abdelazeem Tcl Training File I/O and Program Access (tfp1) 7.5 Catching Command Errors • Use the catch command to trap and handle errors from specific commands/scripts – Returns 1 if there was an error executing Tcl command, 0 otherwise – result contains the error message returned by the command, or the command result (if the command did not generate an error) • Beware – catch also suppresses syntax and programming errors – Use catch at lowest possible level to catch only the errors you expect! % catch {set fid [open does_not_exist.txt r]} result 1 % set result couldn’t open "does_not_exist.txt": no such file or directory % catch {set fid [open does_not_exist.txt r]} result 1 % set result couldn’t open "does_not_exist.txt": no such file or directory !
  • 128. 7.6 Copyright © 2024 abdelazeem Tcl Training File I/O and Program Access (tfp1) 7.6 Writing to Files • Use puts to write to files – Returns an empty string on success, error message otherwise • Special channels are available for standard terminal I/O – stdout (standard terminal output), stderr (standard terminal error output), stdin (standard terminal input) % puts $fid "Hello world!" % % puts -nonewline $fid "Hello world!" % % puts $fid "Hello world!" % % puts -nonewline $fid "Hello world!" % write "Hello world!" + newline into an open file with channel ID $fid write "Hello world!" only (no newline) % puts stdout "Hello world!" Hello world! % puts "Hello world!" Hello world! % puts stderr "Error: invalid input!" Error: invalid input! % puts stdout "Hello world!" Hello world! % puts "Hello world!" Hello world! % puts stderr "Error: invalid input!" Error: invalid input! write "Hello world!" + newline to standard terminal output (stdout channel is the default) write an error message to standard terminal error output Full puts syntax: Be warned that stdin/out and stderr exist only when there is a terminal window. On NT stdout and stderr are identical. puts ?-nonewline? ?channelId? string
  • 129. 7.7 Copyright © 2024 Abdelazeem Tcl Training File I/O and Program Access (tfp1) 7.7 File Pointer Position • Files are accessed using an “invisible” file pointer – Positioned at the beginning when the file is opened – Moves forward with each file read • Use seek to set the file pointer to the desired position T H I 0 1 2 ... the file origin has index 0 S I S L I N E 1 n T H I S test1.dat: ... moves forward as the characters are read % seek $fid 5 start % seek $fid 8 current % seek $fid -10 end % seek $fid 5 start % seek $fid 8 current % seek $fid -10 end move the file pointer 5 positions AFTER the file origin move the file pointer 8 positions AFTER the current position move the file pointer 10 positions BEFORE the end of the file file pointer offset offset origin seek syntax seek channelId offset ?origin?
  • 130. 7.8 Copyright © 2024 Abdelazeem Tcl Training File I/O and Program Access (tfp1) 7.8 Reading Lines • Use gets to read LINES from an open channel – There are two alternative forms • Typical uses – Processing files and communication channel data line-by-line – Building INTERACTIVE command-line scripts % set line [gets $fid] THIS IS LINE 1 % set chars [gets $fid line] 14 % set line [gets $fid] THIS IS LINE 1 % set chars [gets $fid line] 14 gets returns the next line read from an open channel with $fid identifier. (next line = all characters until the end of line) gets stores the next line into variable line, and returns the number of characters read or -1 if the end of file was reached set fid [open "test1.dat" r] while {[gets $fid line] >= 0} { puts "test1.dat: $line" } close $fid set fid [open "test1.dat" r] while {[gets $fid line] >= 0} { puts "test1.dat: $line" } close $fid the while loop will terminate at the end of file (gets will return -1) gets syntax gets channelId ?varName?
  • 131. 7.9 Copyright © 2024 Abdelazeem Tcl Training File I/O and Program Access (tfp1) 7.9 Example: Interactive Command-Line Script puts "Welcome to a simple interactive script!" source to_bits.tcl while {1} { puts "nCommand:" gets stdin line if {$line == ""} {continue} switch -- [lindex $line 0] { quit - exit {break} dec2bits {puts [ to_bits [lindex $line 1] ]} dir - ls {puts [ glob * ]} default {puts stderr "Error: unrecognized command"} } } puts "Thank you!" puts "Welcome to a simple interactive script!" source to_bits.tcl while {1} { puts "nCommand:" gets stdin line if {$line == ""} {continue} switch -- [lindex $line 0] { quit - exit {break} dec2bits {puts [ to_bits [lindex $line 1] ]} dir - ls {puts [ glob * ]} default {puts stderr "Error: unrecognized command"} } } puts "Thank you!" file: examples/interactive.tcl source other scripts if required enter an indefinite while loop (can be broken with exit) print the prompt and collect the input from the user parse and execute the commands skip if no command was supplied by the user
  • 132. 7.10 Copyright © 2024 Abdelazeem Tcl Training File I/O and Program Access (tfp1) 7.10 Reading Characters • Use read to read CHARACTERS from an open channel – There are two alternative forms • Typical uses – Reading the content of an entire file for further processing – Processing text or binary files character-by-character – Reading characters from communication channels % set seven_chars [read $fid 7] THIS IS % set seven_chars [read $fid 7] THIS IS % set file [read -nonewline $fid] THIS IS LINE 1 ... THIS IS LINE 9 % set file [read -nonewline $fid] THIS IS LINE 1 ... THIS IS LINE 9 read next 7 characters from an open channel $fid read until the end of the file from an open channel $fid discard the last newline, if present (optional) read syntax: read ?-nonewline? channelId read channelId numBytes
  • 133. 7.11 Copyright © 2024 Abdelazeem Tcl Training File I/O and Program Access (tfp1) 7.11 Checking for the End of File • Use eof command to check for the end of file position – Returns 1 at the end of file, 0 otherwise – Provides a simple alternative to gets end of file detection • Example: processing files character-by-character while {![eof $fid]} { gets $fid line puts "test1.dat: $line" } while {![eof $fid]} { gets $fid line puts "test1.dat: $line" } repeat the while loop until the end of file set src [open "test1.dat" r] set dest [open "test2.dat" w] while {![eof $src]} { set c [read $src 1] puts -nonewline $dest "$c$c$c" } close $src close $dest set src [open "test1.dat" r] set dest [open "test2.dat" w] while {![eof $src]} { set c [read $src 1] puts -nonewline $dest "$c$c$c" } close $src close $dest read ONE character at the time write the result to the output file (e.g. write 3 copies of the input character) eof syntax: eof channelId
  • 134. 7.12 Copyright © 2024 Abdelazeem Tcl Training File I/O and Program Access (tfp1) 7.12 Portability Issues • End-of-line is represented by n on ALL Tcl platforms – Incompatible end-of-line characters are automatically converted to the end-of-line characters used by the host platform • For portable file manipulation – Avoid code dependent on the case of characters in filenames – Avoid using special characters (<>:"/|.) in filenames – Use Tcl file manipulation commands (cd, pwd, glob, file), NOT the platform-specific commands proc correct_newlines {src_file dest_file} { set src [open $src_file r] set dest [open $dest_file w] puts $dest [read $src] close $src close $dest } proc correct_newlines {src_file dest_file} { set src [open $src_file r] set dest [open $dest_file w] puts $dest [read $src] close $src close $dest } destination file will use end- of-line characters of the host platform file: examples/correct_newlines.tcl Tcl also supports the compatible subset of the native platform's file path convention. However, this will only work on one native platform. It is advisable avoid using this and use portable Tcl file path handling instead. Although the forward slash is the directory separator, one should use file split and file join to analyze and construct the filenames.
  • 135. 7.13 Copyright © 2024 Abdelazeem Tcl Training File I/O and Program Access (tfp1) 7.13 NO buffering LINE buffering FULL buffering T H I S L Channel Buffering puts 1 n T I ... I N E I S H T THIS IS LINE 1n THIS IS LINE 2n THIS IS LINE 1n THIS IS LINE 2n THIS IS LINE 3n ... THIS IS LINE 9n H channel buffer There is an internal buffer associated with each I/O channel. For example, when puts command puts characters into a channel, the characters are first buffered and only then send to the channel. There are three possible methods of channel buffering: • NO buffering: the characters are not buffered at all. The characters are output as they are received. This type of buffering is slow due to frequent I/O operations. Try: source examples/buffering_none.tcl • LINE buffering: the output is flushed after each end-of-line character. Line buffering is the default type of buffering for terminal devices (such as stdout). Try: source examples/buffering_line.tcl • FULL buffering: the output is flushed after the internal buffer was filled with characters. Full buffering is the default for file access as this provides a good performance trade-off (I/O access occurs only after the internal buffer was filled). Try: source examples/buffering_full.tcl
  • 136. 7.14 Copyright © 2024 Abdelazeem Tcl Training File I/O and Program Access (tfp1) 7.14 Configuring Channel Buffers • fconfigure is used to configure the type of channel buffering • The contents of the channel buffer can be flushed at ANY TIME using the flush command ... fconfigure stdout -buffering none ... ... fconfigure stdout -buffering none ... buffering mode none no buffering line line buffering full full buffering file: examples/buffering_none.tcl ... puts -nonewline "> " flush stdout gets stdin line ... ... puts -nonewline "> " flush stdout gets stdin line ... file: examples/interactive2.tcl flushes the stdout channel buffer to print the prompt Use fconfigure to change properties of an open channel at ANY time during channel access. Channel properties which can be changed include: • Automatic end-of-line conversion • End-of-file character • Channel blocking and buffering fconfigure syntax flush syntax fconfigure channelId fconfigure channelId optionName fconfigure channelId optionName optionValue ?optionName optionValue? flush channelId
  • 137. 7.15 Copyright © 2024 Abdelazeem Tcl Training File I/O and Program Access (tfp1) 7.15 Invoking External Programs • Use exec to invoke external programs • auto_noexec variable controls whether the interpreter searches the native shell for unrecognized commands – If auto_noexec does not exist – If auto_noexec is defined (contains ANY value) % exec zip archive.zip test1.dat adding: test1.dat (92 bytes security) (deflated 72%) % exec zip archive.zip test1.dat adding: test1.dat (92 bytes security) (deflated 72%) % zip archive.zip test1.dat adding: test1.dat (92 bytes security) (deflated 72%) % zip archive.zip test1.dat adding: test1.dat (92 bytes security) (deflated 72%) % set auto_noexec "" % zip archive.zip test1.dat invalid command name "zip" % set auto_noexec "" % zip archive.zip test1.dat invalid command name "zip" no exec required external program ...and its arguments external program output is returned back to the Tcl interpreter exec syntax exec ?switches? arg ?arg ...?
  • 138. 7.16 Copyright © 2024 Abdelazeem Tcl Training File I/O and Program Access (tfp1) 7.16 Problems with Multiple Arguments • Trying to remove ALL log files, but... • ...easily solved with eval – eval will force another round of word separation and substitutions before the exec command is executed % glob *.log simulation.log synthesis.log test.log % exec rm [glob *.log] simulation.log synthesis.log test.log: no such file or directory % glob *.log simulation.log synthesis.log test.log % exec rm [glob *.log] simulation.log synthesis.log test.log: no such file or directory exec rm simulation.log synthesis.log test.log WHY? Treated by rm as ONE file name! exec rm simulation.log synthesis.log test.log eval % eval exec rm [glob *.log] % eval exec rm [glob *.log] eval syntax eval arg ?arg ...?
  • 139. 7.17 Copyright © 2024 Abdelazeem Tcl Training File I/O and Program Access (tfp1) 7.17 Problems Executing External Programs • tclsh is NOT a UNIX shell (/bin/sh, /bin/tcsh, etc.) – UNIX shell wildchars, substitution and quoting do NOT work • tclsh is NOT a Windows/DOS shell (command.com) – Built-in Windows/DOS commands cannot be executed directly % exec tar -cvf archive.tar project/* tar: projects/*: Cannot stat: No such file or directory ... % eval exec tar -cvf archive.tar [glob project/*] ... % exec tar -cvf archive.tar project/* tar: projects/*: Cannot stat: No such file or directory ... % eval exec tar -cvf archive.tar [glob project/*] ... UNIX shell wildchars don’t work in Tcl! use glob instead % set dir_list [exec dir C:*.*] couldn’t execute "dir": no such file or directory % % set dir_list [exec COMMAND.COM /C dir C:*.*] ... % set dir_list [exec dir C:*.*] couldn’t execute "dir": no such file or directory % % set dir_list [exec COMMAND.COM /C dir C:*.*] ... dir is a built-in command invoke command.com with built-in command as an argument instead ! ! NOTE! Similarly to Windows/DOS shell example above, you may also invoke commands using a UNIX shell directly. For example, an alternative way of executing the tar command above is exec /bin/sh -c "tar -cvf archive.tar project/*" This will execute correctly as the string given to the -c option is executed by the UNIX shell (/bin/sh).
  • 140. 7.18 Copyright © 2024 Abdelazeem Tcl Training File I/O and Program Access (tfp1) 7.18 Input/Output Redirection • Tcl implements a range of I/O redirection operators – Redirection of standard input, output and error channels to/from files (overwrite and append modes) – Receive standard input from a Tcl string – Piping standard output to standard input between two commands % exec compress << "Hello world!" > foo.Z % % set stats [exec zcat foo.Z | wc] 0 2 12 % exec compress << "Hello world!" > foo.Z % % set stats [exec zcat foo.Z | wc] 0 2 12 read from a Tcl string write standard output to a file pipe standard output from zcat as standard input to wc
  • 141. 7.19 Copyright © 2024 Abdelazeem Tcl Training File I/O and Program Access (tfp1) 7.19 Processes in Tcl • Start a new process with exec and & (ampersand)... – Returns the process ID on success, an error message otherwise • ...or using open with a pipe and use the pid command to retrieve the process ID % exec notepad.exe & 1476 % exec notepad.exe & 1476 process ID % set fid [open "| ipconfig" r] file24 % pid $fid 1164 % set fid [open "| ipconfig" r] file24 % pid $fid 1164 process ID external program to invoke external program to invoke the standard output from the ipconfig program can be accessed as a CHANNEL pipe pid syntax pid ?field?
  • 142. 7.20 Copyright © 2024 Abdelazeem Tcl Training File I/O and Program Access (tfp1) 7.20 Multi-Process Communication HDL Simulator HDL Simulator Hardware test rig Hardware test rig commands results % set fid [open "| test_rig" r+] file24 % fconfigure $fid -buffering line % puts $fid "test1 100" % gets $fid test1: 1000 % puts $fid "test2 200" % gets $fid test2: 400 % close $fid % set fid [open "| test_rig" r+] file24 % fconfigure $fid -buffering line % puts $fid "test1 100" % gets $fid test1: 1000 % puts $fid "test2 200" % gets $fid test2: 400 % close $fid Hardware test rig Hardware test rig read/write mode (bi-directional communication) external program (can be another Tcl script!) CLIENT SERVER IMPORTANT: set-up LINE buffering (FULL buffering is the default for files) The above is the example of SYNCHRONOUS communication, i.e. the client application always waits for the response from the server before proceeding further. Tcl can be also used to build ASYNCHRONOUS communication channels, which are typically used in servers and GUI applications. For more details on writing multi-process and networking applications in Tcl can be found in Appendix C - Client-Server Applications and Networking.
  • 143. 7.21 Copyright © 2024 Abdelazeem Tcl Training File I/O and Program Access (tfp1) 7.21 Quiz 7 • What is the contents of test3.dat? (a) nothing (file test3.dat is an empty file) (b) Hello (c) Hellon (d) Hellon world! (e) Hellon world!n (f) file test3.dat does not exist set fid [open "test3.dat" w] puts -nonewline $fid "Hellon world!" set fid [open "test3.dat" w] puts -nonewline $fid "Hellon world!" file: examples/quiz7.tcl Answer
  • 144. 7.22 Copyright © 2024 Abdelazeem Tcl Training
  • 145. 8.1 Copyright © 2024 Abdelazeem Tcl Training Tcl Scripting for EDA Regular Expressions
  • 146. 8.2 Copyright © 2024 Abdelazeem Tcl Training Regular Expressions (tre1) 8.2 Aims and Topics • Aim – To gain proficiency in using regular expressions for advanced string processing • Topics – Regular expressions (REs): what and why? – Regular expression patterns – RE-based string searching – RE-based string replacement
  • 147. 8.3 Copyright © 2024 Abdelazeem Tcl Training Regular Expressions (tre1) 8.3 Why Regular Expressions? • String search capabilities already exist in Tcl – lsearch, string match, switch, etc. – Inefficient for complex string search/replace operations • Regular Expressions can handle complex and repetitive string manipulation tasks efficiently entity add is ... a : in std_logic_vector(7 downto 0); cin : in std_logic; ... end add; architecture struct of add is ... sum <= result(7 downto 0); cout <= result(8); ... end struct; entity add32 is ... a : in std_logic_vector(0 to 31); cin : in std_logic; ... end add32; architecture struct of add32 is ... sum <= result(0 to 31); cout <= result(32); ... end struct; transformed using a set of rules
  • 148. 8.4 Copyright © 2024 Abdelazeem Tcl Training Regular Expressions (tre1) 8.4 What are Regular Expressions? • Special string patterns which can match strings using various rules – Context-specific – Generic (will work for many different strings) • Example – RE for an output port declaration in a VHDL entity: entity add is port ( cin : in std_logic; a : in std_logic_vector(7 downto 0); b : in std_logic_vector(7 downto 0); y : out std_logic_vector(7 downto 0); cout: out std_logic ); end add; *[a-zA-Z][a-zA-Z0-9_]* *: *out [a-zA-Z][a-zA-Z0-9_]* *[a-zA-Z][a-zA-Z0-9_]* *: *out [a-zA-Z][a-zA-Z0-9_]* regular expression string matching the regular expression NOTE: RE string matching is based on context (e.g. signal which is a 1-bit output port). Therefore the matching will work for signals of any name or type.
  • 149. 8.5 Copyright © 2024 Abdelazeem Tcl Training Regular Expressions (tre1) 8.5 Regular Expression Basics • Alphabet and digit characters are matched as usual a matches a SINGLE given character, i.e. character a VHDL matches a SEQUENCE of given characters, i.e. string VHDL • Regular expressions use several special characters . matches ANY SINGLE character [] matches a SINGLE character from a sequence, e.g. [abc] [A-Z] [^A-Z] [a-zA-Z0-9_] * matches 0 or more occurrences of a preceding ATOM a* [a-z]* [A-Z][a-z]* .* a or b or c (single character) an uppercase letter (character range) a character which is either a letter (lowercase or uppercase), a digit or an underscore 0 or more characters a, e.g a or aaaaa, but also '' (no character) 0 or more lowercase letters word with the first letter in uppercase (0 or more lowercase letters) 0 or more occurrences of any character, i.e. ALL characters a character which is NOT an uppercase letter
  • 150. 8.6 Copyright © 2024 Abdelazeem Tcl Training Regular Expressions (tre1) 8.6 Searching with Regular Expressions • Use regexp command for RE-based string search – regexp returns 1 if the match was found, 0 otherwise • Use -nocase option for case-insensitive search • RE patterns always match the LONGEST possible string of characters % regexp {[A-Z][A-Z]*} "which is better: VHDL or Verilog?" m_var 1 % set m_var VHDL % regexp {[A-Z][A-Z]*} "which is better: VHDL or Verilog?" m_var 1 % set m_var VHDL regular expression pattern string to search variable which will store the matched string Enclose RE patterns within {} to protect patterns from Tcl substitution (unless the substitution is desired) % regexp -nocase -- {[A-Z][A-Z]*} "which is better: ..." m_var 1 % set m_var which % regexp -nocase -- {[A-Z][A-Z]*} "which is better: ..." m_var 1 % set m_var which Always use -- to prevent regexp from confusing patterns with options.
  • 151. 8.7 Copyright © 2024 Abdelazeem Tcl Training Regular Expressions (tre1) 8.7 Example: Find the First VHDL Entity Line set fid [open "adder.vhdl" r] set add [read $fid] close $fid regexp -nocase -- { *entity *[a-z][a-z0-9_]* *is *} $add e_line puts "$e_line" set fid [open "adder.vhdl" r] set add [read $fid] close $fid regexp -nocase -- { *entity *[a-z][a-z0-9_]* *is *} $add e_line puts "$e_line" file: examples/find_entity_line.tcl % cd examples % source find_entity_line.tcl entity add is % cd examples % source find_entity_line.tcl entity add is entity add is port ( ... ); end add; ... file: examples/adder.vhdl regexp syntax regexp ?switches? exp string ?matchVar? ?subMatchVar subMatchVar ...?
  • 152. 8.8 Copyright © 2024 Abdelazeem Tcl Training Regular Expressions (tre1) 8.8 More RE Symbols • Characters and strings matching ^ matches the BEGINNING of a line, e.g. ^architecture $ matches the END of a line, e.g. ;$ • Alternatives x|y matches ONE of the two possible atoms, e.g. out|in [a-z]|[0-9] • Use () to group atoms together, e.g. ([a-z][a-z]*)|[0-9] string architecture at the beginning of a line character ; at the end of line string out OR string in lowercase letter OR a digit lowercase word of 1 or more letters OR a digit
  • 153. 8.9 Copyright © 2024 Abdelazeem Tcl Training Regular Expressions (tre1) 8.9 More RE Symbols (2) • Sequence matching + matches 1 or more occurrences of a preceding atom + [a-z]+ ? matches 0 or 1 occurrence of a preceding atom ? [a-z]? • Meaning of all special RE characters can be escaped with a backslash () ((+?)|-)[0-9]+ • Tcl also provides an advanced version of REs (AREs) which further simplify string searching – See re_syntax Tcl manual page for more details (Tcl 8.2 and later) 1 or more spaces, equivalent to *) 1 or more lowercase letters (a word composed of lowercase letters) 0 or 1 space, equivalent to ( |) 0 or 1 lowercase letter 1 or more digits preceded by either a character - or optionally character +, i.e. an INTEGER
  • 154. 8.10 Copyright © 2024 Abdelazeem Tcl Training Regular Expressions (tre1) 8.10 Searching for Strings within Strings • REs can easily locate a sub-pattern within a pattern – Use RE sub-expressions for sub-string matching • Example: extract VHDL entity name entity add is ... end add; ... regexp -nocase -- { *entity +([a-z][a-z0-9_]*) +is *} $add e_line e_name puts "$e_name" ... regexp -nocase -- { *entity +([a-z][a-z0-9_]*) +is *} $add e_line e_name puts "$e_name" file: examples/find_entity_name.tcl % source find_entity_name.tcl add % source find_entity_name.tcl add file: examples/adder.vhdl holds the 1st matched sub-string holds the entire matched string a sub-expression is enclosed within ()
  • 155. 8.11 Copyright © 2024 Abdelazeem Tcl Training Regular Expressions (tre1) 8.11 Example: Extracting VHDL Port Direction entity add is port ( cin : in std_logic; a : in std_logic_vector(7 downto 0); b : in std_logic_vector(7 downto 0); y : out std_logic_vector(7 downto 0); cout: out std_logic ); end add; ... file: examples/adder.vhdl ... regexp -nocase -- { *([a-z][a-z0-9_]*) +: +([a-z]+)[^;]*;} $add p_line p_name p_dir puts "$p_name ($p_dir)" ... regexp -nocase -- { *([a-z][a-z0-9_]*) +: +([a-z]+)[^;]*;} $add p_line p_name p_dir puts "$p_name ($p_dir)" % source find_port_dir.tcl cin (in) % source find_port_dir.tcl cin (in) • More than one sub-pattern can be used – Add additional sub-pattern variables as necessary file: examples/find_port_dir.tcl
  • 156. 8.12 Copyright © 2024 Abdelazeem Tcl Training Regular Expressions (tre1) 8.12 Using Indices with regexp • With -indices option regexp will extract string index range instead of a string • Typical uses – Searching for an insertion position – Repetitive search – Index-based string manipulation % regexp -indices -- {[A-Z][a-z]+} "VHDL or Verilog?" idx 1 % set idx 8 14 % string range "VHDL or Verilog? [lindex $idx 0] [lindex $idx 1] Verilog % regexp -indices -- {[A-Z][a-z]+} "VHDL or Verilog?" idx 1 % set idx 8 14 % string range "VHDL or Verilog? [lindex $idx 0] [lindex $idx 1] Verilog indices or the first and the last character of the matched string
  • 157. 8.13 Copyright © 2024 Abdelazeem Tcl Training Regular Expressions (tre1) 8.13 Example: Searching for All Occurrences • Find all entity port lines – Use matched pattern indices to resize the search buffer ... set buf $add set llist "" while {[regexp -nocase -indices -- <port_RE> $buf idx]} { # store matched port line lappend llist [string range $buf [lindex $idx 0] [lindex $idx 1]] # resize the search buffer set buf [string range $buf [expr [lindex $idx 1]+1] end] } ... ... set buf $add set llist "" while {[regexp -nocase -indices -- <port_RE> $buf idx]} { # store matched port line lappend llist [string range $buf [lindex $idx 0] [lindex $idx 1]] # resize the search buffer set buf [string range $buf [expr [lindex $idx 1]+1] end] } ... file: examples/find_all_port_lines.tcl { *[a-z][a-z0-9_]* *: *(in|out) +[a-z][a-z0-9_]*(([^()]+))?} Note that since Tcl version 8.3, regexp provides the -start option, which allows to move the search pointer without the need to manipulate the search buffer as above.
  • 158. 8.14 Copyright © 2024 Abdelazeem Tcl Training Regular Expressions (tre1) 8.14 Example: Filtering Command Logs • Extract warnings from a Simplicity .srr log file ... Synthesizing work.interface.rtl @W:"c:lab6interface.vhd":82:39:82:43|Signal aver2 in the sensitivity list is not used in the process Post processing for work.interface.rtl ... file: examples/filtercore.srr proc extract_warnings {f} { set in_file [open $f r] while {[gets $in_file line] >= 0} { if {[regexp @W $line]} { regexp -nocase -- {([a-z_]+.vhd)[0-9:"|]+([a-z_. 0-9]+)} $line buf filename msg puts "$filenamett$msg" } } close $f } proc extract_warnings {f} { set in_file [open $f r] while {[gets $in_file line] >= 0} { if {[regexp @W $line]} { regexp -nocase -- {([a-z_]+.vhd)[0-9:"|]+([a-z_. 0-9]+)} $line buf filename msg puts "$filenamett$msg" } } close $f } file: examples/extract_warnings.tcl extracted output
  • 159. 8.15 Copyright © 2024 Abdelazeem Tcl Training Regular Expressions (tre1) 8.15 String Substitution • Use regsub for RE-based string substitution – regsub does not modify the input string – Returns the number of matched patterns (0 = no match) • Useful options – Use -nocase for case-insensitive search – Use -all to replace ALL matched patterns (global substitution) % regsub -- {[a-z]+} "cin : std_logic;" "carry_in" new_str 1 % set new_str carry_in : std_logic; % regsub -- {[a-z]+} "cin : std_logic;" "carry_in" new_str 1 % set new_str carry_in : std_logic; RE pattern to search for input string variable which will store the result replace the matched pattern with this regsub syntax regsub ?switches? exp string subSpec varName
  • 160. 8.16 Copyright © 2024 Abdelazeem Tcl Training Regular Expressions (tre1) 8.16 Inserting Matched Sub-Strings • regsub can re-insert the matched sub-strings – Uses special positional substitution “commands”: 0 or & insert the entire matched string 1 insert the first matched sub-string 2 insert the second matched sub-string etc. • Example: changing the bit width % regsub -- {[0-9]+ +([a-z]+) +([0-9]+)} "vector(7 downto 0)" {(n-1) 1 2} new_str 1 % set new_str vector((n-1) downto 0) % regsub -- {[0-9]+ +([a-z]+) +([0-9]+)} "vector(7 downto 0)" {(n-1) 1 2} new_str 1 % set new_str vector((n-1) downto 0) first sub-pattern = 1 second sub-pattern = 2
  • 161. 8.17 Copyright © 2024 Abdelazeem Tcl Training Regular Expressions (tre1) 8.17 Using REs for Complex Substitutions • Two-pass processing (collect & substitute) – regexp to collect the information – regsub to substitute • Consider converting all std_logic_vector(0 downto 0) signals/ports to std_logic – First we need to find all 1-bit vector signals/ports – Then substitute ports/signals: std_logic_vector(0 downto 0) to std_logic signal assignments: a(0) to a a <= (others => '0') to a <= '0' – See examples/vector_to_bit.tcl
  • 162. 8.18 Copyright © 2024 Abdelazeem Tcl Training Regular Expressions (tre1) 8.18 Quiz 8 • What is the value of new_line ? (no options, sorry!) set line "a_in: in std_logic_vector(31 downto 0);" regsub {(([0-9]+) +(.*) +([0-9]+));} $line {(3 to 1);} new_line puts $new_line set line "a_in: in std_logic_vector(31 downto 0);" regsub {(([0-9]+) +(.*) +([0-9]+));} $line {(3 to 1);} new_line puts $new_line file: examples/quiz8.tcl Answer
  • 163. 8.19 Copyright © 2024 Abdelazeem Tcl Training Regular Expressions (tre1) 8.19 LAB 4: VHDL Netlist Hacking • Write a procedure find_vector_port which will identify the FIRST bus port in the VHDL design entity – An example of a VHDL design file is in adder.vhdl • Example: % find_vector_port adder.vhdl First bus port is a % % find_vector_port adder.vhdl First bus port is a % entity add is port ( cin : in std_logic; a : in std_logic_vector(7 downto 0); b : in std_logic_vector(7 downto 0); cout: out std_logic; sum : out std_logic_vector(7 downto 0); ) end add; entity add is port ( cin : in std_logic; a_bus : in std_logic_vector(7 downto 0); b_bus : in std_logic_vector(7 downto 0); cout : out std_logic; sum_bus : out std_logic_vector(7 downto 0); ) end add; Stage 2: modify the port names
  • 164. 8.20 Copyright © 2024 Abdelazeem Tcl Training Regular Expressions (tre1) 8.20 LAB 4: VHDL Netlist Hacking (2) • Stage 1 – Open and read in the entire adder.vhdl file into a variable – Use regexp to extract the first entity port name, which is a vector • Construct a regular expression to identify the port name with the std_logic_vector type – Print the port name on the terminal • Stage 2 – Replace regexp with regsub to append _bus string to ALL vector port names and save the new adder entity into a new file – Include port indices into the port names, e.g. ain_bus_7_0 – Replace the port bus signals with a number of single-bit signals labelled with their respective indices, e.g. ain_7, ain_6, etc. – Replace ALL design bus signals (in entity and architecture) with single-bit signals (use adder_full.vhdl)
  • 165. 9.1 Copyright © 2024 Abdelazeem Tcl Training Tcl Scripting for EDA Tcl in EDA Tools
  • 166. 9.2 Copyright © 2024 Abdelazeem Tcl Training Tcl in EDA Tools (tet1) 9.2 Aims and Topics • Aim – To gain understanding about how Tcl is used in contemporary EDA tools • Topics – Where you can find Tcl interpreters in EDA tools – Typical uses of Tcl with various EDA tools
  • 167. 9.3 Copyright © 2024 Abdelazeem Tcl Training Tcl in EDA Tools (tet1) 9.3 Where is My Tcl Interpreter? • Tcl interpreter is typically embedded in your EDA tool command console (GUI or command line) HERE HERE HERE HERE HERE HERE
  • 168. 9.4 Copyright © 2024 Abdelazeem Tcl Training Tcl in EDA Tools (tet1) 9.4 Finding out More about your EDA Tool • Check the version of the Tcl interpreter • Check for EDA tool-specific commands and variables – For example MTI’s simulator-specific commands and variables start with the mti_ prefix • Examine the EDA tool-specific Tcl documentation for tool-specific Tcl functionality and data structures % info tclversion 8.0 % info patchlevel 8.0.5 % info tclversion 8.0 % info patchlevel 8.0.5 % info commands mti_* ... % info globals mti_* ... % info commands mti_* ... % info globals mti_* ... info tclversion provides an alternative way to examining the version of the Tcl interpreter. The same information can be obtained by examining global variables tcl_version and tcl_patchLevel.
  • 169. 9.5 Copyright © 2024 Abdelazeem Tcl Training Tcl in EDA Tools (tet1) 9.5 Examples of Tcl-based EDA Tools • HDL simulation – MTI/Mentor Graphics ModelSim – ... • HDL synthesis – Synopsys Design Compiler (dc_shell-t) – Exemplar Logic LeonardoSpectrum – Cadence Ambit BuildGates – Synplify Pro – ... • Placement & routing – Altera Quatrus – ...
  • 170. 9.6 Copyright © 2024 Abdelazeem Tcl Training Tcl in EDA Tools (tet1) 9.6 LAB 5: Working with a Tcl-enabled EDA Tool • Please refer to your exercise book for your tool specific laboratories.
  • 171. 10.1 Copyright © 2024 Abdelazeem Tcl Training Next Steps Tcl Scripting for EDA
  • 172. 10.2 Copyright © 2024 Abdelazeem Tcl Training Tcl Next Steps (tns1) 10.2 What this Course Covered... • Main topics – Tcl scripting basics – Tcl data structures (strings, lists and arrays) – File I/O, multi-process communication and simple networking – Regular expressions – Building Tcl applications – EDA Tcl scripting – Appendix: • Using expect for interacting with command-line programs • Following the course... – Several months “hands-on” work to become experienced
  • 173. 10.3 Copyright © 2024 Abdelazeem Tcl Training Tcl Next Steps (tns1) 10.3 Object Orientated Programming with [incr_Tcl] Effective Tcl/Tk Programming Suggested Follow-on Training • Tcl for EDA Scripting – This course! • Building Applications with Tcl/Tk – Using Tk graphics toolkit to add complex multi- platform GUI's to Tcl scripts with the minimum of code • Effective Tcl/Tk Programming – More advanced application development using Tcl/Tk • Object Orientated Programming with [incr_Tcl] – Adding object orientated features to Tcl applications using the [incr_Tcl] extension Building Applications with Tcl/Tk Tcl for EDA Scripting 3 day workshop covering the the use of Tcl with Tk - the graphics toolkit extensions to Tcl. Tk allows the designer to add complex multi-platform Graphical User Inferfaces (GUI's) to Tcl scripts, using the minimum of code. Tk is used by many EDA companies to define their tool GUI's. Effective Tcl/Tk Programming 2 day workshop covering advanced design and coding techniques for creating complete and effective Tcl/Tk applications Object Orientated Programming with [incr_Tcl] [incr_Tcl] is the object orientated extension to Tcl. This workshop examines the features of [incr_Tcl] and shows how to take advantage of them in your applications.
  • 174. 10.4 Copyright © 2024 Abdelazeem Tcl Training Tcl Next Steps (tns1) 10.4 What About Tk ? • Tk is a simple but powerful Tool Kit for GUI programming • Supports different window systems – UNIX – Windows 95/98/NT/2000 – Macintosh • Try this: • Tk provides a set of Tcl commands to create window “widgets” $ wish % button .b -text "Hello World!" -command exit .b % pack .b -padx 4 -pady 6 % $ wish % button .b -text "Hello World!" -command exit .b % pack .b -padx 4 -pady 6 % UNIX (Solaris) Windows 2000
  • 175. 10.5 Copyright © 2024 Abdelazeem Tcl Training Tcl Next Steps (tns1) 10.5 Tcl/Tk Resources • Internet – Tcl distributions (source & binary), contributed software archive, discussion lists, books, documentation, tutorials, etc. • dev.scriptics.com (tcl.activestate.com) • cui.unige.ch/eao/www/TclTk.html • www.sco.com/Technology/tcl/Tcl.html • www.tcltk.com • www.neosoft.com/tcl • expect.nist.gov • www.tclforeda.net – newsgroup • comp.lang.tcl • Books – tcl.activestate.com/resource/doc/books There are many resources available to Tcl application developers. Some of the popular websites are listed here. Feel free to use your favourite Internet search engine to discover more. comp.lang.tcl is an on-line discussion forum for Tcl scripting related issues. If your company does not provide a news server access, you might want to use one of the public news services, e.g. try Google at http://groups.google.com/groups?group=comp.lang.tcl
  • 176. 10.6 Copyright © 2024 Abdelazeem Tcl Training
  • 177. 10.7 Copyright © 2024 Abdelazeem Tcl Training
  • 178. 10.8 Copyright © 2024 Abdelazeem Tcl Training Tcl Next Steps (tns1) 10.8 This slide is left intentionally blank.
  • 179. 11.1 Copyright © 2024 Abdelazeem Tcl Training Tcl Scripting for EDA Appendix A: From Scripts to Applications
  • 180. 11.2 Copyright © 2024 Abdelazeem Tcl Training From Scripts to Applications (tsa1) 11.2 Aims and Topics • Aim – Expand the knowledge of Tcl to enable building complex, robust and portable scripting applications • Topics – Tcl scripts versus applications – Command-line arguments & environment variables – Advanced procedures – Variable scope – Error handling – Date & time in Tcl – Scheduling and delaying command execution – Script profiling – Distributing Tcl scripts
  • 181. 11.3 Copyright © 2024 Abdelazeem Tcl Training From Scripts to Applications (tsa1) 11.3 Tcl Script versus Tcl Application • Tcl script is simply a collection of Tcl commands, which do something more or less useful • Tcl application includes one or more Tcl scripts, which can be used as a robust stand-alone application – Invoked similarly to “ordinary” programs – Handles command-line arguments – Provides access to native platform’s environment – Easily distributed and installed
  • 182. 11.4 Copyright © 2024 Abdelazeem Tcl Training From Scripts to Applications (tsa1) 11.4 • MsWindows/Macintosh Tcl Scripts – Double-click a Tcl source file to execute it • UNIX Tcl Scripts – Use the #!<pathname> to specify the full path to the interpreter... – ...or for better portability use the UNIX shell to search the $PATH #!/usr/local/bin/tclsh puts "Hello World!" #!/usr/local/bin/tclsh puts "Hello World!" #!/bin/sh # DO NOT REMOVE: exec tclsh "$0" "$@" puts "Hello World!" #!/bin/sh # DO NOT REMOVE: exec tclsh "$0" "$@" puts "Hello World!" Executing Tcl Scripts as Ordinary Programs full path to the Tcl interpreter which will execute this Tcl script full path to the UNIX shell which will invoke the Tcl interpreter on this script Tcl script starts here IMPORTATNT! (escaped newline) On Windows all .tcl files are associated with a Tcl/Tk interpreter called wish. If you want to use only the plain Tcl interpreter, you may re-define this file association using the Windows Explorer (File Manager) application.
  • 183. 11.5 Copyright © 2024 Abdelazeem Tcl Training From Scripts to Applications (tsa1) 11.5 Command-Line Arguments • Very useful for customizing Tcl script behavior from a command-line • Command-line arguments passed to Tcl scripts are stored in the following special global variables argv Tcl list of all command-line arguments argc number of command-line arguments (= llength $argv) argv0 script name • Example % tclsh examples/cmd_line_args -file mp3.vhdl -dir synth_run.12 argv = -file mp3.vhdl -dir synth_run.12 argc = 4 argv0 = examples/cmd_line_args % % tclsh examples/cmd_line_args -file mp3.vhdl -dir synth_run.12 argv = -file mp3.vhdl -dir synth_run.12 argc = 4 argv0 = examples/cmd_line_args % argv0 argv
  • 184. 11.6 Copyright © 2024 Abdelazeem Tcl Training From Scripts to Applications (tsa1) 11.6 Dealing with Platform-Specific Code • Use the global tcl_platform array to obtain information about the host platform • Typical example proc platform_details {} { global tcl_platform puts "Machine:t $tcl_platform(machine)" puts "Platform:t $tcl_platform(platform)" puts "OS:tt $tcl_platform(os) $tcl_platform(osVersion)" puts "Byte order:t $tcl_platform(byteOrder)" } proc platform_details {} { global tcl_platform puts "Machine:t $tcl_platform(machine)" puts "Platform:t $tcl_platform(platform)" puts "OS:tt $tcl_platform(os) $tcl_platform(osVersion)" puts "Byte order:t $tcl_platform(byteOrder)" } file: examples/platform_details.tcl proc edit {filename} { global tcl_platform switch $tcl_platform(platform) { windows {exec notepad.exe $filename &} unix - linux {exec nedit $filename &} } } proc edit {filename} { global tcl_platform switch $tcl_platform(platform) { windows {exec notepad.exe $filename &} unix - linux {exec nedit $filename &} } } file: examples/edit.tcl
  • 185. 11.7 Copyright © 2024 Abdelazeem Tcl Training From Scripts to Applications (tsa1) 11.7 Accessing Environment Variables • Use global env array to access system environment variables • Processes started from the current Tcl interpreter will inherit the environment variables – Tcl can be used to customise system variables for invoked external programs % set env(PATH) /usr/bin:/bin/:/usr/local/bin % set env(LM_LICENSE_FILE) /nfs/cad/mentor/licenses/license.dat % set env(PATH) /usr/bin:/bin/:/usr/local/bin % set env(LM_LICENSE_FILE) /nfs/cad/mentor/licenses/license.dat % info exists env(EDITOR) 0 % set env(EDITOR) "nedit" nedit % info exists env(EDITOR) 0 % set env(EDITOR) "nedit" nedit check for existence of an environment variable modify the value of an environment variable
  • 186. 11.8 Copyright © 2024 Abdelazeem Tcl Training From Scripts to Applications (tsa1) 11.8 Procedures Revisited • Procedures can have optional arguments – Possible to write one procedure for many uses • Using procedures with optional arguments proc print_log {{fid stdout} {prefix LOG:}} { global log foreach line $log { puts $fid "$prefix $line" } } proc print_log {{fid stdout} {prefix LOG:}} { global log foreach line $log { puts $fid "$prefix $line" } } default value for fid default value for prefix % print_log LOG: ... ... % print_log $open_fid % print_log $open_fid SYNTH: % print_log LOG: ... ... % print_log $open_fid % print_log $open_fid SYNTH: print_log can have 0, 1 or 2 arguments Use optional procedure arguments to improve Tcl code re-use, readability and maintainability.
  • 187. 11.9 Copyright © 2024 Abdelazeem Tcl Training From Scripts to Applications (tsa1) 11.9 Variable Number of Arguments • Use special argument args to absorb all argument values not matched by the preceding arguments – Useful for parsing command switches, reusing procedure code, etc. – args is an ordinary Tcl list proc print_log_args {fid args} { global log set prefix "LOG:"; set header ""; foreach {option value} $args { switch -- $option { -prefix {set prefix $value} -header {set header $value} default {puts "ERROR: Unknown option "$option"."; return;} } } if {$header != ""} {puts $fid $header} foreach line $log {puts $fid "$prefix $line"} } proc print_log_args {fid args} { global log set prefix "LOG:"; set header ""; foreach {option value} $args { switch -- $option { -prefix {set prefix $value} -header {set header $value} default {puts "ERROR: Unknown option "$option"."; return;} } } if {$header != ""} {puts $fid $header} foreach line $log {puts $fid "$prefix $line"} } file: examples/print_log.tcl args must be the LAST argument parsing command options stored in the args list default option values
  • 188. 11.10 Copyright © 2024 Abdelazeem Tcl Training From Scripts to Applications (tsa1) 11.10 Variable Number of Arguments (2) • Using print_log with variable arguments % print_log_args stdout LOG: ... ... % print_log_args stdout -prefix "PLACE & ROUTE:" PLACE & ROUTE: ... ... % print_log_args stdout -prefix "PLACE & ROUTE:" -header "Design P&R Log" Design P&R Log PLACE & ROUTE: ... ... % print_log_args stdout -bad_option Unknown option "-bad_option" % print_log_args stdout LOG: ... ... % print_log_args stdout -prefix "PLACE & ROUTE:" PLACE & ROUTE: ... ... % print_log_args stdout -prefix "PLACE & ROUTE:" -header "Design P&R Log" Design P&R Log PLACE & ROUTE: ... ... % print_log_args stdout -bad_option Unknown option "-bad_option" args (2 elements) args (4 elements) args (1 element) args (0 elements) fid
  • 189. 11.11 Copyright © 2024 Abdelazeem Tcl Training From Scripts to Applications (tsa1) 11.11 Variable Scope • global command provides access to variables at global level only • upvar command allows accessing variables at ANY level – typically used for passing variables by reference proc print_log_upvar {fid log_var args} { upvar 1 $log_var log ... foreach line $log {puts $fid "$prefix $line"} } proc print_log_upvar {fid log_var args} { upvar 1 $log_var log ... foreach line $log {puts $fid "$prefix $line"} } file: examples/print_log_upvar.tcl sets visibility level, 1 = one level UP (default) variable $log_var becomes visible via a local variable log % print_log_upvar stdout sim_log LOG: ... ... % print_log_upvar stdout sim_log LOG: ... ... variable sim_log becomes visible inside print_log_upvar
  • 190. 11.12 Copyright © 2024 Abdelazeem Tcl Training From Scripts to Applications (tsa1) 11.12 Generating Application Errors • Error messages can be generated with puts • Tcl also provides a robust error reporting mechanism using the error Tcl command errorInfo global variable which stores the stack trace after an error occurred errorCode global variable which holds the error code of the last error proc print_log_error {fid log_var args} { ... switch -- $option { -prefix {set prefix $value} -header {set header $value} default {error "ERROR: Unknown option "$option".";} } } ... } proc print_log_error {fid log_var args} { ... switch -- $option { -prefix {set prefix $value} -header {set header $value} default {error "ERROR: Unknown option "$option".";} } } ... } file: examples/print_log_error.tcl terminates immediately and returns the error message. errorInfo and errorCode variables are set appropriately
  • 191. 11.13 Copyright © 2024 Abdelazeem Tcl Training From Scripts to Applications (tsa1) 11.13 • Query the current time • Convert date strings to seconds (mm/dd/yy) • Convert seconds to date strings: Handling Date and Time % clock seconds 1004945376 % clock seconds 1004945376 time measured as seconds from fixed starting time (usually January 1, 1970) % clock scan "10/17/00" 971733600 % clock scan "10/17/00" 971733600 clock scan understands many different formats % clock format 971733600 Tue Oct 17 00:00:00 Romance Daylight Time 2000 % clock format 971733600 -format "%B %d, %Y is in week #%U" October 17, 2000 is in week #42 % clock format [clock seconds] Thu Oct 12 16:49:22 Romance Daylight Time 2000 % clock format 971733600 Tue Oct 17 00:00:00 Romance Daylight Time 2000 % clock format 971733600 -format "%B %d, %Y is in week #%U" October 17, 2000 is in week #42 % clock format [clock seconds] Thu Oct 12 16:49:22 Romance Daylight Time 2000
  • 192. 11.14 Copyright © 2024 Abdelazeem Tcl Training From Scripts to Applications (tsa1) 11.14 Inserting Delays • Use after command to insert delays or to schedule scripts for execution in the future • Typical uses – Wait for another process to complete – Periodic tasks – Simulated user input • Examples % after 1000 % after 5000 {puts "Job done."} after#1 % vwait event-loop Job done. % after 1000 % after 5000 {puts "Job done."} after#1 % vwait event-loop Job done. sleep for 1000 milliseconds, then return returns immediately, but schedules execution of a Tcl script 5000 milliseconds from now tclsh must enter the EVENT LOOP in order to execute all pending scripts
  • 193. 11.15 Copyright © 2024 Abdelazeem Tcl Training From Scripts to Applications (tsa1) 11.15 Script Performance Profiling • Use time command to evaluate the average execution time over 1 or more iterations • Typical uses – Performance profiling – Collecting timing statistics • Examples % time {my_command} 180000 microseconds per iteration % time {my_command} 100 256310 microseconds per iteration % time {my_command} 180000 microseconds per iteration % time {my_command} 100 256310 microseconds per iteration time command execution over 1 iteration (default) time command execution over 100 iterations
  • 194. 11.16 Copyright © 2024 Abdelazeem Tcl Training From Scripts to Applications (tsa1) 11.16 Tcl Application Distribution • Tcl application includes the following elements – Tcl script files – Any other files (data, setup, etc.) – Tcl interpreter (?) • Tcl application can be easily packaged with TclPro • No need to distribute the Tcl interpreter if a compatible interpreter is available on the target platform – Check the Tcl version to guard against unexpected errors if {![string match 8.* $tcl_version]} { puts "Error: incompatible Tcl version $tcl_version" exit } if {![string match 8.* $tcl_version]} { puts "Error: incompatible Tcl version $tcl_version" exit } global variable with Tcl version string (e.g. 8.0)
  • 195. 11.17 Copyright © 2024 Abdelazeem Tcl Training From Scripts to Applications (tsa1) 11.17 Tcl Packages • Rather than source-ing each script required for the application, the scripts can be put into a package – Request access to the package commands using package require • Defining packages – Insert package provide abdelazeem 1.0 in each Tcl script to become part of the abdelazeem package – Run pkg_mkIndex . *.tcl in the package directory to create the package index file (pkgIndex.tcl) – Update auto_path global variable to include the package directory 1.0 % to_bits 9 1001 % % package require Abdelazeem 1.0 % to_bits 9 1001 use to_bits from the package All Tcl scripts in the examples directory, which define procedures were included in package. For an example of the package index file, look in examples/pkgIndex.tcl
  • 196. 11.18 Copyright © 2024 Abdelazeem Tcl Training From Scripts to Applications (tsa1) 11.18 Quiz 9 • What is the number printed by puts ? (a) none (empty string) (b) 0 (c) 1 (d) 4 (e) 5 (f) this will generate a syntax error! proc cell_count {args} { return [llength $args] } set cells [list and2 or2 xor2 inv] puts "Number of cells: [cell_count $cells]" proc cell_count {args} { return [llength $args] } set cells [list and2 or2 xor2 inv] puts "Number of cells: [cell_count $cells]" file: examples/quiz9.tcl Answer
  • 197. 12.1 Copyright © 2024 Abdelazeem Tcl Training Tcl Scripting for EDA Appendix B: Binary Files and Strings
  • 198. 12.2 Copyright © 2024 Abdelazeem Tcl Training Binary Files and Strings (tbf1) 12.2 Aims and Topics • Aim – Learn about handling binary data using Tcl • Topics – Reading and writing binary files – Binary strings
  • 199. 12.3 Copyright © 2024 Abdelazeem Tcl Training Binary Files and Strings () 12.3 Reading and Writing Binary Files • When accessing binary files, the automatic end-of-line conversion must be switched off! • Use fconfigure to change properties of an open channel – Automatic end-of-line conversion – End-of-file character – Channel blocking and buffering ⇒Channel properties can be changed at ANY TIME during channel access set fid [open "bitstream.bit" r] fconfigure $fid -translation binary set bitstream [read $fid] binary scan $bitstream H* bitstream close $fid set fid [open "bitstream.bit" r] fconfigure $fid -translation binary set bitstream [read $fid] binary scan $bitstream H* bitstream close $fid change the translation mode for $fid channel to BINARY (i.e. no newline conversion) file: examples/bitstream.tcl 0 0 1 1 0 1 0 1 1 1 0 1 1 0 1 1 0 When accessing binary files in Tcl, it is important to remember to switch off the default automatic end-of-line translation.
  • 200. 12.4 Copyright © 2024 Abdelazeem Tcl Training Binary Files and Strings (tbf1) 12.4 • Binary strings can hold characters of ANY value – Similar to “normal” Tcl strings – Some string commands don’t work with binary strings – Use backslash substitution to specify binary values or ... Binary Strings % set binary_data "x03x04x05" ♥♦♣ % set binary_data "x03x04x05" ♥♦♣ output will vary depending on the terminal & platform remember me? Binary strings can be manipulated in the same way as “usual” text strings, i.e. they can be constructed using substitution or using the append command and compared using ==. However, only the following string commands are guaranteed to work with binary strings: string index, string range, string length It is therefore sometimes desirable to convert binary strings into normal Tcl strings.
  • 201. 12.5 Copyright © 2024 Abdelazeem Tcl Training Binary Files and Strings (tbf1) 12.5 Converting Binary Strings • ... use the binary Tcl command to convert binary values to/from their equivalent string representation % set binary_data [binary format H* "030405"] ♥♦♣ % binary scan "x03x04x05" H* hex_data 1 % set hex_data 030405 % set binary_data [binary format H* "030405"] ♥♦♣ % binary scan "x03x04x05" H* hex_data 1 % set hex_data 030405 string → binary conversion binary → string conversion returns the number of conversions performed hex conversion specifier (high-to-low order) binary command can be used to convert binary strings into a variety of text strings. binary format syntax: binary format formatString ?arg arg ...?
  • 202. 12.6 Copyright © 2024 Abdelazeem Tcl Training Binary Files and Strings (tbf1) 12.6 The Power of binary • binary command simplifies manipulation of binary values – Converts binary values to different ASCII formats • character, string, decimal, hexadecimal, octal, bit – Converts between different representations of binary values • little ↔ big endian • Generic to_bits (LAB 1) using binary proc to_bits {num} { binary scan [binary format I $num] B* bits return [string trimleft $bits 0] } proc to_bits {num} { binary scan [binary format I $num] B* bits return [string trimleft $bits 0] } bit conversion specifier (high-to-low order) 32-bit integer conversion specifier (big endian order) trims away unnecessary leading 0’s file: examples/to_bits.tcl binary scan syntax Use hexdump (provided in examples/hexdump.tcl) to visualize the contents of a binary string. binary scan string formatString ?varName varName ...?
  • 203. 13.1 Copyright © 2024 Abdelazeem Tcl Training Tcl Scripting for EDA Appendix C: Client-Server Applications and Networking
  • 204. 13.2 Copyright © 2024 Abdelazeem Tcl Training Client-Server Applications and Networking (tcs1) 13.2 Aims and Topics • Aim – Expand the knowledge of Tcl multi-process communication to include client-server and networking applications • Topics – Client-server applications – Safe interpreters – Simple networking
  • 205. 13.3 Copyright © 2024 Abdelazeem Tcl Training Client-Server Applications and Networking (tcs1) 13.3 Multi-Process Communication HDL Simulator HDL Simulator Hardware test rig Hardware test rig commands results % set fid [open "| test_rig" r+] file24 % fconfigure $fid -buffering line % puts $fid "test1 100" % gets $fid test1: 1000 % puts $fid "test2 200" % gets $fid test2: 400 % close $fid % set fid [open "| test_rig" r+] file24 % fconfigure $fid -buffering line % puts $fid "test1 100" % gets $fid test1: 1000 % puts $fid "test2 200" % gets $fid test2: 400 % close $fid Hardware test rig Hardware test rig read/write mode (bi-directional communication) external program (can be another Tcl script!) CLIENT SERVER IMPORTANT: set-up LINE buffering (FULL buffering is the default for files) The above is the example of SYNCHRONOUS communication, i.e. the client application always waits for the response from the server before proceeding further. Tcl can be also used to build ASYNCHRONOUS communication channels, which are typically used in servers and GUI applications.
  • 206. 13.4 Copyright © 2024 Abdelazeem Tcl Training Client-Server Applications and Networking (tcs1) 13.4 Server Application in Tcl while {[gets stdin line] >= 0} { set cmd [lindex $line 0]; set data [lindex $line 1] switch -- $cmd { test1 { # perform test1 set result [expr $data * 10] puts "test1: $result" } test2 { # perform test2 set result [expr $data * 2] puts "test2: $result" } default { puts "Error: unrecognized command" } } } while {[gets stdin line] >= 0} { set cmd [lindex $line 0]; set data [lindex $line 1] switch -- $cmd { test1 { # perform test1 set result [expr $data * 10] puts "test1: $result" } test2 { # perform test2 set result [expr $data * 2] puts "test2: $result" } default { puts "Error: unrecognized command" } } } file: examples/test_rig.tcl test1 procedure goes here test2 procedure goes here Always handle unrecognized input to avoid server locking. command-line parsing Notice that in the above example a considerable amount of Tcl code is used to parse server commands. In order to improve efficiency, it would be better to define all server commands as Tcl commands and then use Tcl parsing and error checking capabilities.
  • 207. 13.5 Copyright © 2024 Abdelazeem Tcl Training Client-Server Applications and Networking (tcs1) 13.5 Using Tcl as a Command Parser proc test1 {data} { # perform test1 set result [expr $data * 10] return "test1: $result" } proc test2 {data} { # perform test2 set result [expr $data * 2] return "test2: $result" } while {[gets stdin line] >= 0} { if {[catch $line result] != 0} { puts "Error: $result" } else { puts $result } } proc test1 {data} { # perform test1 set result [expr $data * 10] return "test1: $result" } proc test2 {data} { # perform test2 set result [expr $data * 2] return "test2: $result" } while {[gets stdin line] >= 0} { if {[catch $line result] != 0} { puts "Error: $result" } else { puts $result } } file: examples/test_rig2.tcl catch will evaluate the Tcl script in $line and store its result in result. Returns 0 on success, 1 otherwise. Use Tcl interpreter to parse commands to improve efficiency there is no need to change the server's parsing code when new commands are added catch syntax catch script ?varName?
  • 208. 13.6 Copyright © 2024 Abdelazeem Tcl Training Client-Server Applications and Networking (tcs1) 13.6 But How Safe is your Tcl Interpreter? • SAFE Tcl interpreters provide protection against harmful scripts – Create safe interpreters using the interp command CLIENT CLIENT SERVER SERVER cd ~; file delete -force . % interp create -safe safe_parser safe_parser % safe_parser eval $script ... % interp create -safe safe_parser safe_parser % safe_parser eval $script ... safe_parser Tcl interpreter safe_parser Tcl interpreter $script hides all “dangerous” commands main Tcl interpreter main Tcl interpreter interp create syntax slave eval syntax When attempting to invoke a “dangerous” Tcl command (e.g. exec, file, open) in a safe interpreter, the command is simply not recognized and the interpreter will return an error. It is always a good idea to examine Tcl scripts you receive from your friends and colleagues by running them in a safe Tcl interpreter. You can use check_script command from examples/check_script.tcl to do this for you. % source examples/check_script.tcl % check_script unknown_script.tcl invalid command name "file" % source examples/check_script.tcl % check_script unknown_script.tcl invalid command name "file" interp create ?-safe? ?--? ?path? slave eval arg ?arg?
  • 209. 13.7 Copyright © 2024 Abdelazeem Tcl Training Client-Server Applications and Networking (tcs1) 13.7 Safe Server Command Parser proc test1 {data} { ... } proc test2 {data} { ... } interp create -safe safe_parser safe_parser alias test1 test1 safe_parser alias test2 test2 while {[gets stdin line] >= 0} { if {[catch {safe_parser eval $line} result] != 0} { puts "Error: $result" } else { puts $result } } proc test1 {data} { ... } proc test2 {data} { ... } interp create -safe safe_parser safe_parser alias test1 test1 safe_parser alias test2 test2 while {[gets stdin line] >= 0} { if {[catch {safe_parser eval $line} result] != 0} { puts "Error: $result" } else { puts $result } } file: examples/test_rig_safe.tcl When receiving Tcl commands from another process or machine, always use SAFE interpreters slave alias syntax slave alias srcCmd targetCmd ?arg ...?
  • 210. 13.8 Copyright © 2024 Abdelazeem Tcl Training Client-Server Applications and Networking (tcs1) 13.8 Introduction to TCP/IP Networking 129.14.234.2 10.140.131.21 8111 8111 80 80 33 33 computer's unique IP address ports unique port number
  • 211. 13.9 Copyright © 2024 Abdelazeem Tcl Training Client-Server Applications and Networking (tcs1) 13.9 More on Networking • Port numbers – < 1024 are reserved – Other ports are available, but could be used by other applications (e.g. EDA license servers) – Port numbers between 8100-9999 are usually OK • Typical uses of Tcl networking in EDA – Remote design testing and prototyping – Co-simulation and co-prototyping – EDA tool servers, priority-based job queuing – Interaction with Web servers (with http Tcl package)
  • 212. 13.10 Copyright © 2024 Abdelazeem Tcl Training Client-Server Applications and Networking (tcs1) 13.10 Client-Server Networking in Tcl • Networking connections are similar to bi-directional pipes • Setting-up client/server networking – Use socket to create network connections (server & client) – Use fileevent to bind Tcl commands to network channel events (server & client) – Use vwait enter-mainloop to start the server (server only) socket -server server_accept 8111 set ch_id [socket $host 8111] socket -server server_accept 8111 set ch_id [socket $host 8111] fileevent $ch_id readable "server_handle $ch_id" fileevent $ch_id readable "server_handle $ch_id" vwait enter-mainloop vwait enter-mainloop SERVER: CLIENT: Tcl procedure to be invoked for each client connection hostname or IP address of the destination server port numbers Tcl procedure to be invoked each time there is something to be READ from $ch_id channel condition enter an indefinite loop (process events until the value of a non-existent variable enter-mainloop is changed) Syntax for the commands above: socket ?-sever? command ?options? port socket ?options? host port fileevent channelId readable ?script? fileevent channelId writable ?script? vwait varName
  • 213. 13.11 Copyright © 2024 Abdelazeem Tcl Training Client-Server Applications and Networking (tcs1) 13.11 Example: A Networked Server ... interp create -safe safe_parser ... proc server_accept {ch_id addr port} { fileevent $ch_id readable "server_handle $ch_id" fconfigure $ch_id -buffering line } proc server_handle {ch_id} { if {[gets $ch_id line] < 0} { close $ch_id } else { if {[catch {safe_parser eval $line} result] != 0} { puts $ch_id "Error: $result" } else { puts $ch_id $result } } } socket -server server_accept 8111 vwait enter-mainloop ... interp create -safe safe_parser ... proc server_accept {ch_id addr port} { fileevent $ch_id readable "server_handle $ch_id" fconfigure $ch_id -buffering line } proc server_handle {ch_id} { if {[gets $ch_id line] < 0} { close $ch_id } else { if {[catch {safe_parser eval $line} result] != 0} { puts $ch_id "Error: $result" } else { puts $ch_id $result } } } socket -server server_accept 8111 vwait enter-mainloop file: examples/test_rig_net.tcl enter an indefinite loop start the server to listen on port 8111 invoked each time a client connects to the server invoked when there is something to be read from the channel
  • 214. 13.12 Copyright © 2024 Abdelazeem Tcl Training Client-Server Applications and Networking (tcs1) 13.12 Tcl Shell as a Networked Client • Very similar to using bi-directional pipes • TCP/IP server can be tested using any telnet client – Easy to test & maintain – Easy to provide various server front-ends % set ch_id [socket 127.0.0.1 8111] sock148 % fconfigure $ch_id -buffering line % puts $ch_id "test1 100" % gets $ch_id test1: 1000 % puts $ch_id "test2 200" % gets $ch_id test2: 400 % set ch_id [socket 127.0.0.1 8111] sock148 % fconfigure $ch_id -buffering line % puts $ch_id "test1 100" % gets $ch_id test1: 1000 % puts $ch_id "test2 200" % gets $ch_id test2: 400 open a network connection to the server with IP address 127.0.0.1 at port number 8111
  • 215. 14.1 Copyright © 2024 Abdelazeem Tcl Training Tcl Scripting for EDA Appendix D: Interacting with Command-Line Programs
  • 216. 14.2 Copyright © 2024 Abdelazeem Tcl Training Interacting with Command-Line Programs (tep1) 14.2 Aims and Topics • Aim – To learn about using Expect for as a tool for communicating between interactive command-line programs and a Tcl interpreter • Topics – What is Expect? – Simple communication with an interactive program – Handling errors and loops – Regular expressions with Expect – Expect in EDA scripting
  • 217. 14.3 Copyright © 2024 Abdelazeem Tcl Training Interacting with Command-Line Programs (tep1) 14.3 What is the Problem? • Some useful tools exists only as interactive command-line programs – Limited command set (e.g. no loops or conditionals) – Require user input – Difficult to use for repetitive jobs • Ever tried using command-line ftp or telnet?
  • 218. 14.4 Copyright © 2024 Abdelazeem Tcl Training Interacting with Command-Line Programs (tep1) 14.4 Expect • Automates tasks normally performed through a terminal – Removes blocking and buffering problems by emulating an interactive user session • Provides Tcl scripting to non-Tcl tools – Networking, hardware testing, software and machine administration, etc. Expect Expect Tcl script
  • 219. 14.5 Copyright © 2024 Abdelazeem Tcl Training Interacting with Command-Line Programs (tep1) 14.5 Example: FTP session secret password type this type this type this expect this expect this expect this
  • 220. 14.6 Copyright © 2024 Abdelazeem Tcl Training Interacting with Command-Line Programs (tep1) 14.6 Talking to an FTP client with Expect if {[llength $argv] < 1} { puts stderr "Usage: expect any_ftp.tcl <hostname>" } set host [lindex $argv 0] exp_spawn ftp $host expect "Name" exp_send "anonymousr" expect "Password:" exp_send "secret passwordr" expect "ftp>" exp_send "cd pubr" expect "ftp>" exp_interact if {[llength $argv] < 1} { puts stderr "Usage: expect any_ftp.tcl <hostname>" } set host [lindex $argv 0] exp_spawn ftp $host expect "Name" exp_send "anonymousr" expect "Password:" exp_send "secret passwordr" expect "ftp>" exp_send "cd pubr" expect "ftp>" exp_interact file: examples/any_ftp.tcl start an ftp client, but redirect its I/O through expect use r to simulate a raw carriage return let user interact with the ftp client at this point
  • 221. 14.7 Copyright © 2024 Abdelazeem Tcl Training Interacting with Command-Line Programs (tep1) 14.7 Handling Errors ... set host [lindex $argv 0] set timeout 10 exp_spawn ftp $host expect { "Name" {exp_send "anonymousr"} "unknown host" {return 0} timeout {return 0} } ... ... set host [lindex $argv 0] set timeout 10 exp_spawn ftp $host expect { "Name" {exp_send "anonymousr"} "unknown host" {return 0} timeout {return 0} } ... file: examples/any_ftp2.tcl controls how long expect waits for a match (in seconds) if matches this... ...then do this if matches this... ...then do this no match after 10 seconds? ...then do this
  • 222. 14.8 Copyright © 2024 Abdelazeem Tcl Training Interacting with Command-Line Programs (tep1) 14.8 Example: Changing Password Remotely secret old password type this expect this expect this secret new password secret new password type this expect this expect this expect this type this type this
  • 223. 14.9 Copyright © 2024 abdelazeem Tcl Training Interacting with Command-Line Programs (tep1) 14.9 Regular Expressions in Expect proc change_remote_passwd {machine user old_pass new_pass} { ... set prompt "#|$|%|>" expect { -re $prompt {exp_send "passwdr"} timeout {return 0} } expect { "assword:" {exp_send "$old_passr"} timeout {return 0} } ... proc change_remote_passwd {machine user old_pass new_pass} { ... set prompt "#|$|%|>" expect { -re $prompt {exp_send "passwdr"} timeout {return 0} } expect { "assword:" {exp_send "$old_passr"} timeout {return 0} } ... file: examples/rpasswd.tcl matches any of these prompt characters treat $prompt as a regular expression > % $ # start up UNIX passwd program type in the old password
  • 224. 14.10 Copyright © 2024 Abdelazeem Tcl Training Interacting with Command-Line Programs (tep1) 14.10 Looping in Expect proc change_remote_passwd {machine user old_pass new_pass} { ... set times 0 expect { "new [Pp]assword:" { incr times if {$times > 2} { return 0 } exp_send "$new_passr" exp_continue } "tokens updated successfullyrn" {return 1} timeout {return 0} } } proc change_remote_passwd {machine user old_pass new_pass} { ... set times 0 expect { "new [Pp]assword:" { incr times if {$times > 2} { return 0 } exp_send "$new_passr" exp_continue } "tokens updated successfullyrn" {return 1} timeout {return 0} } } file: examples/rpasswd.tcl glob-style search pattern type in new password TWICE success! repeat the pattern search
  • 225. 14.11 Copyright © 2024 Abdelazeem Tcl Training Interacting with Command-Line Programs (tep1) 14.11 Expect in EDA Scripting • Many EDA tools and utilities are command-line driven – HDL simulation – HDL synthesis – Placement & routing – Generation & customization of IP cores – File format conversion, back-annotation, etc. – Programs for driving test beds, prototyping boards, etc. • With Expect is it easy to integrate all these tools – Integrate design & test flows – Combine EDA tools with standard OS utilities (networking, system monitoring, backup, job management, etc.)
  • 226. 14.12 Copyright © 2024 Abdelazeem Tcl Training Interacting with Command-Line Programs (tep1) 14.12 LAB 6: Interaction with a Synthesis Server • Write a procedure submit_synthesis_job which will FTP the design file design.vhdl and its synthesis script design_synthesis.tcl to a server, directory ~/incoming. • Stage 1 – Choose an FTP server on your local network to which you have access (localhost will do) and: • Create directories ~/incoming and ~/results • Start examples/synth_server on this server – Test the operation of the FTP client first by hand • Upload the design files using ftp> put design_* • Collect any useful messages you EXPECT – Write an Expect Tcl script for this job
  • 227. 14.13 Copyright © 2024 Abdelazeem Tcl Training Interacting with Command-Line Programs (tep1) 14.13 LAB 6: Interaction with a Synth. Server (2) • Stage 2 – Check in 60-second intervals whether the ~/results directory contains design_results.log. Once present, download all design_* files from the /results directory. • Check for design_results.log using ftp> get design_results.log • Use after 60000 to delay script execution for 60 seconds – After the files were received, start-up an editor with received design_results.log – Send user an e-mail message that the job was completed
  • 228. 14.14 Copyright © 2024 Abdelazeem Tcl Training Have you read "Palestine + 100: Stories from a Century after the Nakba" edited by Basma Ghalayini?
  • 229. Tcl Training i Tcl Scripting for EDA Index Note: the course is structured such that information on a particular construct is usually spread over several consecutive pages. Where this occurs, only the first page of the set is listed in this index Symbols "" quotes grouping, 2-5, 3-14 use of, 3-15 $ dollar variable substitution, 2-11 & ampersand process, 7-19 () parentheses expressions, 3-5 math functions, 3-7 regular expression, 8-8, 8-9 * asterisk regular expression, 8-5 / slash directory separator, 3-12 [] brackets command substitution, 2-16 grouping, 2-18 regular expression, 8-5 backslash b backspace, 2-14 n newline, 2-14, 7-12 regular expression, 8-9 special characters, 2-14 substitution, 2-13 {} braces grouping, 2-5, 3-14 if, 4-16 use of, 3-15 | pipe process, 7-19 regular expression, 8-8, 8-9 A after, 11-14 append, 5-4 argc, 11-5 args, 11-9, 11-10 argv, 11-5 argv0, 11-5 array, 6-17 multi-dimensional, 6-20, 6-22 versus list, 6-23 array exists, 6-21 array get, 6-19 array names, 6-21 array set, 6-19, 6-22 array size, 6-21 auto_noexec, 7-15 auto_path package, 11-17 B backslash substitution, 2-13 binary, 12-5 file, 12-3 string, 12-4 bit-wise operators, 3-5 break, 4-3, 4-14, 4-15 buffering, 7-13 process, 7-20, 13-3 C catch, 7-5, 13-5 cd, 3-12 channel buffering, 7-13 identifier, 7-4 characters special, 2-14 client-server, 13-10 clock, 11-13 close, 7-4 command
  • 230. Tcl Training ii evaluation, 2-9, 2-19, 2-20 substitution, 2-16 comparison operators, 3-5 concat, 6-8 continue, 4-3, 4-14, 4-15 D decrement, 3-8 default, 4-7 E else, 4-5, 4-6 elseif, 4-6 end of file (eof), 7-11 env, 11-7 eof, 7-11 error, 11-12 eval, 7-16, 7-17 exact lsearch, 6-12, 6-13 switch, 4-8 exec, 7-15, 7-16, 7-17 exp_interact, 14-6 exp_send, 14-6 exp_spawn, 14-6 expect, 14-4, 14-6, 14-11 loop, 14-10 regular expressions, 14-9 expr, 3-4 expression regular, 8-3 F fconfigure, 7-14, 7-20, 12-3, 13-3 file binary, 12-3 command, 7-3 descriptor, 7-4 id, 7-4 pointer, 7-7 portability, 7-12 read, 7-8, 7-10 translation, 12-3 write, 7-6 fileevent, 13-10 flush, 7-14 for, 4-3, 4-10, 4-11, 4-15 foreach, 4-3, 4-11, 4-12, 4-15 format clock, 11-13 string, 5-10 functions mathematical, 3-7 G gets, 7-8 glob, 3-12, 5-7, 7-16, 7-17 lsearch, 6-12, 6-13 switch, 4-8 global variable, 3-11, 11-11 grouping "", 2-5, 3-14 [], 2-18 {}, 2-5, 3-14 use of "" and {}, 3-15 I if, 4-3, 4-4, 4-5, 4-6, 4-15 incr, 3-8 increment, 3-8 index file package, 11-17 indices regular expression, 8-12 info, 1-11, 9-4 interp, 13-6 interpretation, 2-4, 3-13 J join, 6-11 L lappend, 6-7 lindex, 6-4 linsert, 6-9 list, 6-3, 6-6 nested, 6-5 reversal, 6-10 summary, 6-16 versus array, 6-23
  • 231. Tcl Training iii llength, 6-4 logical operators, 3-5 lrange, 6-4 lreplace, 6-9 lsearch, 6-12, 6-13 lsort, 6-14, 6-15 M mathematical functions, 3-7 operators, 3-3, 3-5 N networking, 13-8 newline, 2-14, 7-12 nonewline, 7-6 O open, 7-4, 7-19, 7-20, 13-3 operators, 3-5 bit-wise, 3-5 comparison, 3-5 logical, 3-5 mathematical, 3-3 P package, 11-17 pid, 7-19 pipe, 7-18 pipe |, 7-19 precision, 3-9 procedure, 11-8 arguments, 11-9, 11-10 procedures, 3-10 process, 7-19 communication, 7-20, 13-3 provide package, 11-17 puts, 2-5 write to file, 7-6 pwd, 3-12 R random numbers, 3-8 read, 7-10 real numbers, 3-4 redirection, 7-18 regexp, 8-6, 8-17 indices, 8-12 lsearch, 6-12, 6-13 nocase, 8-6 switch, 4-8 regsub, 8-15, 8-17 regular expression, 8-3 sub-expression, 8-10 regular expressions expect, 14-9 require package, 11-17 resources, 10-5 result, 7-5 S safe interpreter, 13-6 scan clock, 11-13 string, 5-11 script, 1-8, 1-9 scripts, 11-3 seconds, 11-13 Seek, 7-7 set, 2-7, 5-4 shift operators, 3-5 socket, 13-10 split, 6-11 stderr, 7-6 stdin, 7-6 stdout, 7-6 string, 5-3 binary, 12-4 formatting, 5-10 scanning, 5-11 string compare, 5-5, 5-9 string first, 5-12 string index, 5-12 string last, 5-12 string length, 5-12 string match, 5-6, 5-9 string range, 5-12
  • 232. Tcl Training iv string tolower, 5-8 string toupper, 5-8 string trim, 5-8 substitution, 2-9, 2-10, 2-12, 2-17 backslash, 2-13 command, 2-16 variable, 2-11 switch, 4-9 switch, 4-3, 4-7, 4-15 multiple pattern match, 4-8 options, 4-8 variable substitution, 4-9 T tcl_platform, 11-6 tcl_precision, 3-9 tcp/ip, 13-8 time, 11-15 Tk, 10-4 U unset, 2-7 upvar, 11-11 V variable, 2-7 environmental, 11-7 global, 3-11, 11-11 name, 2-8 substitution, 2-11 switch, 4-9 upvar, 11-11 value, 2-8 vwait, 11-14, 13-10 W while, 4-3, 4-13, 4-15
  • 233. Tcl Scripting for EDA TCL Lab Exercises and Case Studies
  • 234. Contents INTRODUCTION..............................................................................................................................1 Tool Specific Information...............................................................................................................................1 Conventions....................................................................................................................................................2 Icons ................................................................................................................................................................2 Overview of Labs............................................................................................................................................3 Lab Summary.................................................................................................................................................3 LAB 1 – GENERIC TCL, SYNTHESIS REPORT FILE PARSING................................................4 Looking at the script design ..........................................................................................................................5 Modifying the get_message procedure..........................................................................................................5 LAB 2 – GENERIC TCL, TEST HARNESS BUILDER ..................................................................6 Looking at the script design ..........................................................................................................................9 Adding the ‘findPorts’ procedure...................................................................................................................9 Modifying the ‘entity’ pattern .....................................................................................................................10 LAB 3 – MODELSIM DYNAMIC POWER ESTIMATION...........................................................11 Looking at the script design ........................................................................................................................14 Adding the ‘monitorSingnals’ procedure ....................................................................................................15 Optional ........................................................................................................................................................15 LAB 3 – LEONARDO MULTI-PASS SYNTHESIS .......................................................................16 Looking at the script design ........................................................................................................................20 Completing the procedures..........................................................................................................................21 LAB 4 – SYNPLIFY MULTI-PASS SYNTHESIS..........................................................................22 Looking at the script design ........................................................................................................................25 Completing the procedures..........................................................................................................................26
  • 235. TCL Scripting Lab Exercises - 1 - © Abdelazeem 2024 Revision TCL/1.0 Introduction These lab exercises are designed to make you more familiar with TCL scripting by using it in some typical EDA scripting situations. They are organized in a way that takes you step by step through what to do first, and then let you alter the code to achieve the desired functionality. Tool Specific Information The Lab exercises are designed to suit individual requirements. A number of EDA tools are proposed with corresponding Labs. You can choose which tool you want to use when you attend a TCL Workshop. Alternatively you can choose to work on one of the EDA tool-independent Labs. The later Labs will illustrate the powers of TCL for file/data processing.
  • 236. TCL Scripting Lab Exercises - 2 - © Abdelazeem 2024 Revision TCL/1.0 Conventions Certain conventions are followed in the exercises, that are worth mentioning before you start. Icons Each exercise starts on a new page and is divided into separate clear sections using icons: Goals The aims of the exercise. Scenario Explains the function of the script to be created. Background Info Discusses specific TCL language issues that you will need to understand to write the model. Recommendations Explains how to go about writing the procedures in terms of arguments, types, etc. Read these before you move on to..... Action This is what you actually do!! Two additional symbols are used within the main text, to represent: i Additional information ? A question to be answered.
  • 237. TCL Scripting Lab Exercises - 3 - © Abdelazeem 2024 Revision TCL/1.0 Overview of Labs The labs are not in any specific sequence. Choose a specific lab according to your requirements. If time permits, you are welcomed to experiment with any of the other labs presented in this lab book. The labs will involve, understanding of the supplied code and the addition of new functionalities to the existing code. The data structure as well as the subprograms’ functionality will be explained inside the ‘background info’ and ‘recommendation’ sections of each individual lab. Lab Summary Lab 1 : Generic TCL, synthesis report file parsing - an example of the use of TCL to parse a simple report file and log the error, warning and note messages. Lab 2 : Generic TCL, test harness builder - automatically creating a VHDL test harness template from a top level design. Lab 3 : ModelSim, dynamic power estimation - performing an analysis of internal signal toggle count during a simulation. Lab 4 : Leonardo Spectrum - executing a multi-pass synthesis Lab 5 : Synplify - executing a multi-pass synthesis
  • 238. TCL Scripting Lab Exercises - 4 - © Abdelazeem 2024 Revision TCL/1.0 Lab 1 – Generic TCL, synthesis report file parsing Goals The goals of the lab exercise are to familiarize yourself with a typical example file parsing and information gathering. This example uses a Synplify ‘.srr’ file however this example can be extended to any synthesis tool with a limited amount of alterations. Scenario Commonly, EDA tools generate lengthy ASCII report files summarizing their activity. Although the created reports are very thorough, the amount of information available is often overwhelming for the human eye. As a result, the user at times overlooks important messages. The proposed lab example consists in creating a procedure that will be used to extract specific information from a report file and display them on the screen. The output value is displayed on the screen (standard output). Alternatively, the output strings can be directed to a result file. standard output file_name message_type get_message
  • 239. TCL Scripting Lab Exercises - 5 - © Abdelazeem 2024 Revision TCL/1.0 Recommendations ! Data types: - message_type : (string) notes, warnings, errors - file_name : (string) filtercore.srr - standard output : (string) ! ‘Notes’ pattern sample: @N:"thresh_mux.vhd":106:15:106:26|Removed redundant assignment ! ‘Warnings’ pattern sample: @W:"nsmask.vhd":31:11:31:19|Input middle_in is unused ! ‘Errors’ pattern sample: @E:"nsmask.vhd":31:11:31:19|Expecting <= ! Procedure usage: get_message filtercore.srr warnings Action Looking at the script design ❏ Files Location: the lab files will are stored in the following directories: Workstation Users: <install_path>/tclscript/labs/generictcl PC Users: <install_path>tclscriptlabsgenerictcl Your trainer will tell you the location of the lab files installation <install_path> ❏ We will work on the file warnings_errors.tcl. Take a look at the file's contents using a text editor. Check with your instructor to see which text editors are available, or use your favorite editor. Modifying the get_message procedure ❏ Complete the ‘get_message’ procedure and test it on the ‘filtercore.srr’ synthesis report file. ❏ Add to the ‘get_message’ procedure a routine that will prevent the same message to be printed more than once.
  • 240. TCL Scripting Lab Exercises - 6 - © Abdelazeem 2024 Revision TCL/1.0 findEntity Lab 2 – Generic TCL, test harness builder Goals The goal of this exercise is to become familiar with how to create complex parsing patterns for language processing. This example uses a VHDL design as a source. Once the principles of language processing are understood, the same techniques can be used for a variety of other languages such as Verilog, EDIF, and HTML. No prior knowledge of the VHDL language is required for this lab. Scenario Hardware programming languages like VHDL or Verilog require the creation of test harnesses for the verification of specific designs. The designer usually creates those test harnesses manually. However, in most cases a large part of the creation process of a test harness can be automated by gathering information contained inside the design to be tested. The proposed lab example consists in improving an existing script to extend its semantics coverage and the creation of a procedure used to find the ports of a given design. The general structure of the script is as follows: findPorts createTb vhdlDesign buildTestBench filtercore.vhd t_filtercore.vhd status (entity) (ports) (ports) (entity) (line) (line) (line) Procedure call : Data transfer :
  • 241. TCL Scripting Lab Exercises - 7 - © Abdelazeem 2024 Revision TCL/1.0 The ‘createTb’ procedure is the top-level procedure. It implements a state machine that directs the text line ($line) read from the input file to ether the procedure ‘findEntity’ or the procedure ‘findPorts’ according to the state, the state machine is in. The variable ‘status’ is the state variable. The values held in the variable ‘status’ can be : ‘entity’ ‘ports’ ‘finish’. The procedure ‘findEntity’, searches the ‘line’ variable for the entity name of the design. Once the name has been found, it is stored in the variable ‘vhdlDesign(entity)’. The procedure ‘findPorts’ searches the line variable for ports patterns. Once ports have been identified, the procedure append the variable list ‘vhdlDesign(ports)’ with the following information: name, direction and type of the port . For more information, see the ‘Data structure’ topic in the ‘Recommendations’ section. The procedure ‘buildTestBench’ simply creates the output file from the information gathered inside the ‘vhdlDesign’ variable. You are welcomed to look at this procedure although, you will not be asked to do any work on it. Recommendations ! Data structures: The main data structure used in this script is called: ‘vhdlDesign’. This variable is used to hold the name of the entity declared in the original design file (filtercore.vhd) as well as the port details. The following diagram represents how the design information is stored inside the vhdlDesign variable. # Variable declaration global vhdlDesign set vhdlDesign(entity) {} set vhdlDesign(ports) {} # Variable assignment set vhdlDesign(entity) “decoder” lappend vhdlDesign(ports) “a in integer” lappend vhdlDesign(ports) “b out bit” entity decoder is port (a : in integer; b : out bit); end decoder; decoder a in integer (entity) (ports) vhdlDesign b out bit
  • 242. TCL Scripting Lab Exercises - 8 - © Abdelazeem 2024 Revision TCL/1.0 ! VHDL Tokens: Tokens are commonly used in scanners/parsers to facilitate the building of complex regular expressions. Here are the tokens defined for this TCL script: set separator {s} set nameIdentifier {[a-z][_a-z0-9]*} set typeIdentifier {[a-z][a-z0-9_ ]*(([a-z0-9_ ]*))*} set portMode "in|out|inout|buffer" ! VHDL Grammar: The grammar part of a scanner/parser is used to define a valid set of token sequences. This is used in regular expressions to extract specific information from code. Here are the grammar rules defined in the TCL script. set portPattern "($nameIdentifier)$separator*:$separator*! ($portMode)+$separator+($typeIdentifier)" This pattern is used to match VHDL port declarations such as : clk4 : IN STD_LOGIC; edge_fs : OUT STD_LOGIC; fs : IN STD_LOGIC; ack : OUT STD_LOGIC; enable : IN STD_LOGIC; wr_nrd : IN STD_LOGIC; edge : OUT STD_LOGIC; coef : IN bit_vector(14 downto 0) Other patterns used in this script are used to detect entity declarations such as: set entityHead "^$separator*entity$separator+! ($nameIdentifier)$separator+is" set entityEnd1 "$separator+$nameIdentifier" set entityEnd "^$separator*end($entityEnd1)?$separator*;" These patterns will respectively match the following declarations: entityHead entityEnd entity decoder is port (a : in integer; b : out bit); end decoder;
  • 243. TCL Scripting Lab Exercises - 9 - © Abdelazeem 2024 Revision TCL/1.0 Action Looking at the script design ❏ Files Location: the lab files will are stored in the following directories: Workstation Users: <install_path>/tclscript/labs/generictcl PC Users: <install_path>tclscriptlabsgenerictcl Your trainer will tell you the location of the lab files installation <install_path> ❏ We will work on the file testbench.tcl. Take a look at the file's contents using a text editor. Check with your instructor to see which text editors are available, or use your favorite editor. ❏ Familiarize yourself with the script. Before modifying the script, you can execute it to see what it does (look at the generated ‘t_filtercore.vhd’). Adding the ‘findPorts’ procedure ❏ The first part of this lab consists in adding a procedure called ‘findPorts’ that will be used to store the ports information inside the variable ‘vhdlDesign’. The following diagram represents the data flow for that function: The ‘line’ variable is passed from the procedure ‘createTb’. Its value is a text line (ASCII) extracted from input file currently processed (filtercore.vhd). findPorts vhdlDesign status (ports) (line)
  • 244. TCL Scripting Lab Exercises - 10 - © Abdelazeem 2024 Revision TCL/1.0 In this procedure you will have to process the ‘line’ to define if it is a port declaration or not. If so, you will have to store the ports information inside the variable ‘vhdlDesign’. The processing information has been described in the recommendation section. The second operation performed by the ‘findPorts’ procedure is to set the value of the ‘status’ variable to: ‘finish’ when it detects the end of the entity declaration such as: By setting the value of ‘status’ to ‘finish’, this will force the state machine implemented inside the procedure ‘createTb’ to stop. ❏ One you have made the modifications, run the script and observe the differences in the resut file ‘t_filtercore.vhd’. Modifying the ‘entity’ pattern ❏ Although the current ‘entityEnd’ pattern works with the current example, this grammar can only match two type of entity ending: ‘END;’ Or ‘END filtercore;’ The VHDL language reference manual defines that an entity ending can also be of the following form: ‘END ENTITY;’ Or ‘END ENTITY filtercore;’ ❏ Modify the ‘entityEnd’ pattern to include those two extra kinds of endings. ❏ Modify the ‘filtercore’ entity ending inside the ‘filtercore.vhd’ file to be: ‘END ENTITY;’ or END ENTITY filtercore;’ and validate your new script. ... ls : IN STD_LOGIC; reset : IN STD_LOGIC; ); END filtercore; ... ls : IN STD_LOGIC; reset : IN STD_LOGIC; ); END ENTITY filtercore; ... ls : IN STD_LOGIC; reset : IN STD_LOGIC; ); END filtercore; entityEnd portPattern
  • 245. TCL Scripting Lab Exercises - 11 - © Abdelazeem 2024 Revision TCL/1.0 Lab 3 – ModelSim Dynamic Power Estimation Goals The goal of this exercise is to become familiar with some of the features of ModelSim’s API. This example is based on a VHDL simulation; this script will be used to log signal activity during a simulation and report the results of its analysis. No prior knowledge of the VHDL language is required for this lab. Scenario A large number of current ASIC/FPGA designs require careful considerations of power consumption aspects. Although a number of specialized EDA tools are available for dynamic and static power analysis, a simple script run during simulation can already indicate what are the critical areas of a design. This estimation is based on the principles of CMOS transistors consumption. The theory tells us that CMOS based circuit only consume energy during a charge transfer; in other words during a change of state. The proposed lab example consists in creating a procedure that will be used to monitor signals activity at a given hierarchical level of the design during a simulation. Once the simulation is over the script will display the results using a graph. The procedure ‘monitorSignal’ is the top level procedure. It is called with an argument ‘hierarchy’ that indicates the hierarchy level you want to monitor inside the design. The procedure ‘monitorSignal’ will extract all the signal names contained at the specified hierarchical level using the ‘find’ API command. Once the signal names have been extracted, the procedure will create an array of counters ‘expendedList’ that will be used to record all the signals toggle activity. Lastly the procedure will set an individual ‘when’ command for each of the signals encountered at the specified hierarchical level. This ‘when command is used to record all the signals toggle activity (concurrently). The procedure ‘reportSignals’ is used to query the variable ‘expendedList’ and display the ten most toggled signals. The following diagram illustrates the script’s architecture:
  • 246. TCL Scripting Lab Exercises - 12 - © Abdelazeem 2024 Revision TCL/1.0 describe reportSignals Procedure call : Data transfer : API Procedure : monitorSignals find signalList signalType sortedList resultList expendedList API graph.tcl (hierarchy) (signal) (hierarchy) (maxValue) (mostLeast) (toggled signal) result.txt when
  • 247. TCL Scripting Lab Exercises - 13 - © Abdelazeem 2024 Revision TCL/1.0 Recommendations ! ModelSim’s API: ModelSim features a large amount of TCL API commands described in detail in the simulator’s documentation. This script will only feature a few of those to give you a feel for what you can achieve with scripting. This is the list of ModelSim commands used in this lab: - find : This command is used to find objects in the design o ‘find signal <path>/*’ will return a list of all the signals at the specified level of hierarchy. o ‘find signal –r /*’ will extract all the signals of the design, recursively. o ‘find nets –in /top/clk*’ will extract all the input signals at the ‘top’ level starting with a ‘clk’. - when : Allows to perform commands when a specific condition is met. o ‘when { result = “1100”} {puts “error”}’ prints the message ‘error’ when the value of result reaches “1100”. o ‘when {clk’event} {incr a}’ increases the value of ‘a’ when the signal ‘clk’ has had an event. - nowhen : This command disable when commands. o ‘nowhen *’ disables all whens o ‘nowhen xxx’ disable the ‘when’ labeled xxx - discribe : Displays information about a specific VHDL item. o ‘describe clk’ will return the string: Enum: ('U','X','0','1','Z','W','L','H','-') When clk is of a std_logic type. o ‘desicribe dataio’ will return : Array(15 downto 0) of Enum: ('U','X','0','1','Z','W','L','H','-') When dataio is of a std_logic_vector(15 downto 0) type; ! Data types: - signalList : (list of strings) signal names. - signalType : (string) type information of a signal (see previous section ‘describe’ command). - expendedList : (array) Signal names are used as indexes whilst the toggle amount is the value. - resultList: (list of ‘toggle value/ signal’ name pair) a list version of the values contained in the variable ‘expendedList’.
  • 248. TCL Scripting Lab Exercises - 14 - © Abdelazeem 2024 Revision TCL/1.0 - sortedList : numerically sorted version of the variable ‘resultList’. Action Looking at the script design ❏ Files Location: the lab files will are stored in the following directories: Workstation Users: <install_path>/tclscript/labs/modelsimtcl PC Users: <install_path>tclscriptlabsmodelsimtcl Your trainer will tell you the location of the lab files installation <install_path> ❏ We will work on the file signalcount.tcl. Take a look at the file's contents using a text editor. Check with your instructor to see which text editors are available, or use your favorite editor. signal a : integer := 0; signal b : std_logic := ‘0’; signal c : Boolean := false; 0 0 (a) (b) ExpendedList() 0 (c) incr expendedList(a) wait for 10 ns; a <= not a; wait; 1 0 ExpendedList() 0 (a) (b) (c) Activity on signal ‘a’ results in an increase of its toggle count. counter
  • 249. TCL Scripting Lab Exercises - 15 - © Abdelazeem 2024 Revision TCL/1.0 Adding the ‘monitorSignals’ procedure ❏ Complete the ‘monitorSignals’ procedure using the comments found inside the script file. ❏ Test the resulting script on the filtercore.srr synthesis report file. ❏ Add to the get_message procedure a routine that will prevent the same message to be printed more than once. Optional ❏ If you have some time left, try to improve the ‘monitorSignals’ procedure by checking if a signal (inside the ‘signalList’ variable) is of an array type; if so, expend the signal into individual values so that you can create individual counters for each of the bits of a vector. The following diagram explains the procedure. sig_a dataio signalList clk describe dataio Array(3 downto 0) of Enum: ('U','X','0','1','Z','W','L','H','-') 0 0 (sig_a) (dataio(0)) ExpendedList() 0 (dataio(1)) (dataio(2)) (dataio(3)) (dataio) (clk) 0 0 0 0 Added
  • 250. TCL Scripting Lab Exercises - 16 - © Abdelazeem 2024 Revision TCL/1.0 Lab 3 – Leonardo Multi-pass Synthesis Goals The goal of this exercise is to become familiar with some of the features of Leonardo’s API. This example is based on a VHDL synthesis; this script will be used to perform a multi-pass synthesis and report the results of its analysis. No prior knowledge of the VHDL language is required for this lab. Scenario Synthesis is often viewed as a simple push-button process. In most cases this approach is sufficient to achieve the required results. However when dealing with designs with tight constrains such as area or timing, synthesis becomes a more involved process. Commonly designers find themselves engaged in countless synthesis runs involving different sets of synthesis constraints. Unfortunately, due to the increasing level of complexity of synthesis algorithms, synthesis constraints combinations that used to lead to specific improvements are no longer valid. The proposed lab example consists in creating a procedure that will be used to initiate synthesis runs over a range of constraint variations. This type of script would typically run overnight since they are inherently long. Once the multi- pass synthesis is complete, the script will display the results using a graph. The following diagram illustrates the script’s architecture:
  • 251. TCL Scripting Lab Exercises - 17 - © Abdelazeem 2024 Revision TCL/1.0 compile synResult newRun config Leonardo’s variables vhdlFileList report_delay read load_library pre_optimize report_area optimize_timing delay.txt area.txt result.txt maxFreq args Procedure call : Data transfer : API Procedure : API optimize
  • 252. TCL Scripting Lab Exercises - 18 - © Abdelazeem 2024 Revision TCL/1.0 The ‘compile’ procedure is the top-level procedure. This procedure reads all the files located inside the current directory and initiate successive synthesis runs on each of those files. When calling the procedure, the user has to specify a required frequency value in MHz. Optionally, if the VHDL files require packages to be analyzed prior to synthesis, the user will specify the required files as part of the procedure’s arguments. The procedure ‘newRun’ is invoked by the procedure ‘compile’ whenever there is a new synthesis run to perform. This procedure will configure the synthesis tool’s variables from the information located inside the ‘config’ variable. Once the variable have been set-up, the procedure ‘newRun’ will call a number of Leonardo’s API functions to perform a synthesis. Finally, the procedure will browse the report files to create a concise summary file ‘result.txt’. Recommendations ! Leonardo Spectrum’s API: Leonardo Spectrum features a large amount of TCL API commands described in detail in the synthesis tool’s documentation. This script will only feature a few of those to give you a feel for what you can achieve with scripting. This is the list of Leonardo Spectrum’s commands used in this lab: - read : This command is used to analyze an HDL file o ‘read -format vhdl <file name>’ will analyze the given file and return any errors or warning related to the semantics of that file. - load_library : This command loads a pre-compiled technology library. o ‘load_library flex10’ will load the Altera Flex 10K primitive library. - pre-optimize : This procedure does a number of high level optimizations, such as: operator sharing, redundant logic removal, macros extraction. o ‘pre_optimize –common_logic –unused_logic ! –boudary –xor_comparator_optimize –extract’ will use all the pre optimization options. - optimize : Optimizes and map a design to a target technology. o ‘optimize’ will run the optimization process, using the constraint information located inside the synthesis tool’s global variables (see Leonardo’s global variables). - optimize_timing : Performs critical path optimization on the design.
  • 253. TCL Scripting Lab Exercises - 19 - © Abdelazeem 2024 Revision TCL/1.0 o ‘optimize_timing’: Optimize the critical paths using the timing constraints found in Leonardo’s global variables (see Leonardo’s global variables). - report_delay : Writes out a report file containing timing information. - report_area : Writes out a report file containing area information. ! Leonardo Spectrum’s global variables: Leonardo Spectrum features a large amount of variables used to configure the synthesis engine. This script will only feature a few of those. This is the list of Leonardo Spectrum’s global variables used in this lab: - output_file : This variable indicates the name of the resulting netlist. o ‘set output_file decode.edf’ will assign the name ‘decode.edf’ to the resulting netlist. - part : This variable indicates the part name in the chosen target family. o ‘set part EPF10K30RC208’ will set the part to the specified value. - process : This indicates the grade of the device. o ‘set process 3’ will set the process to 3 - register2register : This variable indicates the delay requirement (ns) between registers inside your design. o ‘set register2register 25’ will force Leonardo Spectrum to try to meet a 25 ns delay between any register in the design. - input2register : This variable indicates the delay requirement (ns) between any input and register inside your design. o ‘set input2register 25’ will force Leonardo Spectrum to try to meet a 25 ns delay between any input and register in the design. - output2register : This variable indicates the delay requirement (ns) between any output and register inside your design. o ‘set output2register 25’ will force Leonardo Spectrum to try to meet a 25 ns delay between any output and register in the design. - resource_sharing : This indicate if the synthesis tool tries to resource share operators or not. o ‘set resource_sharing TRUE’ will force Leonardo Spectrum to try to implement resource sharing.
  • 254. TCL Scripting Lab Exercises - 20 - © Abdelazeem 2024 Revision TCL/1.0 - encoding : This variable is used to set the encoding style of state machines. o ‘set encoding Binary’ will force Leonardo Spectrum to use the binary style for the state machines contained inside the current design. If you require more information about specific variables, you can type the command ‘help –v’ inside the Leonardo Spectrum’s console window. ! Data types: - config : (array) Constraint names are used as indexes. - vhdlFileList : (list of stings) List of all the vhdl files contained inside the current directory. Action Looking at the script design ❏ Files Location: the lab files will are stored in the following directories: Workstation Users: <install_path>/tclscript/labs/leonardotcl PC Users: <install_path>tclscriptlabsleonardotcl Your trainer will tell you the location of the lab files installation <install_path> 100 100 (register2register) (input2register) config() 100 TRUE Binary (output2register) (resource_sharing) (encoding) nano seconds
  • 255. TCL Scripting Lab Exercises - 21 - © Abdelazeem 2024 Revision TCL/1.0 ❏ We will work on the file complile.tcl. Take a look at the file's contents using a text editor. Check with your instructor to see which text editors are available, or use your favorite editor. Completing the procedures ❏ Complete the procedures using the comments found inside the script file. ❏ Test the resulting script on the vhdl files found in the lab directory. This can be achieved by typing the following commands in Leonardo Spectrum. cd <install_path>/tclscript/labs/leonardotcl source compile.tcl compile 40 mask_types.vhd
  • 256. TCL Scripting Lab Exercises - 22 - © Abdelazeem 2024 Revision TCL/1.0 Lab 4 – Synplify Multi-pass Synthesis Goals The goal of this exercise is to become familiar with some of the features of Synplify’s API. This example is based on a VHDL synthesis; this script will be used to perform a multi-pass synthesis and report the results of its analysis. No prior knowledge of the VHDL language is required for this lab. Scenario Synthesis is often viewed as a simple push-button process. In most cases this approach is sufficient to achieve the required results. However when dealing with designs with tight constrains such as area or timing, synthesis become a more involved process. Commonly designers find themselves engaged in countless synthesis runs involving different sets of synthesis constraints. Unfortunately, due to the increasing level of complexity of synthesis algorithms, synthesis constraints combinations that used to lead to specific improvements are no longer valid. The proposed lab example consists in creating a procedure that will be used to initiate synthesis runs over a range of constraint variations. This type of script would typically run overnight since they are inherently long. Once the multi- pass synthesis is complete, the script will display the results using a graph. The following diagram illustrates the script’s architecture:
  • 257. TCL Scripting Lab Exercises - 23 - © Abdelazeem 2024 Revision TCL/1.0 compile newRun vhdlFileList add_file set_option result.txt <name>.srr maxFreq args Procedure call : Data transfer : API Procedure : API project config
  • 258. TCL Scripting Lab Exercises - 24 - © Abdelazeem 2024 Revision TCL/1.0 The ‘compile’ procedure is the top-level procedure. This procedure reads all the files located inside the current directory and initiate successive synthesis runs on each of those files. When calling the procedure, the user has to specify a required frequency value in MHz. Optionally, if the VHDL files require packages to be analyzed prior to synthesis, the user will specify the required files as part of the procedure’s arguments. The procedure ‘newRun’ is invoked by the procedure ‘compile’ whenever there is a new synthesis run to perform. This procedure will configure the synthesis tool’s variables from the information located inside the ‘config’ variable. Once the variable has been set-up, the procedure ‘newRun’ will call a Synplify API functions to perform a synthesis. Finally, the procedure will browse the report files to create a concise summary file ‘result.txt’. Recommendations ! Synplify’s API: Synplify features a large amount of TCL API commands described in detail in the synthesis tool’s documentation. This script will only feature a few of those to give you a feel for what you can achieve with scripting. This is the list of Synplify ’s commands used in this lab: - project : This command is used by Synplify for a number of applications. In this script, ‘project’ is used to set-up a new project, specify a log file and run the synthesis engine. o ‘project -new’ will initialize the synthesis tool and prepare a new project. o ‘project –log_file <name>.srr’ will specify the name of the log file to be generated after synthesis. o ‘project –run synthesis’ will initiate a synthesis run. - add_file : This command is used to analyze an HDL file. o ‘add_file –vhdl decode.vhd’ will compile the decode.vhd file. - set_option : This procedure is used to set the design constraints as well as synthesis options. o ‘set_option –technology FLEX10K’ will select the Altera FLEX technology. o ‘set_option –part EFP10K30’ will specify the part to be used within the Altera FLEX family o ‘set_option frequency 40’ will specify the required frequency for the current design (in MHz). o ‘set_option resource_sharing 1’will indicate to the synthesis engine to try to resource share logic. o ‘set_option symbolic_fsm_compiler 1’ will to the synthesis engine to use dedicated algorithms for state machine optimization.
  • 259. TCL Scripting Lab Exercises - 25 - © Abdelazeem 2024 Revision TCL/1.0 o ‘set_option default_enum_encoding sequential’ will indicate Synplify to use a sequential (binary) encoding style for the state machines inside the current design. Alternatively, the user can specify ‘onehot’ for a one-hot coding style. ! Data types: - config : (array) Constraint names are used as indexes. - vhdlFileList : (list of stings) List of all the vhdl files contained inside the current directory. Action Looking at the script design ❏ Files Location: the lab files will are stored in the following directories: Workstation Users: <install_path>/tclscript/labs/Synplifytcl PC Users: <install_path>tclscriptlabsSynplifytcl Your trainer will tell you the location of the lab files installation <install_path> ❏ We will work on the file complile.tcl. Take a look at the file's contents using a text editor. Check with your instructor to see which text editors are available, or use your favorite editor. sequential 0 (default_enum_encoding) (symbolic_fsm_compiler) config() 0 0 (resource_sharing) (frequency)
  • 260. TCL Scripting Lab Exercises - 26 - © 2024 Abdelazeem Revision TCL/1.0 Completing the procedures ❏ Complete the procedures using the comments found inside the script file. ❏ Test the resulting script on the vhdl files found in the lab directory. This can be achieved by performing the following steps. Click on: run > run script Select: compile.tcl