Generating Statement Collections

Applies to TestComplete 14.40, last modified on April 22, 2021

In most cases, you will need to generate code snippets that consist of several statements rather than a single statement. To make it easier to generate the code of statement blocks, you can create a collection of the appropriate syntax object. In this case, you will be able to generate the entire code block at once.

To create a collection of code statements, do the following:

  • Create a CollectionSyntax object using the Syntax.CreateCollection method.

  • Create syntax objects corresponding to the desired statements and use the Add method of the CollectionSyntax object to add those statements to the collection.

After populating the collection, you can pass the resulting CollectionSyntax object to the Syntax.GenerateSource method to generate the appropriate code block. Statement collections can also be used as part of conditional statements (see Generating Conditional Statements).

The example below illustrates the usage of syntax collections. It generates a code block that consists of a variable declaration statement and an assignment statement:

JScript

function ShowCollection()
{
  var oColl = Syntax.CreateCollection();

  var oVarDef = Syntax.CreateVarDef("MyVar");

  oColl.Add(oVarDef)

  var oVarName = Syntax.CreateInvoke();
  oVarName.InvokeName = "MyVar";
  oVarName.IsProperty = true;

  var oAssignment = Syntax.CreateAssign();
  oAssignment.Left = oVarName;
  oAssignment.Right = 42;

  oColl.Add(oAssignment);

  var strCode = Syntax.GenerateSource(oColl);
  aqDlg.ShowMessage(strCode);
}

VBScript

Sub ShowCollection
  Dim oColl, oVarDef, oVarName, oAssignment, strCode

  Set oColl = Syntax.CreateCollection

  Set oVarDef = Syntax.CreateVarDef("MyVar")

  oColl.Add oVarDef

  Set oVarName = Syntax.CreateInvoke
  oVarName.InvokeName = "MyVar"
  oVarName.IsProperty = True

  Set oAssignment = Syntax.CreateAssign
  oAssignment.Left = oVarName
  oAssignment.Right = 42

  oColl.Add oAssignment

  strCode = Syntax.GenerateSource(oColl)
  aqDlg.ShowMessage strCode
End Sub

The generated code is as follows:

JavaScript, JScript

var MyVar;
MyVar = 42;

Python

MyVar = 42

VBScript

Dim MyVar
MyVar = 42

DelphiScript

var MyVar;
MyVar := 42;

C++Script, C#Script

var MyVar;
MyVar = 42;

See Also

Generating Script Code
CollectionSyntax Object
CreateCollection Method

Highlight search results