Top Banner
Basic Tcl Training Based on Verdi/Siloti 2011.07 Allen Shieh
73
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: TCL Training Verdi 201107

Basic Tcl Training

Based on Verdi/Siloti 2011.07

Allen Shieh

Page 2: TCL Training Verdi 201107

SpringSoft Notifications

Copyright© 2011 SpringSoft, Inc. All rights reserved. No part of this training may be reproduced in any form or by any means without written permission of SpringSoft, Inc.

TrademarksThe product names used in this document are the trademarks or registered trademarks of their respective owners.

ConfidentialityThe information in this document is confidential and is covered by a license agreement between SpringSoft and your organization. Distribution and disclosure are restricted.

2

Page 3: TCL Training Verdi 201107

Overview

Tcl IntroductionBasic Tcl Syntax• Lab 1

Basic Tcl Data Types• Lab 2

Control Tcl Programs• Lab 3

Use Tcl in VerdiCase Study – 1Case Study – 2Lab 4Resource

Page 4: TCL Training Verdi 201107

Tcl Introduction

What is Tcl?• Tcl stands for Tool Command Language• A “String” basis scripting language• Use source your_script.tcl to execute your Tcl script under tclsh

What is Tk?• Tk is an associated toolkit to create window-based interactive

applications using Tcl

Basic Introduction

Page 5: TCL Training Verdi 201107

Use Tcl to combine Verdi commands to make your own feature to improve efficiency

Add your new feature, which was created by Tcl scripts, to the Verdi menu command or bind-key

Use NPI (Novas Programming Interface) to traverse the design without Verdi GUI

Tcl IntroductionWhat Can You Do in Verdi with Tcl?

Page 6: TCL Training Verdi 201107

Application of FSDB• Calculate FSDB results. For example, duty cycles• Search and sort FSDB results. For example, search for small pulses

Interoperability with 3rd party tools• Read 3rd party tool reports and translate into Verdi’s format

Application of KDB• Access to Verdi database to do calculations and queries. For example,

extract snake path from the design

Tcl IntroductionPossible Applications in Verdi with Tcl

Page 7: TCL Training Verdi 201107

Verdi provides Tcl commands for each action in the GUI.All Tcl commands are categorized by module and have a set prefix.

Tcl IntroductionTcl Command Sets in Verdi

Prefix Modulesys Systemdeb Debussy (Verdi)src nTracewv nWavesch nSchematfg Temporal Flow ViewnMem Memory/MDAfsm nStatereg nRegistereco nECOta Transactionsid Silotilx ListX

Page 8: TCL Training Verdi 201107

Tcl is a Unix shell language, and it can be executed under /usr/local/bin/tclsh

• Add #!/usr/local/bin/tclsh in the first line of your Tcl script• Execute your Tcl script in the prompt• Example: hello.tcl

Tcl IntroductionExecute Tcl in Prompt

#!/usr/bin/tclshputs “Hello!!”

In terminal

>chmod +x hello.tcl>hello.tclHello!!

Page 9: TCL Training Verdi 201107

Tcl is a combination of commands

enter and semicolon (;) needs to be used to separate different commands

If the next line is an extension of previous line, a backslash (\) needs to be added in the end of the line

If a line begins with #, the line will be treated as a comment; Tcl will ignore this line

Use spaces to separate arguments in a command • The first word in a command line is the command, following are

arguments • The command line will return string

Basic Tcl SyntaxBasic Syntax

Page 10: TCL Training Verdi 201107

Some examples for basic syntax:• set a 22 set value of variable to 22

• It is not necessary to declare a in advance, the variable in Tcl will be declared automatically after you assign a value to it.

• unset a to erase variable a

• set x 4; set y “Hello” use semicolon (;) to separate two commands

• set text “This line is \ use backslash to connect to next linesplit into two lines”

NOTE: “space” cannot be added after the backslash (this is a common error)

• #This line is comment create a comment; Tcl will not execute this line

Some Examples

Basic Tcl Syntax

Page 11: TCL Training Verdi 201107

Syntax: $varName or ${varName}• Use dollar sign $ to get the variable value• Use curly brackets { } to separate the variable and following words• The variable can be formed by letter, number, and underscore• Examples:

• set b 66 66• set a b b• set a $b 66• set a $b+$b+$b 66+66+66• set a $b.3 66.3• set w ${a}fix 66.3fix

• To keep the dollar sign $, add the backslash \ in front of $• set a \$b $b

• NOTE: Use info exist a to check whether variable a exists. If it exists, then 1 will be returned; otherwise, 0 will be returned.

Basic Tcl SyntaxUse Variables

Page 12: TCL Training Verdi 201107

Syntax: [script]• Will execute the command inside the square bracket [ ], and

return the value• Examples:

• set b 8 8• set a [expr $b+2] 10• set a “b+2 = [expr $b+2]” b+2 = 10

• To keep the square bracket [ ], add the backslash \ in front of [ ]• set a \[expr\] [expr]

Basic Tcl SyntaxSquare Brackets [ ]

Page 13: TCL Training Verdi 201107

Syntax: {script}• The use of curly brace { } is similar to the double quotation mark “ “;

the purpose is for grouping. However, the curly brace { } will ignore all replacements and calculations, all items inside the curly brace will be treated as a string.

• Example:• set b 8 8• set a {[expr $b+2]} [expr $b+2]• set a [expr $b+2] 10• set a “b+2 = [expr $b+2]” b+2 = 10• set w ${b}fix 8fix

