Design Script Documentation
Design Script Documentation
Introduction
Lexicalelements
Comments
Semicolons
Identifiers
Keywords
Boolliteral
Integerliteral
Floatingpointliteral
Stringliteral
Types
PrimitiveTypes
Userdefinedtypes
List
Rank
Dynamiclist
Useasadictionary
Typeconversionrules(TBD)
Nonarraycase
Arraypromotion
Arraydemotion
Variables
Dynamic
ListImmutability
Scope
Declarations
Functiondeclaration
Defaultparameters
Functionoverloads
Classdeclaration
Inheritance
Constructors
Properties
Memberfunctions
Accessmodifiers
Staticmembers
_Dispose()method
Expressions
Listcreationexpression
Rangeexpression
Inlineconditionalexpression
Memberaccessexpression
Listaccessexpression
Operators
Arithmeticoperators
Comparisonoperators
Logicaloperators
Statements
Emptystatements
Importstatements
Expressionstatements
Assignments
Flowstatements
Returnstatements
Breakstatements
Continuestatement
Ifstatements
Whilestatements
Forstatements
Languageblocks
Defaultassociativelanguageblock
Nestedassociativelanguageblock
Imperativelanguageblock
Associativeupdate
Associativity
Associativityestablishment
Updatebyreexecution
Dependents
Entitiesthatcouldbedependedon
Variables
Function
Properties
Associativityscope
Replicationandreplicationguide
Replicationandreplicationguide
Functiondispatchruleforreplicationandreplicationguide
Builtinfunctions
1.
Introduction
ThisisthedocumentationforDesignScriptprogramminglanguage.DesignScriptisdynamic,
garbagecollectedandassociativelanguage,andprovidesstrongsupportforvisualprogramming
environment.
ThegrammarinthisspecificationisinExtendedBackusNaurForm(EBNF)1 .
ThisdocumentdoesntcontaininformationaboutAPIsandForeignFunctionInterface(FFI).Thelater
isimplementationdependent.
2.
Lexicalelements
2.1.
Comments
DesignScriptsupportstwokindsofcomments.
Singlelinecommentstartswith/ /andstopattheendoftheline.
Blockcommentsstartswith/ *andendswith* /.
Example:
x=1;//singlelinecomment
/*
Blockcomments
*/
y=2;
2.2.
Semicolons
Semicolon;isusedasaterminatorofastatement.
2.3.
Identifiers
IdentifiersinDesignScriptnamevariables,types,functionsandnamespaces.
Identifier=
identifier_start_letter{identifier_part_letter}
identifier_start_letteristheunicodecharacterinthefollowingcategories:
Uppercaseletter(Lu)
Lowercaseletter(Ll)
Titlecaseletter(Lt)
Modifierletter(Lm)
Otherletter(Lo)
Letternumber(Nl)
https://en.wikipedia.org/wiki/Extended_BackusNaur_Form
identifier_part_letteristheunicodecharacterinthecategoriesofidentifier_start_letterincluding
thefollowingcategories:
Combiningletter(Mn,Mc)
Decimaldigitalletter(Nd)
Connectingletter(Nc)
ZeroWidthNonJoiner
ZeroWidthJoiner
2.4.
Keywords
Thefollowingwordsarereservedaskeywords
break,class,constructor,continue,def,else,elseif,extends,for,from,if,
import,in,return,static,while,
2.5.
Boolliteral
true,false
2.6.
Integerliteral
Integerliteralrepresentsanintegerconstant.Itisindecimalbase,orinhexadecimalbase.
digit=0..9
hex_digit=0..9+a..f+A..F
decimal_number=digit{digit}
hexadecimal_number=(0x|0X)hex_digit{hex_digit}
InDesignScript,therangeofintegervalueis263
263
1.
Example:
123;
0xff;//255
0XFF;//255
2.7.
Floatingpointliteral
Floatingpointliteralrepresentafloatingpointconstantindecimalbase.
floating_point=
digit{digit}.[digit{digit}][exponent]
|digit{digit}exponent
|.digit{digit}[exponent]
exponent=(E|e)[+|]digit{digit}
Example:
1.2e3;//1200.0;
1.234;
.123;//0.123
2.8.
Stringliteral
Stringliteralrepresentsastringconstant.Itisobtainedbyputtingcharactersequencebetween
doublequote( ).
Anycharactercanbeinthesequenceexceptnewlineanddoublequote( ).Backslashcharacterinthe
sequencecouldbecombinedwiththenextcharactertobecomeanescapecharacter2:
\a
\b
\f
\n
\t
\v
\r
Example:
//HelloDesignScript
//Language
\Hello\tDesignScript\nLanguage\;
3.
Types
3.1.
PrimitiveTypes
ThetypesysteminDesignScriptisdynamicandobjectoriented.DesignScriptsupportsfollowing
primitivetypes
Type
Valuerange
Defaultvalue
string
n.a.
integer
263
263
1
https://en.wikipedia.org/wiki/Escape_character
floatingpoint
IEEE754doubleprecision3
bool
true,false
false
null
null
null
var
n.a.
null
Thedefaultvalueofallothertypesisnull.
3.2.
Userdefinedtypes
Userdefinedtypesaresupportedthroughclassmechanism.Objects,instancesofclasses,may
contain
Properties
Instancemethods
Staticmembers
Constructors
OnlysingleinheritanceisallowedinDesignScript.
3.3.
List
3.3.1.
Rank
Ifatypehasranksuffix,itdeclaresalist.Thenumberof[]specifiesthenumberofrank.[]..[]
specifiesarbitraryrank.Forexample,
int[]//anintegerlistwhoserankis1
int[][]//anintegerlistwhoserankis2
int[]..[]//anintegerlistwitharbitraryrank
Therankoftypedecideshowdoreplicationandreplicationguideworkinfunctiondispatch.
3.3.2.
Dynamiclist
ThelistinDesignScriptisdynamic.Itispossibletoindexintoanylocationofthelist.Ifsettingvalueto
anindexwhichisbeyondthelengthoflist,listwillbeautomaticallyexpanded.Forexample,
x={1,2,3};
x[5]=4;//x={1,2,3,null,null,4};
3.3.3.
Useasadictionary
https://en.wikipedia.org/wiki/Doubleprecision_floatingpoint_format
ListinDesignScriptisjustaspecialcaseofdictionarywhosekeysareintegers.Whenindexingalist,
thetypeofkeycouldbeanytype.Forexample:
x={1,2,3};
x[foo]=4;
x[false]=5;
Whenadictionaryisusedininclauseofforloop,itreturnsallvaluesassociatedwithkeys.
3.4.
Typeconversionrules(TBD)
Followingimplicittypeconversionrulesspecifytheresultofconvertingonetypetoanother:
3.4.1.
Nonlistcase
yesmeansconvertible,nomeansnoconvertible.
To
From
var
int
double
bool
string
userdefined
var
yes
no
no
no
no
no
int
yes
yes
yes
x!=0
no
no
double
yes
warning
yes
x!=0&&x
!=NaN
no
no
bool
yes
no
no
yes
yes
no
string
yes
no
no
x!=
yes
no
userdefined
yes
no
no
x!=null
no
Covariant
3.4.2.
Arraypromotion
To
From
var[]
int[]
double[]
bool[]
string[]
user
defined[]
var
yes
no
no
no
no
no
int
yes
yes
yes
x!=0
no
no
double
yes
warning
yes
x!=0&&x
!=NaN
no
no
bool
yes
no
no
yes
yes
no
string
yes
no
no
x!=
yes
no
userdefined
yes
3.4.3.
no
no
x!=null
no
Covariant
Arraydemotion
To
From
var
int
double
bool
string
userdefined
var[]
yes
no
no
no
no
no
int[]
yes
yes
yes
x!=0
no
no
double[]
yes
warning
yes
x!=0&&
x!=NaN
no
no
bool[]
yes
no
no
yes
yes
no
string[]
yes
no
no
x!=
yes
no
user
defined[]
yes
no
no
x!=null
no
Covariant
4.
Variables
4.1.
Dynamic
VariablesinDesignScriptaredynamic.Itisfreetoassignanykindsofobjectstoanyvariable,andthe
typeofavariableistotallyruntimedependent.
4.2.
ListImmutability
ListsinDesignScriptareimmutable.Thatis,whencopyingalistfromonevariabletotheother
variable,itisdeepcopyoperation:allelementsinthelistarecopiedaswell.
4.3.
Scope
DesignScriptusesblockscope4,andblocksareeitherfunctionsorlanguageblocks.Becauseof
associativity,avariablecouldbeusedbeforeitisdefined,theDesignScriptvirtualmachinewillensure
topropagatethevalueupdatetoallitsreferences.
Example:
x=1;
y=2;
deffoo(x){
https://en.wikipedia.org/wiki/Scope_(computer_science)#Block_scope
z=3;//zislocalvariable
return=x+y;//xisparameter
//yisdefinedintheglobalassociativelanguageblock
}
[Imperative]{
x=3;//updatetheglobalx
m=n;//m,narelocalvariables.Itisfinetousen
n=4;//theVMensuresmfinallyis4
return=x+y+m;
}
4.4.
Scoperesolution
Thesearchorderofanidentifieris
Innermostscope.
Eachprogressiveouterscope,includingclassscope.
Classesthatthecurrentclassextends.
Theglobalscope.
5.
Declarations
5.1.
Functiondeclaration
FunctionDeclaration=
defidentifier[:TypeSpecification]ParameterListStatementBlock.
ParameterList=
([Parameter{,Parameter}])
Parameter=
identifier[:TypeSpecification][DefaultArgument]
StatementBlock=
{{Statement}}
Thereturntypeoffunctionisoptional.Bydefaultthereturntypeisvar.Ifthereturntypeisspecified,
typeconversionmayhappen.Itisnotencouragedtospecifyreturntypeunlessitisnecessary.
Functionmustbedefinedintheglobalassociativelanguageblock.
Forparameters,iftheirtypesarenotspecified,bydefaultisv ar.Thetypeofparametersshouldbe
carefullyspecifiedsothatreplicationandreplicationguidewillworkasdesired.Forexample,ifa
parameterstypeisv ar[]..[](arbitraryrank),itmeansnoreplicationonthisparameter.
Example:
deffoo:var(x:int[]..[],y:int=3)
{
return=x+y;
}
5.1.1.
Default parameters
Functiondeclarationallowstohavedefaultparameter,butwithonerestriction:alldefault
parametersshouldbetherightmostparameters.
Forexample:
//itisvalidbecauseyandzaretherightmostdefaultparameters
deffoo(x,y=1,z=2)
{
return=x+y+z;
}
//itisinvalidbecausexisnottherightmostdefaultparameter
defbar(x=1,y,z=2)
{
return=x+y+z;
}
5.1.2.
Function overloads
DesignScriptsupportsfunctionoverload,i.e.,functionswithasamenamebutwithdifferent
types/numberofparameters,butwhichfunctionwillbecalledfinallyistotallyruntimedependent,,
especiallyifreplicationhappens.DesignScriptvirtualmachinewilltrytofindoutthebestmatchone
basedonthetypeofargumentsandthetypeofallparametersofallfunctioncandidates.
Followingcodeshowsafunctionoverloadexample:
deffoo(x:int,y:int)
{
return=x+y;
}
deffoo(x:double,y:double)
{
return=x*y;
}
//willcallfoo(x:int,y:int)
r1=foo(2,3);
//willcallfoo(x:double,y:double)
r2=foo(2.1,3.2);
5.2.
Classdeclaration
ClassDeclaration=
classidentifer[extendsidentifier]
{[ClassMemberDeclaration]}
ClasMemberDeclaration=
ConstructorDeclaration
|MemberDeclaration
ConstructorDeclaration=
constructoridentifierParameterList
[:base(ArgumentList)]
StatementBlock
MemberDeclaration=
[AccessModifier][static](FunctionDeclaration|VariableDeclaration;)
AccessMmodifier=public|protected|private
Classshouldbedefinedinthetopassociativelanguageblock.
5.2.1.
Inheritance
DesignScriptonlysupportssingleinheritance.Thatis,onlyonebaseclassisallowed.
Example:
classPoint2D
{
...
}
classPoint3D:extendsPoint2D
{
...
}
5.2.2.
Constructors
Althoughitisnotforced,butitissuggestedthatthenameofconstructorstartswithBytoindicate
howtocreatetheobject.Forexample,theconstructorofcreatingaP ointmaybe
B yCoordinates().
Iftheclassinheritsfromtheotherclass,itispossibletocallthebaseclass'sconstructorbycalling
b ase(...).
Tocreateaninstanceofclass,useobjectcreationstatementC lassName.ConstructorName(...).If
thenameofconstructoristhesameasclassname,oraclassiswithoutconstructor(inthiscasea
defaultconstructorwillbecreatedinternally),inbothcasesobjectcreationstatementcouldbe
simplifiedasC lassName(...).
Example:
classPoint2D
{
constructorByCoordinates(x,y)
{
...
}
}
classPoint3D:extendsPoint2D
{
constructorByCoordinates(x,y,z):base(x,y)
{
...
}
constructorPoint3D()
{
...
}
}
//createaninstanceofPoint3D
p1=Point3D.ByCoordinates(1,2,3);
//createtheotherinstanceofPoint3D
p2=Point3D();
5.2.3.
Properties
Variablesdefinedinclassareproperties.Theinitializationofpropertiescouldeitherbeinconstructor
orindefinition.
Todistinguishpropertiesfromotherkindsofvariables,memberaccessexpression
t his.property_nameorb ase.property_namecouldbeusedtoindicatep roperty_nameisa
propertyoftheclassorapropertyofbaseclass.
classPoint2D
{
x=0;//initializepropertyx
y=0;
constructorByCoordinates(x,y)
{
this.x=x;
this.y=y;
}
}
classPoint3D:extendsPoint2D
{
z=0;
constructorByCoordinates(x,y,z):base(x,y)
{
this.z=z;
}
constructorPoint3D()
{
x=1;//itispropertyxofbaseclass
base.y=1;//itispropertyyofbaseclass
z=1;
}
}
//createtheotherinstanceofPoint3D
p1=Point3D();
//x==1
x=p1.x;
//updatepropertyy
p1.y=2;
5.2.4.
Memberfunctions
Thedefinitionofmemberfunctionsisthesameasnormalfunctiondefinition.Allpropertiesare
accessibleinmemberfunctions.
5.2.5.
Accessmodifiers
Theaccessrestrictiontoclasspropertiesandmemberfunctionsarespecifiedbylabelspublic,
protectedandp
rivate.Ifnoaccessspecifierisspecifiedformembers,bydefaulttheyarepublic.
Thefollowingrulesapply:
Publicmembersareaccessiblefromanywhereinsideandoutsidetheclass.
Protectedmembersareonlyaccessibleintheclassorinthederivedclass.
Privatemembersareonlyaccessibleintheclass.
Example:
classBase
{
privateprop1;
protectedprop2;
publicprop3;
privatedeffoo1()
{...}
protecteddeffoo2()
{...}
//bydefaultitispublic
deffoo3()
{
}
}
classDerived:extendsBase
{
defbar()
{
//as"prop1"isprivateinbase,itisnotaccessible
x=prop1;
//"prop2"isaccessibleinderivedclass
y=prop2;
//"prop3"isaccessibleinderivedclass
z=prop3;
}
}
b=Base();
//as"prop1"isprivate,itisnotaccessibleoutsidetheclass
//p1isnull
p1=b.prop1;
//as"prop2"isprotected,itisnotaccessibleoutsidetheclass
//p2isnull
p2=b.prop2;
//as"prop3"ispublic,itisaccessibleoutsidetheclass
p3=b.prop3;
5.2.6.
Staticmembers
Staticpropertiesandstaticmemberfunctionsaredefinedonclasslevel.Thatis,theaccessexpression
isintheformof"C lassName.X"or"C lassName.Y()'
Therearesomerules:
Itisinvalidtoaccessstaticmembersoninstancelevel.
Itisinvalidifastaticpropertyhasthesamenameasanonstaticproperty,orastaticmember
functionhasthesamesignatureasanonstaticmemberfunction.
Itisnotnecessarytohave"C lassName."prefixwhencallingstaticmembersintheclass.
Theexamplebelowsshowstheserules:
classFoo
{
x;
//error:xhasbeendefinedasanonstaticproperty
staticx;
staticY;
deffoo()
{
}
//error:foo()hasbeendefinedasanonstaticmemberfunction
staticdeffoo()
{
}
staticdefbar()
{
//error:itisinvalidtocallstaticmemberfunctioninnonstatic
//memberfunction
qux();
}
defqux()
{
//itisfinetocallstaticmemberfunctioninnonstaticmember
//function
bar();
}
}
f=Foo();
//error:itisinvalidtoaccessstaticmembersoninstancelevel
r=f.Y;
//getthevalueofstaticmember"Y"
r=Foo.Y;
//error:itisinvalidtoaccessstaticmembersoninstancelevel
r=f.bar();
//callstaticmemberfunction"bar()"
r=Foo.bar();
5.2.7.
_Dispose() method
Ifapublic_Dispose()methodisdefinedintheclass,whentheinstanceisgarbagecollected,this
methodwillbecalled,so_Dispose()couldbeusedtoreleaseresourcesacquiredbyinstance.
Typically,thismethodwillbegeneratedautomaticallyforFFIclasses.
Example:
classDiposable
{
staticFlag=false;
def_Dispose()
{
Flag=true;
}
}
[Imperative]
{
d=Disposable();
//builtinfunctiontoforcegarbagecollection.
__GC();
//"d"willbegarbagecollected
}
//Disposable.Flagistrue
r=Disposable.Flag;
5.3.
Functionresolution
Theorderofresolveafunctionis:
Innermostscope
Eachprogressiveouterscope
Classinstancescope
Classthattheclassextends
Theglobalscope
Asfunctioncouldbeoverloaded,theresultoffunctionresolutionwillreturnalistoffunction
candidates.Thevirtualmachinewillfindoutthebestmatchdependingonthetypeofarguments,the
typesofparametersandreplicationguide.
6.
Expressions
6.1.
Listcreationexpression
ListCreationExpression={[Expression{,Expression}]}
Listcreationexpressionistocreatealist.Example:
x={{1,2,3},null,{true,false},DesignScript};
6.2.
Rangeexpression
Rangeexpressionisaconvenientwaytogeneratealist.
RangeExpression=
Expression[..[#]Expression[..[#]Expression]
Therearethreeformsofrangeexpressions:
start_value..end_value
Ifs tart_value<e nd_value,itgeneratesalistinascendantorderwhichstartsat
start_value,andthelastvalue<e
nd_value,theincrementis1
Ifs tart_value>e nd_value,itgeneratesalistindescendentorderwhichstartsat
start_valueandthelastvalue>=e
nd_value,theincrementis1.
start_value..#number_of_elements..increment:itgeneratesalistthatcontains
number_of_elementselements.Elementstartsats
tart_valueandtheincrementis
increment.
start_value..end_value..#number_of_elements:itgeneratesalistthatcontains
number_of_elementselements.Elementstartsatstart_valueandendsatend_value.
Dependingonifs tart_value<=e nd_value,thegeneratedlistwillbeinascendantorderorin
descendentorder.
Example:
1..5;//{1,2,3,4,5}
5..1;//{5,4,3,2,1}
1.2..5.1;//{1.2,2.2,3.2,4.2}
5.1..1.2;//{5.1,4.1,3.1,2.1}
1..#5..2;//{1,3,5,7,9}
1..5..#3;//{1,3,5}
Rangeexpressionishandledspeciallyforstringswithsinglecharacter.Forexample,followingrange
expressionsarevalidaswell:
a..e;//{a,b,c,d,e}
a..#4..2;//{a,c,e,g}
a..g..#3;//{a,d,g}
6.3.
Inlineconditionalexpression
InlineConditionalExpression=Expression?Expression:Expression;
Thefirstexpressionininlineconditionalexpressionisconditionexpressionwhosetypeisbool.Ifitis
true,thevalueof?clausewillbereturned;otherwisethevalueof:clausewillbereturned.The
typesofexpressionsfortrueandfalseconditionsarenotnecessarytobethesame.Example:
x=2;
y=(x%2==0)?foo:21;
Inlineconditionalexpressionsreplicateonallthreeexpressions.Example:
x={true,false,true};
y={foo,bar,qux};
z={ding,dang,dong};
r=x?y:z;//replicates,r={foo,dang,qux}
6.4.
Memberaccessexpression
Memberaccessexpressionisoftheform
x.y.z
yandzcouldbeproperties,ormemberfunctions.Iftheyarenotaccessible,nullwillbe
returned.
6.5.
Listaccessexpression
Listaccessexpressionisoftheform
a[x]
xcouldbeintegervalueorakeyofanykindoftypes(ifaisadictionary).
Thefollowingrulesapply:
Ifitisjustgettingvalue,ifa isnotalist,orthelengthofaislessthanx,ortherankof
a islessthanthenumberofindexer,forexampletherankofa is2buttheexpressionis
a[x][y][z],therewillbeaIndexOutOfRangewarningandn
ullwillbereturned.
Ifitisassigningavaluetothelist,ifa isnotalist,orthelengthofaislessthanx ,orthe
rankofa islessthanthenumberofindexer,a willbeextendedoritsdimensionwill
promotedsothatitisabletoaccommodatethevalue.Forexample,
a=1;
a[1]=2;//awillbepromoted,a={1,2}now
a[3]=3;//awillbeextended,a={1,2,null,3}now
a[0][1]=3;//awillbepromoted,a={{1,3},2,null,3}now
6.6.
Operators
ThefollowingoperatorsaresupportedinDesignScript:
+Arithmeticaddition
Arithmeticsubtraction
*Arithmeticmultiplication
/Arithmeticdivision
%Arithmeticmod
>Comparisonlarge
>=Comparisonlargethan
<Comparisonless
<=Comparisonlessthan
==Comparisonequal
!=Comparisonnotequal
&&Logicaland
||Logicalor
!Logicalnot
Negate
Alloperatorssupportreplication.Exceptunaryoperator!,allotheroperatorsalsosupport
replicationguide.Thatis,theoperandscouldbeappendedreplicationguides.
x={1,2,3};
y={4,5,6};
r1=x+y;//replication
//r1={5,7,9}
r2=x<1>+y<2>;//replicationguide
//r2={
//{5,6,7},
//{6,7,8},
//{7,8,9}
//}
Operatorprecedence
Precedence
Operator
*,/,%
+,
>,>=,<,<=,==,!=
&&
||
6.7.
Arithmeticoperators
+,,*,/,%
Normallytheoperandsareeitherintegervalueorfloatingpointvalue.+canbeusedasstring
concatenation:
s1=Design;
s2=Script;
s=s1+s2;//DesignScript
6.8.
Comparisonoperators
>,>=,<,<=,==,!=
6.9.
Logicaloperators
&&,||,!
Theoperandshouldbebooltype;otherwisetypeconversionwillbeincurred.
7.
Statements
7.1.
Emptystatements
Emptystatementis
7.2.
Importstatements
ImportstatementsimportotherDesignScriptsourcefileorC#assemblyintocurrentnamespace.
ImportStatement=import((string|(identfromstring)))
IfimportingaC#assembly,DesignScriptvirtualmachinewillgenerateDesignScriptclassesforclasses
definedintheassembly,thisisdonebyFFI.
Importstatementscouldimportalltheentitiesfoundatthelocation,orforspecificnamedentity
foundatthelocation.
Thelocationmaybespecifiedby:
Arelativefilepath,usinglocaloperatingsystemconventions.
Anabsolutefilepath,usinglocaloperatingsystemconventions.
AURI.
Example:
import(/home/dev/libraries/foo.ds);
import(PointfromGeometry.dll);
7.3.
Expressionstatements
ExpressionStatement=Expression;
Expressionstatementsareexpressionswithoutassignment.
7.4.
Assignments
Assignment=Expression=((Expression;)|LanguageBlock)
Thelefthandsideof=shouldbeassignable.Typically,itismemberaccessexpressionorarray
accessexpressionorvariable.Ifthelefthandsideisavariablewhichhasntbeendefinedbefore,the
assignmentstatementwilldefinethisvariable.
7.5.
Flowstatements
Flowstatementschangetheexecutionflowoftheprogram.Aflowstatementisoneofthefollowings:
1. Areturnstatement.
2. Abreakstatementintheblockoffororwhilestatementinimperativelanguageblock.
3. Acontinuestatementintheblockoffororwhilestatementinimperativelanguageblock.
7.6.
Returnstatements
ReturnStatement=return=Expression;
Areturnstatementterminatestheexecutionoftheinnermostfunctionandreturnstoitscaller,or
terminatestheinnermostimperativelanguageblock,andreturnstotheupperlevellanguageblockor
function.
7.7.
Breakstatements
BreakStatement=break;
Abreakstatementterminatestheexecutionoftheinnermostforlooporwhileloop.
7.8.
Continuestatement
ContinueStatement=continue;
Acontinuestatementbeginsthenextiterationoftheinnermostforlooporwhileloop.
7.9.
Ifstatements
ifstatementsspecifytheconditionalexecutionofmultiplebranchesbasedonthebooleanvalueof
eachconditionalexpression.ifstatementsareonlyvalidinimperativelanguageblock.
IfStatement=
if(Expression)StatementBlock
{elseif(Expression)StatementBlock}
[elseStatementBlock]
Forexample:
x=5;
if(x>10){
y=1;
}
elseif(x>5){
y=2;
}
elseif(x>0){
y=3;
}
else{
y=4;
}
7.10.
Whilestatements
whilestatementsrepeatedlyexecutesablockuntiltheconditionbecomesfalse.whilestatements
areonlyvalidinimperativelanguageblock.
WhileStatement=while(Expression)StatementBlock
Example:
sum=0;
x=0;
while(x<10)
{
sum=sum+x;
x=x+1;
}
//sum==55
7.11.
Forstatements
foriteratesallvaluesininclauseandassignsthevaluetotheloopvariable.Theexpressioninin
clauseshouldreturnalist;ifitisasingleton,itisasinglestatementevaluation.forstatementsare
onlyvalidinimperativelanguageblock.
ForStatement=for(IdentifierinExpression)StatementBlock
Example:
sum=0;
for(xin1..10)
{
sum=sum+x;
}
//sum==55
8.
Languageblocks
8.1.
Defaultassociativelanguageblock
Bydefault,allstatementsareinadefaulttopassociativelanguageblock,soassociativeupdateis
enabledbydefault.
Notlikenestedlanguageblock,thereisnoreturnstatementintoplanguageblock:allstatementswill
beexecutedsequentiallytothelastone.
8.2.
Nestedassociativelanguageblock
Itisalsovalidtoexplicitlydefineanestedassociativelanguageblockinthetopassociativelanguage
block,inanimperativelanguageblockorinafunction.
AssociativeLanguageBlock=[Associative]StatementBlock
Thestatementsinassociativelanguageblockwillbeexecutedsequentiallyuntilareturnstatement
returnsavalue;otherwisethelanguageblockreturnsn ull.
Noteitisinvalidtodefineanassociativelanguageblockinsideanassociativelanguageblock,except
thelateristhedefaultone.
Examples:
x=1;
//z=3
z=[Associative]
{
y=2;
return=x+y;
}
[Associative]
{
//invalidassociativelanguageblock
[Associative]
{
}
}
8.3.
Imperativelanguageblock
Imperativelanguageblockprovidesaconvenientwaytouseimperativesemantics.Similartonested
associativelanguageblock,imperativelanguageblockexecutesallstatementssequentiallyunlessa
statementisareturnstatementtoreturnavalue.Imperativelanguageblockcanonlybedefinedin
theotherassociativelanguageblock,includingthetopassociativelanguageblock.
Thekeydifferencesbetweenassociativelanguageblockandimperativelanguageblockare:
Associativeupdateistemporarilydisabledinimperativelanguageblock.
if,forandwhilestatementsareonlyavailableinimperativelanguageblock.
Example:
x=1;
//defineanimperativelanguageblockinthetopassociativelanguageblock
y=[Imperative]
{
if(x>10){
return=3;
}
elseif(x>5){
return=2;
}
else{
return=1;
}
}
defsum(x)
{
//defineanimperativelanguageblockinsideafunction,whichisinglobal
//associativelanguageblock
return=[Imperative]
{
s=0;
for(iin1..x)
{
s=s+i;
}
return=s;
}
}
[Associative]
{
//defineanimperativelanguageblockinsideanassociativelanguageblock
return=[Imperative]
{
return=42;
}
}
[Imperative]
{
//invalidimperativelanguageblock
[Imperative]
{
}
}
9.
Associativeupdate
9.1.
Associativity
AssociativityisafeatureinDesignScriptthatallowsthepropagationofchangeofavariabletoall
dependentstatementsintheprogram.Thepropagationofchangehappensatruntimeandishandled
byupdatemechanisminDesignScriptvirtualmachine.
Followingcodeshowsasimpleassociativeupdatecase:
1:x=1;
2:y=x;
3:x=3;
Ifthecodeisinassociativelanguageblock,itwillbeexecutedasfollow:
1. x issetto1.
2. y issettoxanddependsonx ,soy is1.
3. x ischangedto3.Asy dependsonx ,y willbeupdatedto3.
Ontheotherhand,ifthecodeisinimperativelanguageblock,thechangeofx willnotupdatey,
justlikeotherprogramminglanguages.
Therearefourkeyelementsinassociativitydefinitionandupdate:
1. Theestablishmentofassociativityisdonebyassignmentstatement.
2. Theupdateisdonebyreexecutingassignmentstatement.
3. Thedependent(onthelefthandsideofassignment)couldbe
Variables
Properties
4. Entitiesthatcouldbedependedonare
Variables
Properties
Functions
9.2.
Associativityestablishment
Assignmentstatementinassociativelanguageblockestablishesarelationshipbetweentheassigned
entitiesandtheentitiesusedinthestatementtocomputeit.Reredefinitionwillremoveprevious
associativity(ifthereis)andredefineassociativity.
Itisimportanttonotethattheassignedentitiesandtheentitiesthataredependedonshouldbe
definedinthesamescope.Seeassociativityscope.
Anexampleinassociativelanguageblock
1:x=1;
2:y=2;
3:z=foo(x,y);
4:x=3;
5:y=4;
6:z=0;
7:x=5;
Atline3,theassignmentestablishestheassociativitybetweenzandfoo,xandy,sozwill
dependonf oo,x andy .Afterupdatingx to3,line3willbereexecutedtoupdatez ;after
updatingy to4atline5,line3willbereexecutedagain.
Assignmentstatementinimperativelanguageblockchangesonlyvariables/propertiestheyare
assignedtoandhasnoimplicitupdate.
Anexampleinimperativelanguageblock
[Imperative]
{
1:x=1;
2:y=x;
3:x=3;
}
Thecodeisexecutedlinebyline,norecomputationwillhappeninimperativelanguageblock.After
execution,x is3andy is1.
9.3.
Updatebyreexecution
Thechangeispropagatedtoalldependentsrecursivelybyreexecutingallstatementsthatestablish
associativity.
9.4.
Dependents
Adependentcouldbeavariableoraproperty.Codebelowshowsthelatercase.
classFoo
{
x;
}
f=Foo();
m=21;
//propertyxdependsonm
f.x=m;
m=42;
//ris42
r=f.x;
Aftermisupdatedto42,assignmentstatementf.x=mwillbereexecutedtoupdateproperty
x .
9.5.
Entitiesthatcouldbedependedon
9.5.1.
Variables
Thechangeofvariablewilltriggerupdatesofitsdependents.Variablecouldappearsin
Expression
Parameters:intheformofx =f(y,z),wherexdependsonf ()andvariablesyand
z.
Listindexing:intheformofx =y[z],wherex dependsonbothvariablesy andarray
indexervariablez .
Thereisaspecialcaseforselfredefinition,i.e.,avariabledependsonitself.Forexample,a=a+
1.Thiskindofselfredefinitionwillnotremovepreviouslyestablishedassociativitybetweenaand
othervariables.Besides,thechangeofa willonlyupdateitsdependents,nota itself.Following
exampleillustratesthiscase:
1:x=1;
2:y=2;
3:x=x+y;
4:z=x+y;
5:x=x+1;
Thecodeabovewillbeexecutedasfollow:
1. x issetto1.
2. y issetto2.
3. x ischangedtox +y.Sox dependsony,xis3now.
4. z issettox +y.Soz dependsonx andy ,z is3now.
5. x isincreasedby1.Theupdateforz willbetriggered,z is4now.
Itisalsofinethatvariableappearsinfunctionparameterlist,justastheexampleinassociativity
establishmentshows.
9.5.2.
Function
Intheformof
x=f(...);
Theassignmentestablishesassociativitybetweenxandfunctionf().Anyupdateoffunctionbody
ofanyoverloadedf ()willcausethereexecutionofthisstatement.Notethisfeatureisonly
availablewhenliverunnerisenabled(whichisonlyavailableinvisualprogrammingenvironment).
9.5.3.
Properties
Intheformof
r=x.y.z;
Theassignmentestablishesassociativitybetweenrandvariablexandpropertiesyandz.Any
updateforx ,y andz willupdater .
Example:
classFoo
{
x;
constructorFoo(_x)
{
x=_x;
}
}
classBar
{
foo;
constructorBar(_x)
{
f=Foo(_x);
}
}
b=Bar(0);
t=b.foo.x;
b.foo.x=1;//updatex
b.f=Foo(2);//updatef
b=Bar(3);//updateb
Eachupdateinthelastthreestatementwillreexecutestatementt=b.foo.xtoupdatethevalue
oft .
9.6.
Associativityscope
Astheestablishmentofassociativityandupdatearebothatruntime,itisimportanttonotethatthe
associativityestablishmentandupdateshouldonlyapplytoentitiesinthesamescope;otherwisethe
resultisundefined.Iftherealreadyisanassociativity,theassociativitymayberemoved.
Therearefourundefinedcases:
1. Thedependentisdefinedinupperscopeanddependsonvariablesdefinedinthesamescope,
butassociativityisestablishedinfunction.Forexample,inbelowcode,x andy both
definedinglobalassociativelanguageblock.Theexecutionoffoo()willexecuteline5to
establishassociativitybetweenx andy .Theexpectedbehaviorofthiskindofassociativity
isundefined,thereforeupdatingy to3willnotnecessarilyupdatex astheDesignScript
virtualmachinedoesntsupporttojustexecuteline5withoutexecutingthewholefunction
f oo().
1:x=1;
2:y=2;
3:deffoo()
4:{
5:x=y;
6:return=null;
7:}
8:
9:foo();
10:y=3;//theupdateforxisundefined
2. Thedependentisdefinedinupperscopeanddependsonvariablesdefinedinthesamescope,
butassociativityisestablishedinnestedlanguageblock.Forexample,inbelowcode,x and
y bothdefinedinglobalassociativelanguageblock.Theexecutionofnestedimperative
languagewillestablishassociativitybetweenx andy atline5,buttheexpectedbehavior
ofthiskindofassociativityisundefinedaswell.
1:x=1;
2:y=2;
3:[Imperative]
4:{
5:x=y;
6:return=null;
7:}
8:y=3;//theupdateforxisundefined
3. Thedependentisdefinedinupperscopebutdependsonvariablesdefinedinfunction.For
example,x dependsonlocalvariabley inf oo().
1:x=1;
2:deffoo()
3:{
4:y=2;
5:x=y;
6:return=null;
7:}
8:foo();
9:y=3;
4. Thedependentisdefinedinupperscopebutdependsonvariablesdefinedinnestedlanguage
block.Forexample,x dependsonlocalvariabley innestedimperativelanguageblock.
1:x=1;
2:[Imperative]
3:{
4:y=2;
5:x=y;
6:return=null;
7:}
10.
Replicationandreplicationguide
10.1.
Replicationandreplicationguide
Replicationisawaytoexpressiterationinassociativelanguageblock.Itappliestoafunctioncall
whentherankofinputargumentsexceedstherankofparameters.Inotherwords,afunctionmaybe
calledmultipletimesinreplication,andthereturnvaluefromeachfunctioncallwillbeaggregated
andreturnedasalist.
Therearetwokindsofreplication:
Zipreplication:formultipleinputlists,zipreplicationisabouttakingeveryelementfromeach
listatthesamepositionandcallingthefunction;thereturnvaluefromeachfunctioncallis
aggregatedandreturnedasalist.Forexample,forinputarguments{x1,x2,...,xn}and
{y1,y2,...,yn},whencallingfunctionf
()withzipreplication,itisequivalentto{f(x1,
y1},f(x2,y2),...,f(xn,yn)}.Asthelengthsofinputargumentscouldbedifferent,zip
replicationcouldbe
Shortestzipreplication:usetheshorterlength.
Longestzipreplication:usethelongestlength,thelastelementintheshortinputlist
willberepeated.
Thedefaultzipreplicationistheshortestzipreplication;otherwiseneedtousereplication
guide
tospecifythelongestapproach.
Cartesianreplication:itisequivalenttonestedloopinimperativelanguage.Forexample,for
inputarguments {x1,x2,...,xn}and{ y1,y2,...,yn},whencallingfunctionf ()with
cartesianreplicationandthecartesianindicesare{ 0,1},whichmeanstheiterationoverthe
firstargumentisthefirstloop,andtheiterationoverthesecondargumentisthenestedloop;
itisequivalentto{f(x1,y1},f(x1,y2),...,f(x1,yn},f(x2,y1),f(x2,y2),
...,f(x2,yn),...,f(xn,y1),f(xn,y2),...,f(xn,yn)}.
Replicationguideisusedtospecifytheorderofcartesianreplicationindices;thelowerreplication
guide,theouterloop.Iftworeplicationguidesarethesamevalue,zipreplicationwillbeapplied.
ReplicationGuide=<number[L]>{<number[L]>}
Onlyintegervalueisallowedinreplicationguide.PostfixLdenotesifthereplicationiszip
replication,thenusethelongestzipreplicationstrategy.Thenumberofreplicationguidespecifiesthe
nestedlevel.Forexample,replicationguide xs<1><2>indicatestheargumentshouldbeatleastof2
dimensionalanditsnestedlevelis2;itcouldalsobeexpressedbythefollowingpseudocode:
//xs<1><2>
for(ysinxs)
{
for(yinys)
{
...
}
}
Example:
defadd(x:var,y:var)
{
return=x+y;
}
xs={1,2};
ys={3,4};
zs={5,6,7};
//usezipreplication
//r1={4,6}
r1=add(xs,ys);
//usetheshortestzipreplication
//r2={6,8};
r2=add(xs,zs);
//thelongestzipreplicationshouldbespecifiedthroughreplicationguide.
//theapplicationguidesshouldbethesamevalue;otherwisecartesian
//replicationwillbeapplied
//r3={6,8,9}
r3=add(xs<1L>,zs<1L>);
//usecartesianreplication
//r4={{4,5},{5,6}};
r4=add(xs<1>,ys<2>);
//usecartesianreplication
//r5={{4,5},{5,6}};
r5=add(xs<2>,ys<1>);
Besidesreplicationforexplicitfunctioncall,replicationandreplicationguidecouldalsobeappliedto
thefollowingexpressions:
1. Binaryoperatorslike+,,*,/andsoon.AllbinaryoperatorsinDesignScriptcanbeviewedas
afunctionwhichacceptstwoparameters,andunaryoperatorcanbeviewedasafunction
whichacceptsoneparameters.Therefore,replicationwillapplytoexpressionx s+ysif
x sandy sarelists.
2. Rangeexpression.
3. Inlineconditionalexpressionintheformofx s?ys:zswherex s,y sandz sare
lists.
4. Arrayindexing.Forexample, xs[ys]wherey sisalist.Replicationcouldapplytoarray
indexingonthebothsidesofassignmentexpression.Notereplicationdoesnotapplyto
multipleindices.
5. Memberaccessexpression.Forexample,x s.foo(ys)where xsand ysarelists.Replication
guidecouldbeappliedtoobjectsandarguments.Ifx sisalist,x sshouldbeahomogeneous
list,i.e.,allelementsinx sareofthesametype.
10.2.
Functiondispatchruleforreplicationandreplicationguide
Usingzipreplicationorcartesianreplicationtotallydependsonthespecifiedreplicationguide,the
typesofinputargumentsandthetypesofparameters.Becausetheinputargumentcouldbea
heterogenouslist,theimplementationwillcomputewhichreplicationcombinationwillgeneratethe
shortesttypeconversiondistance.
Noteifargumentisjaggedlist,thereplicationresultisundefined.
Formally,forafunctionf (x1:t1,x2:t2,...,xn:tn)andinputargumentsa1,a2,...,
an,functiondispatchruleis:
1. Getalistofoverloadedfunctionf ()withsamenumberofparameters.Thesefunctionsare
candidates.
2. Iftherearereplicationguides,theywillbeprocessedlevelbylevel.Forexample,forfunction
call f(as<1><1>,bs,cs<1><2>,ds<2><1L>),therearetwolevelsofreplicationguides.
a. Foreachlevel,sortreplicationguidesinascendantorder.Ifreplicationguideisless
thanorequalto0,thisreplicationguidewillbeskipped(itisastubreplicationguide).
i.
Foreachreplicationguide,ifitappearsinmultiplearguments,zipreplication
applies.Bydefaultusingshortestlacing.Ifanyreplicationguidenumberhas
suffixL,longestlacingapplies.
ii.
Otherwisecartesianreplicationapplies.
iii.
Repeatstepbuntilallreplicationguideshavebeenprocessed.
b. Repeatstepauntilallreplicationlevelshavebeenprocessed.
c. Forthisexample,followingreplicationswillbegenerated:
i.
Zipreplicationona s, cs
ii.
Cartesianreplicationond s
iii.
Zipreplicationona s,d s
iv.
Cartesianreplicationond s
3. Aftertheprocessingofreplicationguide,therankofeachinputargumentiscomputed:r1=
rank(a1),r2=rank(a2),...,rn=rank(an);foreachrank,updateitto r=r
<numberofreplicationguideonargument>.Thefinallist
{r1,r2,...,rn}iscalleda
reductionlist, eachreductionvaluerepresentsapossiblemaximumnestedlooponthe
correspondingargument.
4. Basedonthisreductionlist,computeacombinationofreductionlistwhoseelementvalueis
lessthanorequaltothecorrespondingreductionvalueinbasereductionlist.Foreach
reductionlist{r1,r2,...,rn},iterativelydothefollowingcomputationtogenerate
replications:
a. Forany ri>0,r i=r i1.Iftherearemultiplereductionswhosevaluesarelarger
thanorequalto1,zipreplicationapplies;otherwisecartesianreplicationapplies.
5. Combinethereplicationsgeneratedonstep3andstep4,basedontheinputargumentsand
thesignatureofcandidatefunctions,choosethebestmatchedfunctionandbestreplication
strategy.Duringtheprocess,ifthetypeofparameterandthetypeofargumentaredifferent,
thetypedistancescorewillbecalculated.
11.
Builtinfunctions
AllFalse:bool(list:var[]..[])
Checksifallelementsinthespecifiedlistarefalse.
AllTrue:bool(list:var[]..[])
Checksifallelementsinthespecifiedlistaretrue.
Average:double(list:int[]..[])
Returnsaveragevalueofallelementsinthespecifiedlist.
Break()
Notifiesdebuggertobreakatthepoint.
Concat:var[]..[](list1:var[]..[],list2:var[]..[])
Concatslist1andlist2andreturnsanewlist.
Contains:bool(list:var[]..[],element:var)
Checksifthespecifiedelementisinthespecifiedlist.
Contains:bool(list:var[]..[],element:var[]..[])
Checksifthespecifiedelementisinthespecifiedlist.
ContainsKey:bool(list:var[]..[],key:var)
Checksifthespecifiedkeyispresentinthespecifieddictionary.
Count:int(list:var[]..[])
Returnsthenumberofelementsinthespecifiedlist.
CountTrue:int(list:var[]..[])
Returnsthenumberoftruevaluesinthespecifiedlist.
CountFalse:int(list:var[]..[])
Returnsthenumberoffalsevaluesinthespecifiedlist.
Equals:bool(objectA:var,objectB:var)
Determineswhethertwoobjectinstancesareequal.
Evaluate:var[]..[](fptr:fptr,params:var[]..[],unpack:bool)
Forinternaluse.Evaluatesafunctionpointerwithspecifiedparams.
Flatten:var[](list:var[]..[])
Returnstheflattened1Dlistofthemultidimensionalinputlist.
GetElapsedTime:int()
Returnselapsedmillisecondsinthevirtualmachine
GetKeys:var[]..[](list:var[]..[])
Getsallkeysfromthespecifieddictionary.
GetValues:var[]..[](list:var[]..[])
Getsallvaluesstoredinthespecifieddictionaryandforasimplelistitreturnsallelements.
IndexOf:int(list:var[]..[],element:var[]..[])
Returnstheindexofthememberinthelist.
Insert:var[]..[](list:var[]..[],element:var,index:int)
Insertsanelementintoalistatspecifiedindex.
Insert:var[]..[](list:var[]..[],element:var[]..[],index:int)k
Insertsanelementintoalistatspecifiedindex.
IsRectangular:bool(list:var[]..[])
Checksifeachofrowsinmultidimensionallisthasthesamenumberofelements.
ImportFromCSV:double[][](filePath:string)
Importsdatafromatextfilecontainingcommaseparatedvaluesintotwodimensionallist.
ImportFromCSV:double[][](filePath:string,transpose:bool)
Importsdatafromatextfilecontainingcommaseparatedvaluesintotwodimensionallistand
alsotransposetheoutputlistifspecified.
IsHomogeneous:bool(list:var[]..[])
Checksifalltheelementsinthespecifiedlistareofthesametype.
IsUniformDepth:bool(list:var[]..[])
Checksifthelisthasauniformdepth.
Map:double(rangeMin:double,rangeMax:double,inputValue:double)
Mapsavalueintoaninputrange.
MapTo:double(rangeMin:double,rangeMax:double,inputValue:double,
targetRangeMin:double,targetRangeMax:double)
Mapsavaluefromonerangetoanotherrange.
NormalizeDepth:var[]..[](list:var[]..[])
Returnsalistwithuniformdepthasspecifiedbytheinputdepth.
NormalizeDepth:var[]..[](list:var[]..[],rank:var)
Returnmultidimensionallistaccordingtotherankgiven.
Print(msg:var)
Printmsgtotheconsole.
Rank(list:var[]..[])
Countsthemaximalrankofthespecifiedlist.
Remove:var(list:var[]..[],index:int)
Removeselementatthespecifiedindexofthelist.
RemoveDuplicates:var[]..[](list:var[]..[])
Removesduplicateelementsinthespecifiedlist.
RemoveNulls:var[]..[](list:var[]..[])
Removesnullelementsfromthespecifiedlist.
RemoveIfNot:var[]..[](list:var[]..[],type:string)
Removesthemembersofthelistwhicharenotmembersofthespecifiedtype.
RemoveKey:bool(list:var[]..[],key:var)
Returnstrueifthespecifiedkeyisremovedfromthespecifiedlist;otherwisereturnsfalse.
Reorder:var[](list:var[],indice:var[])
Reordersthelistusingthespecifiedindices.
Reverse:var[]..[](list:var[]..[])
Reversesthespecifiedlist.
SetDifference:var[](list1:var[],list2:var[])
Returnsobjectsthatareincludedinlist1butnotexcludedinlist2
SetIntersection:var[](list1:var[],list2:var[])
Producesthesetintersectionoftwolists.
SetUnion:var[](list1:var[],list2:var[])
Producesthesetunionoftwosequencesbyusingthedefaultequalitycomparer.
Sleep(x:int)
Putthevirtualmachinetosleepforxmilliseconds.
SomeFalse:bool(list:var[]..[])
Returnstrueifanyelementinthelistisfalse
SomeNulls:bool(list:var[]..[])
Returnstrueifanyelementinthelistisnull.
SomeTrue:bool(list:var[]..[])
Returnstrueifanyelementinthelististrue.
Sort:int[](list:int[])
Obsolete.
SortIndexByValue:int[](list:double[])
Sortsaspecifiedlistbyvaluesofitsmembersinascendingorder.
SortIndexByValue:int[](list:double[],ascending:bool)
Sortsaspecifiedlistbyvaluesofitsmembersineitherdescendingorascendingorder.
Sum:int(list:int[]..[])
Returnsthesumofallelementsinthespecifiedlist.
ToString:string(object:var[]..[])
Obsolete.Use_ _ToStringFromObject()or_ _ToStringFromArray()instead.Returnsobject
instringrepresentation.
Transpose:var[]..[](list:var[]..[])
Swapsrowsandcolumnsinalistoflists.Iftherearesomerowsthatareshorterthanothers,
nullvaluesareinsertedasplaceholdersintheresultlistsuchthatitisalwaysrectangular.
__GC()
Forcegarbagecollection.
__ToStringFromObject:string(object:var)
Returnsobjectinstringrepresentation.
__ToStringFromArray:string(list:var[])
Returnslistinstringrepresentation.
__TryGetValueFromNestedDictionaries:var[]..[](list:var[]..[],key:var[]..[])
Recursivelyiteratealldictionaryelementsinthespecifiedlistandreturnsvaluesassociated
withthespecifiedkey.