• NOTE: A common error is that a space is not inserted between “}”and “{”.

• For example if { $x<1 }{ puts “X=$x”} will cause a syntax error

Basic Tcl SyntaxCurly Brace { }

Page 14: TCL Training Verdi 201107

Tcl will add the double quotation mark “” automatically when analyzing arguments

• C: x = 4; y = x+10 y 14• Tcl: set x 4; set y x+10 y “x+10”

The double quotation mark can avoid the effect of the semicolon “;”(will be treated as a string), but all replacements and calculations will be executed• set a “x is $x; y is $y” x is 4; y is x+10

When the curly brace { } is inside the double quotation mark “”, the item inside the curly bracket will be calculated

• Originally the items inside the curly brace { } will not be replaced and calculated

• Example: • set x CurlyBraces• set a “x is {$x}” x is {CurlyBraces}

Basic Tcl SyntaxDouble Quotation Marks “ "

Page 15: TCL Training Verdi 201107

Syntax: expr function• The expr will replace and calculate all expressions in the function

and return the result• Example:

• set b 5; set a 8 5 8• expr ($b*4) – 3 17• expr $a * cos(2*$b) -6.71257

• Error prone examples:• expr 122/10 12 (an integer divided by an integer)• expr 122.0/10.0 12.2• expr (122*1.0)/10.0 12.2

• expr will adjust the data type automatically based on the value in the expression

• The value after the decimal point will be rounded down if you use integers in an expression

Basic Tcl Syntaxexpr

Page 16: TCL Training Verdi 201107

The built-in variable tcl_precision can be set to control the precision of the calculation result by expr

• Examples:• expr 1/3 0• expr 1.0/3.0 0.333333• set tcl_precision 10 10• expr 1.0/3.0 0.3333333333• set tcl_precision 3 3• expr 1.0/3.0 0.333

• NOTE: The value for tcl_precision means the total digit number (not including the decimal point and the first zero). For example, 333.333 is 6, 0.333 is 3.

Basic Tcl Syntaxexpr

Page 17: TCL Training Verdi 201107

Syntax: incr variable increment• The incr is equivalent to command:

set variable [expr $variable + increment]

• If increment is not specified, the default value is 1.• Examples:

• set a 3 3• incr a 4• incr a 6 10• incr a -2 8

Basic Tcl Syntaxincr

Page 18: TCL Training Verdi 201107

The value of integers are all in base-10 number system (decimal)• If the first digit is 0, then it becomes base-8 number system (octal)• If the first digit is 0x, then it becomes base-16 number system

(hexadecimal)• Examples:

• expr 243 243• expr 0363 243• expr 0xF3 243

A real number can also be presented in following ways:• 5.5

• 3.7e+6• 6E4• 3.

Basic Tcl SyntaxRadix

Page 19: TCL Training Verdi 201107

Syntax:proc Name {argument1 argument2 …} {

TCL command body}

• The return value will be the result of the last command in this procedure

• If use return command then you can return your expected result• Example:

proc sum { A B } {set r [ expr $A+$B ]return $r

}

• Execute above procedure, and invoke from following command:• set result [sum 1 2]

• The return value will be 3

NOTE: A procedure cannot be included by another procedure.

Basic Tcl SyntaxBasic Execution Unit: Procedure

Page 20: TCL Training Verdi 201107

Lab 1

1. set a 10 → 10 (Create variable a and assign value 10)2. set b 22; set c 8 → 8 (Use “;” to write two commands in a line)3. set a → 10 (Get the value of variable a)4. echo $a → 10 (To invoke variable a) 5. puts $a → 10 (Print out variable a to terminal)6. puts “$a $b $c” → 10 22 8 (Print out variable a, b, c to terminal) 7. puts {$a $b $c} → $a $b $c (Notice the usage of { and })8. puts “{$a $b $c}” → {10 22 8} ({ } will take no effect inside “”)9. expr $a+$b+c → 40 (Use expr command to do calculation)10. set d [expr $a+$b+$c] → 40 (Save the expression result to $d)11. set e $a+$b+$c → 10+22+8 (Will not be calculated without expr)12. set aa $d → 40 (Assign the value of $d to variable aa)13. set bb \$d → $d (”\” to reserve special character)

Practice with Basic Syntax

Page 21: TCL Training Verdi 201107

14. expr 10/3 → 3 (Result will be interger)15. expr 10.0/3 → 3.333333333333 (Result will be

floating number, since 10.0 is floating number )16. set tcl_precision 8 → 8 (Set precision to 8, default is 12)17. expr 10.0/3 → 3.3333333 (The valid digit number

is 8, not including the decimal point )18. expr 1.0/3 → 0.33333333 (The valid digit number

is 8, not including the decimal point and the first integer zero)19. set k 0; incr k → 1 (Equal to set k [expr $k+1],

notice that the variable for incr does not need $)20. incr k 4 → 5 (Equal to set k [expr $k+4] )

Lab 1Practice with Basic Syntax

Page 22: TCL Training Verdi 201107

Basic Tcl Data Types

What is a List? • A collection of words enclosed within curly braces and separated

by whitespace characters (one or more blanks), tabs, or newline characters

• NOTE: The double quotation mark can also be used to define a List, but the replacement and calculations will be executed inside thedouble quotation marks.

• Example:• set month {January February March April}• set color “red green blue”

• The curly brace can be used to group items in the List, for example:• a b {c d e} f (4 words)• {a b} { b {c d } } e {f g} H (5 words)• “ a b { c d e } f g {h I }” (6 words)

NOTE: The index in a List is starts from 0.

Working with Lists

Page 23: TCL Training Verdi 201107

list: Create a list • Syntax: list argument1 argument2 …• Example:

• list a b {c d e} {f {g h}} a b {c d e} {f {g h}}• set a [list a b c] a b c

lindex: Retrieve an element from a list• Syntax: lindex list index• Example:

• lindex “a b c” 0 a

lrange: Return one or more adjacent elements from a list• Syntax: lrange list first last• Example:

• lrange “a b c d” 2 end c d• set list {t p t s 1}• set y [lrange $list 1 2] p t

Basic Tcl Data TypesWorking with Lists – Frequently Used Commands

Page 24: TCL Training Verdi 201107

lappend: Append list elements onto a variable • Syntax: lappend varName value1 value2 …• Example:

• set CellList “INV” “INV”• lappend CellList AND2 NOR2 “INV AND2 NOR2”• lappend CellList “AND2 NOR2” “INV {AND2 NOR2}”

linsert: Insert elements into a list • Syntax: linsert list index element1 element2 ...• Example:

• linsert “a d” 1 b c “a b c d”• linsert “a d” 1 “b c” “a {b c} d”

Basic Tcl Data TypesWorking with Lists – Frequently Used Commands

Page 25: TCL Training Verdi 201107

lsort: Sort the elements of a list • Syntax: lsort options list• options: -ascii -dictionary -integer -real -command -increasing

-decreasing -indices -index -stride -nocase -unique• Refer to Tcl Manual for detailed usage of above options

• Examples:• Sorting a list using ASCII sorting: lsort {a10 B2 b1 a1 a2} B2 a1 a10 a2 b1

• Sorting a list using Dictionary sorting: lsort -dictionary {a10 B2 b1 a1 a2} a1 a2 a10 b1 B2

• Stripping duplicate values using sorting: lsort -unique {a b c a b c a b c} a b c

• Sorting with index list:lsort -integer -index 1 \{{First 24} {Second 18} {Third 30}}

{Second 18} {First 24} {Third 30}

Basic Tcl Data TypesWorking with Lists – Frequently Used Commands

Page 26: TCL Training Verdi 201107

lreplace: Replace elements in a list with new elements • Syntax: lreplace list first last element1 element2 ...• Example:

• lreplace {a b c d} 1 2 Z Y X a Z Y X d• lreplace {a b c d} 1 2 a d

llength: Count the number of elements in a list• Syntax: llength list• Example:

• llength {a b c d} 4

lsearch: See if a list contains a particular element, and return the index number. Returns -1 if no matching element.

• Syntax: lsearch options list pattern• Refer to Tcl Manual for detailed usage of options

• Example:• lsearch –exact {a b c d} c 2

Basic Tcl Data TypesWorking with Lists – Frequently Used Commands

Page 27: TCL Training Verdi 201107

split: Split a list into a proper Tcl list • Syntax: split string splitChars• Example:

• set y /u/home/tcl/lists.tcl• split $y / {} u home tcl lists.tcl• split abcdef “” a b c d e f

join: Create a string by joining together list elements• Syntax: join list joinString• Example:

• set x {5 12 7}• expr [join $x +] 24 ( expr 5+12+7 )

concate: Join lists together (will expand one level)• Syntax: concate argument1 arguments …• Example:

• concat {a b c} {d e} f {g h} { {i j} k}a b c d e f g h {i j} k

Basic Tcl Data TypesWorking with Lists – Frequently Used Commands

Page 28: TCL Training Verdi 201107

Tcl supports associative arrays (also known as "hash tables") in which the index value is a string

• The array is a better choice than the list when representing some complex data structures

The syntax of setting arrays:• set arrName(index) value• set arrName(i,j) value• NOTE: The index can be an integer or string.

Example to set an array:• set name(first) “Allen“ Allen• set name(last) “Rita“ Rita• puts "Full name: $name(first) $name(last)“

Full name: Allen Rita

Basic Tcl Data TypesWorking with Arrays

Page 29: TCL Training Verdi 201107

array: Manipulate array variables • Syntax: array option arrayName arg1 arg2 ...• Frequently used options:

• array exists arrayName: Returns 1 if arrayName is an array variable, 0 if there is no variable by that name or if it is a scalar variable

• array get arrayName pattern: Get the index which matches the specified pattern and return index value• array get name fi* first Allen• array get name last Rita first Allen

• array set arrayName list: Convert list to array. list must have a form like that returned by array get, consisting of an even number of elements • array set colorcount {red 1 green 5 blue 4 white 9}• array get colorcount blue 4 white 9 green 5 red 1

• array size arrayName: Returns a decimal string giving the number of elements in the array. If arrayName is not the name of an array then 0 is returned • array size colorcount 4

Basic Tcl Data TypesWorking with Arrays – Commands to Manipulate Arrays

Page 30: TCL Training Verdi 201107

String is a basic data type in Tcl• Frequently used commands for manipulating strings are: string,

append, format, and scan.

string: Manipulate strings• Syntax: string option arg1 arg2 ...• To set a string:

• set string_verdi “Verdi Tcl” Verdi Tcl

• To calculate the length of a string:• string length $string_verdi 9

• To convert the string to upper case or lower case (upper: toupper; lower: tolower)• string toupper $string_verdi VERDI TCL

• To compare whether two strings are the same:• string equal $string_verdi $string_verdi 1• string equal abc def 0

Basic Tcl Data TypesWorking with Strings – “string” Command

Page 31: TCL Training Verdi 201107

Note for string comparison:• If you want to compare “strings”, use string equal or string

compare instead of using “==“. For example:if {[string compare $s1 $s2] == 0} {

# s1 and s2 are equal}if {[string equal $s1 $s2]} {

# s1 and s2 are equal}

Do not use “==” to compare strings. In example below, although the two strings have different content, they will be treated thesame with “==“. Tcl will convert the string to numbers first, so that the hexadecimal (base-16) 0xa will be converted to decimal 10 –this is not our expectation for comparing “strings”

if { “0xa” == “10”} { puts “Correct” }

Basic Tcl Data TypesWorking with Strings – “string” Command

Page 32: TCL Training Verdi 201107

More options for string command:• To trim the leading and trailing characters (if no character is specified,

white space will be removed):• set v_string "Verdi is Verdi” Verdi is Verdi• string trim $v_string Verdi is

• Trim the leading characters:• string trimleft $v_string Verdi is Verdi

• Trim the trailing characters:• string trimright $v_string Verdi Verdi is

• Return a range of a string:• string range $v_string 0 6 Verdi i

• Judge the type of string content:• string is integer $v_string 0• string is ascii $v_string 1• Refer to Tcl manual for more types

Basic Tcl Data TypesWorking with Strings – “string” Command

Page 33: TCL Training Verdi 201107

Syntax: string match -nocase pattern string• See if pattern matches string; return 1 if it does, 0 if it does not

• set str “ControlInformation“• string match Control* $str 1

To describe a pattern:• * : Matches any sequence of characters in string, including a null string

• string match tcl* tcltk 1• string match tcl* allen 0

• ?: Matches any single character in string• string match all?? allen 1 • string match all? allenshieh 0

Basic Tcl Data TypesWorking with Strings – String Match (1/2)

Page 34: TCL Training Verdi 201107

• [chars]: Matches any character in the set given by chars. [abc]matches any single character in abc; [a-z] matches any single character in lowercase; [a-e] matches any of a, b, c, d, and e.• string match {[a-z]} allen 0 • string match {[a-z][a-z][a-z][a-z][a-z]} allen 1

• \x: Matches the single character x. This provides a way of avoiding the special interpretation of the characters * ? [ ] \ in pattern. • set a “a?bc”; • string match {[a-c][a-c][a-c][a-c]} $a 0• string match {[a-c][\?][a-c][a-c]} $a 1

Basic Tcl Data TypesWorking with Strings – String Match (2/2)

Page 35: TCL Training Verdi 201107

format: Format a string in the style of sprintf• Syntax: format formatString arg1 arg2 ...• Example:

• set pi [expr 2*asin(1.0)]3.14159265359

• puts [format “Value: %s = %07.3f” “PI” $pi]Value: PI = 003.142

• %s : No conversion; just insert string • %07.3f : Convert number to signed decimal string of the form xx.yyy,

where 7 means the digit of floating decimal number (the floating point is also one digit), 3 means the precision after floating point, 0 means to fill 0 for the blank.

Basic Tcl Data TypesWorking with Strings – “format” Command

Page 36: TCL Training Verdi 201107

scan: Parse string using conversion specifiers in the style of scanf• Syntax: scan string format varName1 varName2 ...

• The scan command will search the string based on the defined format, and then save the matched string to variables sequentially

• Example:• set str “AreaUsagePattern = T3T57”• scan $str “%s %s %s” key eq value• set Key AreaUsagePattern• set eq =• set value T3T57

Basic Tcl Data TypesWorking with Strings – “scan” Command

Page 37: TCL Training Verdi 201107

Lab 2

1. set traffic1 “red green yellow” red green yellow2. set traffic2 [list red green yellow] red green yellow3. set traffic3 “red {green1 green2} yellow” red {green1 green2} yellow4. lindex $traffic1 0 red (Notice the index starts

from 0)5. lindex $traffic1 1 green6. lindex $traffic1 end yellow (Get the last item)7. lindex $traffic3 1 green1 green28. lappend traffic1 blue red green yellow blue

(Append blue into list traffic1, notice here the traffic1 does not need $)9. lrange $traffic1 1 2 green yellow (Get 1~2 range)10. linsert $traffic1 2 “pink white” red green {pink white} yellow blue

(Notice that linsert will not put the value to $traffic1, so the traffic1 will still be red green yellow blue)

11. lsort –ascii –decreasing $traffic1 yellow red green blue12. lsearch –regexp $traffic1 .*ee.+ 1 (Find green and return the

index 1)13. set str happy; split $str “” h a p p y (Separate words)14. set str “h a p p y”; join $str “” happy (Combine words)

Practice for basic data types

Page 38: TCL Training Verdi 201107

if: Execute scripts conditionally • Syntax: if condition then body1 else body2…

• Where the value of condition must be a Boolean expression • If the condition is true then execute body1, if the condition is false then

execute boody2• Example:

set A 10set B 5if {$A >= $B } {

puts “A >= B”} else {

puts “A < B”}

Control Tcl Programs“if” Command (1/3)

A >= B

Page 39: TCL Training Verdi 201107

Control Tcl Programs“if” Command (2/3)

Note the location of the Curly Brace { }

wrong

If { …. }

{

………..

}

wrong

If { ….. } {

……….

}

else { …..}

Correct

If { …. } {

………..

}

Correct

If { ….. } {

……….

} else {

…..

}

Page 40: TCL Training Verdi 201107

if –else nested styles:

“if” Command (3/3)

if { } {…

} elseif { } {…

} elseif { } {…

} else {…

}

Control Tcl Programs

if { } {if { } {…

} else { …

}} else {

if { } {…

} else {…

}}

An example for if-elseif nested style

An example for if-else nested style

Page 41: TCL Training Verdi 201107

while: Execute script repeatedly as long as a condition is met • Syntax: while test body

• Where test is a Boolean expression• Body is the program to be executed when test is true

• Example:

Control Tcl Programs“while” Command

## calculate the sum from 0~10

set a 0set sum 0while {$a <= 10} {

set sum [expr $a+$sum]set a [expr $a + 1]

}puts “ Total = $sum “

012345678910

00136101521283645

013610152128364555

a sum new sum

Page 42: TCL Training Verdi 201107

Control Tcl Programs

for: 'For' loop • Syntax: for start test next body• The flow:

1. Execute start2. Repeatedly evaluates test3. If the result of test is non-zero it invokes body4. Invokes the Tcl interpreter on next5. Back to step 2 to repeat the loop

• Example:## calculate the sum from 0~10 for {set a 0; set sum 0} {$a <= 10} {incr a} {

set sum [expr $sum + $a]}puts “ Total = $sum “

“for” Command

Page 43: TCL Training Verdi 201107

Control Tcl Programs

foreach: Iterate over all elements in one or more lists • Syntax: foreach varname list body

• List: a Tcl list• Body: the Tcl script• The flow: For each element of list (in order from first to last), foreach

assigns the contents of the element to varname, then executes body. • Example:

set sum 0set numList [list 1 2 3 4 5 6 7 8 9 10]foreach a $numList {

set sum [expr $sum+ $a]}puts “Total = $sum”

“foreach” Command

Page 44: TCL Training Verdi 201107

switch: Evaluate one of several scripts, depending on a given value

• Syntax: switch options string {pattern1 body1 pattern2 body2 ...} • Options: -exact, -glob, -regexp, -nocase, -matchvar, -indexvar, --

• -exact : use exact matching, this is default• -regexp : use regular expression matching • -- : Marks the end of options. The argument following this one will be

treated as string even if it starts with a –• Refer to the Tcl manual for detailed usage

• NOTE: The comment in switch command is only allowed in body; otherwise, it may cause problems in Tcl parser.

Control Tcl Programs“switch” Command

Page 45: TCL Training Verdi 201107

Control Tcl Programs

switch example:

proc aa {value} {set b 0switch -regexp -- $value {

Verdi {set b caseA } {[0-9]+} {set b caseB } {^(c|d)} {set b caseC } default {set b caseD }}return $b

}

“switch” Command

tcl>aa VerdicaseA

tcl>aa 1caseB

tcl>aa ccaseC

tcl>aa abccaseD

Page 46: TCL Training Verdi 201107

Tcl can use exec command to invoke external programs • The external program result, which directs to the standard output,

will be returned• The exec command supports output redirect “<“ and “>” and

pipeline “|”• Example:

• set date [exec date]• set n [exec sort < /etc/passwd | uniq ]

• If the external program gets error when executing, it will causethe exec command to get the unexpected value. To avoid this, you can use catch command to filter the error message:• catch {exec program arg1 arg2 } result

• NOTE: Use curly brace “{ }” after catch command, this is because catch will invoke Tcl interpreter. The command will be executed before activate catch if you use the square bracket “[ ]”

Control Tcl ProgramsExecute External Programs

Page 47: TCL Training Verdi 201107

catch: Evaluate script and trap exceptional returns • Syntax: catch script resultVarName• If the script raises an error:

• catch returns a non-zero integer value and saves the error to resultVarName

• If the script does not have an error:• catch returns zero value and saves the return value to resultVarName

• Example:proc cat {} {

set fildid ""if { [catch { open ./abc.tcl r } fileid ] } {

puts "opening file error: $fileid"} else {

while { [ gets $fileid line ] } { puts $line

}close $fileid

}}

Control Tcl ProgramsPreventing Errors – “catch” Command

Page 48: TCL Training Verdi 201107

Manipulate Files

Frequently used commands for file processing:• open fileName access: Open a file-based or command pipeline

channel • puts channelId string: Write to a channel • gets channelId varName: Read a line from a channel • read channelId numChars: Read from a channel • Close channelId r|w: Close an open channel

Example:set filename “input.data”set input [open $filename r ]while { [gets $input read_line] >= 0 } {

puts “read_line=$read_line”}close $input

Commands for File Processing

Page 49: TCL Training Verdi 201107

A better coding style for opening a file:if { {catch { open data r } fileId } { puts “cannot Open data : $fileId”} else { ………; close $fileId}

Access for open command:• r: Open a file for reading; the file must already exist • r+: Open a file for reading and writing; the file must already exist • w: Open a file for writing, create it if it doesn’t exist• w+: Open a file for reading and writing, create it if it doesn’t exist• a: Open a existing file for writing, new data is appended• a+: Open a existing file for reading and writing, new data is appended

NOTE: Remember to close the file, otherwise the data may lost.

Manipulate FilesFile Processing – open

Page 50: TCL Training Verdi 201107

file: Manipulate file names and attributes • Syntax: file option name arg1 arg2 ...• Frequently used options:

• file dirname name: Return the directory name of name file • file executable name: Returns 1 if file name is executable, 0 otherwise. • file exists name: Returns 1 if file name exists, 0 otherwise. • file extension name: Returns the extension name of file name. • file isdirectory name: Returns 1 if file name is a directory, 0 otherwise• file size name: Returns the file size of file name.• file mkdir name : Generate a directory name.• file join path name: Concatenate path and name• file rootname name: Returns name but filters the last component after “.”.• file tail name: Returns name after the last directory separator.

Example:• file join work/verdi a.tcl work/verdi/a.tcl• file rootname /work/verdi/a.gds /work/verdi/a • file tail /work/verdi/a.tcl a.tcl

Manipulate FilesFile Processing – file

Page 51: TCL Training Verdi 201107

Lab 3

Refer to following “while” script for calculating (1+2+3+…+9+10), try to use “for” loop to write a script for calculating (1+3+5+…+9):

set a 0; set sum 0while {$a <=10} {incr sum $a; incr a}; puts $sum

Write a simple Tcl script

Page 52: TCL Training Verdi 201107

In the Command Entry form:• When you execute any GUI command, the associated Tcl

command will be logged in the Command Entry form• Directly typing the Tcl command in the Command Entry form will

execute the Tcl command• Type source your_script.tcl in the Command Entry form to

execute the Tcl script

Use Tcl in VerdiExecute Tcl in GUI

Page 53: TCL Training Verdi 201107

Open the Command Entry form:• Invoke the Preferences form from Tools Preferences

• Go to General folder, enable the Enable TCL Command Entry Form option, the Command Entry form will be opened.

• The setting will be saved into novas.rc, and the Command Entry form will be opened automatically next time you invoke Verdi

Use Tcl in VerdiExecute Tcl in GUI

Page 54: TCL Training Verdi 201107

Execute the Tcl script in Verdi command line:• % Verdi –play your_script.tcl &• All associated Tcl commands will be saved in ./VerdiLog/Verdi.cmd

• Use –replay to execute the Verdi.cmd file can reproduce previous steps

Automatically source the Tcl script• By setting NOVAS_AUTO_SOURCE environment variable:

• % setenv NOVAS_AUTO_SOURCE your_script.tcl• % verdi &

• By modifying the novas.rc resource file:• Search for TclAutoSource tag in [General] section in the novas.rc file• Specify your Tcl script for the TclAutoSource tag, for example:

[General]TclAutoSource = MyTclScript.tcl

Use Tcl in VerdiExecute Tcl in Command Line

Page 55: TCL Training Verdi 201107

Register a Tk name for Verdi with –tkname• % Verdi -tkName <Tk name>

Add an event callback with triggered reason• Syntax: AddEventCallback TkAppName CallbackFun Reason async

• Check all available Reason in Introduction Tk Command Client Adding Event Callbacks to Your Tk Application section of the Novas Command Language document (tcl.pdf in <Novas_install>/doc directory)

NOTE: you can also register a callback with a triggered reason after invoking Verdi, for example:• AddEventCallback [tk appname] AutoLoadSignal

wvCreateWindow 1• To execute the Tcl procedure AutoLoadSignal when a nWave window

is created• tk appname: returns the name of the application, the application name

will be “Verdi” if you source the Tcl script after invoking Verdi

Use Tcl in VerdiRegister Event Callbacks

Page 56: TCL Training Verdi 201107

#!wish -f proc myFunc args {puts "Received CursorTime Change Event" puts "Parameters:" foreach i $args { puts $i } }exec Verdi -tkName abc & while {1} { set s [winfo interps] if {-1 != [string first abc $s]} { break; }after 500 } send abc {AddEventCallback demo.tcl myFunc wvCursorTimeChange 1}

Add this line to declare this is Tcl script

The script body which you want to execute in Verdi

Use Tcl in VerdiRegister Event Callbacks – Example (demo.tcl)

Invoke Verdi and give a Tk name

To confirm the Tk application is invoked before executing the next line

Register the callback: trigger myFunc when change cursor time in nWave

Page 57: TCL Training Verdi 201107

Users have a signal list file which was generated from another EDA tool; they want a direct way to load all signals into nWave from the file without selecting each one in Get Signals form.

Script introduction• file.list: the signal list generated from other EDA tool• load_menu.tcl: create banner menu• load.menu: define the banner menu• load_signal.tcl: the main body of the script

Case Study - 1Requirement

Page 58: TCL Training Verdi 201107

To execute the script: verdi –play load_menu.tcl &

Input file: file.list/system/addr[7:0]/system/clock

load_menu.tclfmAppendBannerMenu -win window_id -file load.menu

load.menuMenu Load{"Load Signals From File" _L f.tcl dummy "source load_signal2.tcl"}

The Script

Case Study - 1

Page 59: TCL Training Verdi 201107

Case Study - 1

To execute the script: verdi –play load_menu.tcl &

Input file: file.list/system/addr[7:0]/system/clock

load_menu.tclfmAppendBannerMenu -win window_id -file load.menu

load.menuMenu Load{"Load Signals From File" _L f.tcl dummy "source load_signal2.tcl"}

Append a bannermenu item

Could be $_nTrace1 or any string. If meaningless string is specified, the menu will apply to all existing windows

The file which defines the banner menu

The Script

Page 60: TCL Training Verdi 201107

Case Study - 1

To execute the script: verdi –play load_menu.tcl &

Input file: file.list/system/addr[7:0]/system/clock

load_menu.tclfmAppendBannerMenu -win window_id -file load.menu

load.menuMenu Load{"Load Signals From File" _L f.tcl dummy "source load_signal.tcl"}

Give the name forthe banner menu

The command name under the banner menu

The bind-key for the command, needs to be one of the

command name characters

f.tcl : execute a tcl script f.exec: execute a Verdi command

Execute the tcl script when invoking the banner menu

TCL file name, could be any string

The Script

Page 61: TCL Training Verdi 201107

proc load_signal {} {global file_strset w .loadtoplevel $wwm title $w "Load Signals From File"

label $w.msg -justify left -text "Please specify file name"pack $w.msg -side top

frame $w.filepack $w.file -side top -fill x -pady 1entry $w.file.file -relief sunken -textvar file_strlabel $w.file.file_label -text "file name"pack $w.file.file_label -side leftpack $w.file.file -side left

button $w.file.load -text Load -command "load"button $w.file.dismiss -text Dismiss -command "destroy $w"pack $w.file.load $w.file.dismiss -side left

}

The Script – load_signal.tcl

Case Study - 1

Page 62: TCL Training Verdi 201107

Case Study - 1

proc load_signal {} {

global file_str

set w .load

toplevel $w

wm title $w "Load Signals From File"

label $w.msg -justify left -text "Please specify file name"pack $w.msg -side topframe $w.filepack $w.file -side top -fill x -pady 1entry $w.file.file -relief sunken -textvar file_strlabel $w.file.file_label -text "file name"pack $w.file.file_label -side leftpack $w.file.file -side leftbutton $w.file.load -text Load -command "load"button $w.file.dismiss -text Dismiss -command "destroy $w"pack $w.file.load $w.file.dismiss -side left

}

The Script – load_signal.tcl

Set a global variable file_str. the variable can be used in another procedure

Create .load as the top window.Note: a window name must start with “.”.

Specify the title for the .load windowThe syntax: wm title window “string”

Page 63: TCL Training Verdi 201107

Case Study - 1

proc load_signal {} {global file_strset w .loadtoplevel $wwm title $w "Load Signals From File"

label $w.msg -justify left -text "Please specify file name"

pack $w.msg -side top

frame $w.filepack $w.file -side top -fill x -pady 1entry $w.file.file -relief sunken -textvar file_strlabel $w.file.file_label -text "file name"pack $w.file.file_label -side leftpack $w.file.file -side leftbutton $w.file.load -text Load -command "load"button $w.file.dismiss -text Dismiss -command "destroy $w"pack $w.file.load $w.file.dismiss -side left

}

The Script – load_signal.tcl

label: Create and manipulate the label widget.-justify: When multiple lines of text displays in a widget, this option determines how the lines line up with each other. Must be one of left, center, or right. -text: Specifies a string to be displayed inside the widget.

pack: The pack command is used to communicate with the packer, a geometry manager that arranges the children of a parent by packing them in order around the edges of the parent -side: Specifies which side of the master the slave(s) will be packed against. Must be left, right, top, or bottom. Defaults to top.

Page 64: TCL Training Verdi 201107

Case Study - 1

proc load_signal {} {global file_strset w .loadtoplevel $wwm title $w "Load Signals From File"

label $w.msg -justify left -text "Please specify file name"pack $w.msg -side top

frame $w.file

pack $w.file -side top -fill x -pady 1

entry $w.file.file -relief sunken -textvar file_str

label $w.file.file_label -text "file name"

pack $w.file.file_label -side left

pack $w.file.file -side left

button $w.file.load -text Load -command "load"button $w.file.dismiss -text Dismiss -command "destroy $w"pack $w.file.load $w.file.dismiss -side left

}

The Script – load_signal.tcl

Create a frame widget .w.file

-fill x: If the slave's parcel is larger than its requested dimensions, this option may be used to stretch the slave. The argument x will stretch the slave horizontally to fill the entire width of its parcel.-pady amount: Amount specifies how much vertical internal padding to leave on each side of the slave. Amount defaults to 0.

Create a entry widget .w.file.file and pack the widget to its parent (.w.file).-relief: creates the 3-D effect for the widget. Acceptable values are raised,

sunken, flat, ridge, solid, and groove-textvar: specify the variable for the input text. File_str is a global variable.

Page 65: TCL Training Verdi 201107

Case Study - 1

proc load_signal {} {global file_strset w .loadtoplevel $wwm title $w "Load Signals From File"

label $w.msg -justify left -text "Please specify file name"pack $w.msg -side top

frame $w.filepack $w.file -side top -fill x -pady 1entry $w.file.file -relief sunken -textvar file_strlabel $w.file.file_label -text "file name"pack $w.file.file_label -side leftpack $w.file.file -side left

button $w.file.load -text Load -command "load"

button $w.file.dismiss -text Dismiss -command "destroy $w"

pack $w.file.load $w.file.dismiss -side left}

The Script – load_signal.tcl

Create a button widget .w.file.load-text: Specifies a string to be displayed inside the widget-command: Specifies a Tcl command to associate with the button

Create a button widget .w.file.dismiss and associate with Tcl command “destroy $w” to close the window.

Pack two buttons into the frame and specify the position

Page 66: TCL Training Verdi 201107

Case Study - 1

proc load {} {

global file_str

set file_id [open $file_str r]while {[gets $file_id sig_line] >= 0} {

wvAddSignal "$sig_line"}

}load_signal

The load procedure will be invoked when clicking Load button inload_signal procedure

Declare file_str as a global variable, the value is inherited from the entry .w.file.file in the load_signal procedure

The Script – load_signal.tcl

Open the file with read access, get each line in the file and add signal into nWave

To invoke the load_signal procedure

Page 67: TCL Training Verdi 201107

Case Study - 1

verdi –f run.f –ssf rtl.fsdb –play load_menu.tcl &

How does it works?

1. Invoke the command

2. Fill in the file name, click Load

3. Signals in the list will be loaded

Page 68: TCL Training Verdi 201107

[Function Abstract]This scripts generates an nWave session file before exiting and loads last session when nWave is invoked.

When select Save and Close Win under File menu on nWave , it generates nWave session file named "<FSDBName>.rc" and "AutoSaveSignal.rc" automatically.

If there is a file named "AutoSaveSignal.rc" when invoking nWave, it is loaded automatically.

[Usage]% setenv NOVAS_AUTO_SOURCE AutoSave.tcl% verdi ...

[Input File]-

[Output File]<FSDBNAME>.rcAutoSaveSignal.rc

Case Study - 2Readme File

Page 69: TCL Training Verdi 201107

proc AutoSaveSignal {} {global ary

if { [file exists "AutoSaveSignal.rc"] } {file rename -force AutoSaveSignal.rc AutoSaveSignal.rc.bak

}

set wid [wvGetCurrentWindow]set fname $ary($wid)

if { $fname != "" } {wvSaveSignal -win $wid "$fname.rc"

}wvSaveSignal -win $wid "AutoSaveSignal.rc“

wvCloseWindow -win $wid}

Case Study - 2The Script

Inherit $ary from GetFileName procedure

Check whether the save file already exists, rename if it exists

$fname: get the FSDB name from GetFileNameprocedure. Note it uses $ary($wid) to get the same FSDB name in GetFileName procedure when there are multiple FSDB files

Save signals to FSDB_name.rc file

Save signals to AutoSaveSignal.rc file

Close current nWave window

Page 70: TCL Training Verdi 201107

proc AutoLoadSignal {p1 p2} {

if { [file exists "AutoSaveSignal.rc"] } {wvRestoreSignal -win $p2 "AutoSaveSignal.rc"

}

eMenuAppendItem -win $p2 -menuName File -itemName "Save and Close Win" -tclCmd "AutoSaveSignal"

}

Case Study - 2The Script

Note: here the p1 and p2 argument will be:$P1: wvCreateWindow$P2: 2a97b46aa8 (the window ID)

Restore the AutoSaveSignal.rc file into nWave if the file already exists

Create a “Save and Close Win” command under File menu, invoking the command will execute the AutoSaveSignal procedure.

Page 71: TCL Training Verdi 201107

proc GetFileName {p1 p2} {global aryset lname ""set wid [wvGetCurrentWindow]

set sid [string last / $p2]set lid [string last . $p2]

set lname [string range $p2 [incr sid] [incr lid -1]]# puts "$p1 $p2 $lname"

set ary($wid) $lname}

AddEventCallback [tk appname] AutoLoadSignal wvCreateWindow 1AddEventCallback [tk appname] GetFileName wvOpenFSDBFile 1

Case Study - 2The Script

Get the window ID for current nWave window

$lname: get the string for fsdb name without “.fsdb”

Note: here the p1 and p2 argument will be:P1: wvOpenFSDBFileP2: /verdi/home/allen_shieh/demo/rtl.fsdb

$sid: get the index for last “/” in $p2$lid: get the index for last “.” in $p2

To store the fsdb name in $ary array with $wid index

Register callbacks to:1. Execute procedure AutoLoadSignal when opening nWave window2. Execute procedure GetFileName when loading FSDB

Page 72: TCL Training Verdi 201107

Requirement:• When there is any pulse in the signal which is smaller than the

specified time range, dump the signal name and the time when thepulse happens.

Hints:• Create an entry for specifying the time range by:

• Creating a menu item and question box for entry, or:• Using an environment variable, or:• Adding parameters in the script

• Use nWave commands to traverse scopes and find matching signals• Check <Novas_install>/doc/tcl.pdf to find proper commands

• Output a report for matching signals

To see how other people write the script:• Download the Script package from web site, check the example under

./Scripts/ReportSmallPulse

Lab 4Practice for Writing a Useful Tcl Script

Page 73: TCL Training Verdi 201107

Reference

Novas Command Language:• <Novas_install>/doc/tcl.pdf

Useful web sites:• Tcl Developer Site: http://www.tcl.tk/• Tcl Tutorials: http://www.tcl.tk/man/tcl8.5/tutorial/tcltutorial.html• Tcl Commands: http://www.tcl.tk/man/tcl8.5/TclCmd/contents.htm• Tk Commands: http://www.tcl.tk/man/tcl8.5/TkCmd/contents.htm

Books:• Sams Teach Yourself Tcl/Tk in 24 Hours – by Venkat V.S.S.• Practical Programming in Tcl and Tk – by Brent Welch and Ken Jones

Support you can find:• Training: Allen Shieh [email protected]

Get Help from Resources