RascalTutor
Synopsis

The available Rascal libraries.

Description

The libraries described here provide the following functionality:

  • Prelude: The Rascal standard prelude.

  • Vis: Functions for creating visualisations.

  • analysis: Library functions for analysis tasks.

  • lang: Definitions and tools for various languages.

  • util: Utilities: functions, data types and interfaces with external libraries.

1. Prelude

Synopsis

The Rascal standard prelude.

Description

The Prelude library provides core functionality for handling all of Rascal’s data-types. See the Rascal Language Reference for details of the language Rascal itself.

For

Prelude provides the following:

  • Boolean: Library functions for Booleans.

  • DateTime: Library functions for date and time.

  • Exception: Exceptions thrown by the Rascal run-time.

  • IO: Library functions for input/output.

  • List: Library functions for lists.

  • ListRelation: Library functions for list relations.

  • Map: Library functions for maps.

  • Message: A Message datatype that represents messages in the IDE.

  • Node: Library functions for nodes.

  • ParseTree: Library functions for parse trees.

  • Relation: Library functions for relations.

  • Set: Library functions for sets.

  • String: Library functions for strings.

  • Type: Rascal’s type system, implemented in Rascal itself.

  • ValueIO: Library functions for reading and writing values in textual and binary format.

Benefits

This library makes it possible to import all core Rascal functionality with a single import.

Pitfalls
  • The prelude may contain more functionality than you need; this leads to an unnecessary longer import and pollution of your name space.

  • The precise contents of the prelude are under discussion.

  • In the future, Rascal may automatically load the prelude.

1.1. Boolean

Usage

import Boolean;

Synopsis

Library functions for Booleans.

Description

For operators on Boolean values see Boolean in the Rascal Language Reference.

The following functions are defined for Booleans:

  • arbBool: Return an arbitrary Boolean value.

  • fromString: Convert the strings "true" or "false" to a bool

  • toInt: Convert a Boolean value to integer.

  • toReal: Convert Boolean value to real.

  • toString: Convert Boolean value to string.

1.1.1. arbBool

Function

bool arbBool()

Synopsis

Return an arbitrary Boolean value.

Examples
rascal>import Boolean;
ok
rascal>arbBool();
bool: false
rascal>arbBool();
bool: true
rascal>arbBool();
bool: true
Benefits

arbInt is a convenient generator for arbitrary binary choices.

1.1.2. fromString

Function

bool fromString(str s)

Synopsis

Convert the strings "true" or "false" to a bool.

1.1.3. toInt

Function

int toInt(bool b)

Synopsis

Convert a Boolean value to integer.

Description

Maps true to 1 and false to 0.

Examples
rascal>import Boolean;
ok
rascal>toInt(true);
int: 1
rascal>toInt(false);
int: 0

1.1.4. toReal

Function

real toReal(bool b)

Synopsis

Convert Boolean value to real.

Description

Maps true to 1.0 and false to 0.0.

Examples
rascal>import Boolean;
ok
rascal>toReal(true);
real: 1.0
rascal>toReal(false);
real: 0.0

1.1.5. toString

Function

str toString(bool b)

Synopsis

Convert Boolean value to string.

Description

Maps true to "true" and false to "false".

Examples
rascal>import Boolean;
ok
rascal>toString(true);
str: "true"
rascal>toString(false);
str: "false"

1.2. DateTime

Usage

import DateTime;

Synopsis

Library functions for date and time.

Description

For operators on datetime see DateTime in the Rascal Language Reference.

The following functions are defined for datetime:

1.2.1. now

Function

datetime now()

Synopsis

Get the current datetime.

Examples
rascal>import DateTime;
ok
rascal>now();
datetime: $2017-06-22T09:32:23.035+00:00$

1.2.2. createDate

Function

datetime createDate(int year, int month, int day)

Synopsis

Create a new date.

Examples
rascal>import DateTime;
ok
rascal>createDate(2012,1,1);
datetime: $2012-01-01$

1.2.3. createTime

Function
  • datetime createTime(int hour, int minute, int second, int millisecond)

  • datetime createTime(int hour, int minute, int second, int millisecond, int timezoneHourOffset, int timezoneMinuteOffset)

Synopsis

Create a new time (with optional timezone offset).

Examples
rascal>import DateTime;
ok
rascal>createTime(8,15,30,55);
datetime: $T08:15:30.055+01:00$
rascal>createTime(8,15,30,55,2,0);
datetime: $T08:15:30.055+02:00$

1.2.4. createDateTime

Function
  • datetime createDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond)

  • datetime createDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int timezoneHourOffset, int timezoneMinuteOffset)

Synopsis

Create a new datetime (with optional timezone offset).

Examples
rascal>import DateTime;
ok
rascal>createDateTime(2012,1,1,8,15,30,55);
datetime: $2012-01-01T08:15:30.055+01:00$
rascal>createDateTime(2012,1,1,8,15,30,55,2,0);
datetime: $2012-01-01T08:15:30.055+02:00$

1.2.5. joinDateAndTime

Function

datetime joinDateAndTime(datetime date, datetime time)

Synopsis

Create a new datetime by combining a date and a time.

Examples
rascal>import DateTime;
ok
rascal>D = createDate(2012, 1, 1);
datetime: $2012-01-01$
rascal>T = createTime(8, 15, 45, 30);
datetime: $T08:15:45.030+01:00$
rascal>joinDateAndTime(D, T);
datetime: $2012-01-01T08:15:45.030+01:00$

1.2.6. splitDateTime

Function

tuple[datetime date, datetime time] splitDateTime(datetime dt)

Synopsis

Split an existing datetime into a tuple with the date and the time.

Examples
rascal>import DateTime;
ok
rascal>N = now();
datetime: $2017-06-22T09:32:24.010+00:00$
rascal>splitDateTime(N);
tuple[datetime,datetime]: <$2017-06-22$,$T09:32:24.010+00:00$>

1.2.7. incrementYears

Function
  • datetime incrementYears(datetime dt, int n)

  • datetime incrementYears(datetime dt)

Synopsis

Increment the years by given amount or by 1.

Examples
rascal>import DateTime;
ok
rascal>N = now();
datetime: $2017-06-22T09:32:24.234+00:00$
rascal>incrementYears(N);
datetime: $2018-06-22T09:32:24.234+00:00$
rascal>incrementYears(N, 5);
datetime: $2022-06-22T09:32:24.234+00:00$

1.2.8. incrementMonths

Function
  • datetime incrementMonths(datetime dt, int n)

  • datetime incrementMonths(datetime dt)

Synopsis

Increment the months by a given amount or by 1. .Function

Examples
rascal>import DateTime;
ok
rascal>N = now();
datetime: $2017-06-22T09:32:24.563+00:00$
rascal>incrementMonths(N);
datetime: $2017-07-22T09:32:24.563+00:00$
rascal>incrementMonths(N, 5);
datetime: $2017-11-22T09:32:24.563+00:00$

1.2.9. incrementDays

Function
  • datetime incrementDays(datetime dt, int n)

  • datetime incrementDays(datetime dt)

Synopsis

Increment the days by given amount or by 1.

Examples
rascal>import DateTime;
ok
rascal>N = now();
datetime: $2017-06-22T09:32:24.827+00:00$
rascal>incrementDays(N);
datetime: $2017-06-23T09:32:24.827+00:00$
rascal>incrementDays(N, 5);
datetime: $2017-06-27T09:32:24.827+00:00$

1.2.10. incrementHours

Function
  • datetime incrementHours(datetime dt, int n)

  • datetime incrementHours(datetime dt)

Synopsis

Increment the hours by a given amount or by 1.`

Examples
rascal>import DateTime;
ok
rascal>N = now();
datetime: $2017-06-22T09:32:25.117+00:00$
rascal>incrementHours(N);
datetime: $2017-06-22T10:32:25.117+00:00$
rascal>incrementHours(N, 5);
datetime: $2017-06-22T14:32:25.117+00:00$

1.2.11. incrementMinutes

Function
  • datetime incrementMinutes(datetime dt, int n)

  • datetime incrementMinutes(datetime dt)

Synopsis

Increment the minutes by a given amount or by 1.

Examples
rascal>import DateTime;
ok
rascal>N = now();
datetime: $2017-06-22T09:32:25.382+00:00$
rascal>incrementMinutes(N);
datetime: $2017-06-22T09:33:25.382+00:00$
rascal>incrementMinutes(N, 5);
datetime: $2017-06-22T09:37:25.382+00:00$

1.2.12. incrementSeconds

Function
  • datetime incrementSeconds(datetime dt, int n)

  • datetime incrementSeconds(datetime dt)

Synopsis

Increment the seconds by a given amount or by 1.

Examples
rascal>import DateTime;
ok
rascal>N = now();
datetime: $2017-06-22T09:32:25.652+00:00$
rascal>incrementSeconds(N);
datetime: $2017-06-22T09:32:26.652+00:00$
rascal>incrementSeconds(N, 5);
datetime: $2017-06-22T09:32:30.652+00:00$

1.2.13. incrementMilliseconds

Function
  • datetime incrementMilliseconds(datetime dt, int n)

  • datetime incrementMilliseconds(datetime dt)

Synopsis

Increment the milliseconds by a given amount or by 1.

Examples
rascal>import DateTime;
ok
rascal>N = now();
datetime: $2017-06-22T09:32:25.909+00:00$
rascal>incrementMilliseconds(N);
datetime: $2017-06-22T09:32:25.910+00:00$
rascal>incrementMilliseconds(N, 5);
datetime: $2017-06-22T09:32:25.914+00:00$

1.2.14. decrementYears

Function
  • datetime decrementYears(datetime dt, int n)

  • datetime decrementYears(datetime dt)

Synopsis

Decrement the years by a given amount or by 1.

Examples
rascal>import DateTime;
ok
rascal>N = now();
datetime: $2017-06-22T09:32:26.210+00:00$
rascal>decrementYears(N);
datetime: $2016-06-22T09:32:26.210+00:00$
rascal>decrementYears(N, 5);
datetime: $2012-06-22T09:32:26.210+00:00$

1.2.15. decrementMonths

Function
  • datetime decrementMonths(datetime dt, int n)

  • datetime decrementMonths(datetime dt)

Synopsis

Decrement the months by a given amount or by 1.

Examples
rascal>import DateTime;
ok
rascal>N = now();
datetime: $2017-06-22T09:32:26.482+00:00$
rascal>decrementMonths(N);
datetime: $2017-05-22T09:32:26.482+00:00$
rascal>decrementMonths(N, 5);
datetime: $2017-01-22T09:32:26.482+00:00$

1.2.16. decrementDays

Function
  • datetime decrementDays(datetime dt, int n)

  • datetime decrementDays(datetime dt)

Synopsis

Decrement the days by a given amount or by 1.

Examples
rascal>import DateTime;
ok
rascal>N = now();
datetime: $2017-06-22T09:32:26.763+00:00$
rascal>decrementDays(N);
datetime: $2017-06-21T09:32:26.763+00:00$
rascal>decrementDays(N, 3);
datetime: $2017-06-19T09:32:26.763+00:00$

1.2.17. decrementHours

Function
  • datetime decrementHours(datetime dt, int n)

  • datetime decrementHours(datetime dt)

Synopsis

Decrement the hours by a given amount or by 1.

Examples
rascal>import DateTime;
ok
rascal>N = now();
datetime: $2017-06-22T09:32:27.020+00:00$
rascal>decrementHours(N);
datetime: $2017-06-22T08:32:27.020+00:00$
rascal>decrementHours(N, 5);
datetime: $2017-06-22T04:32:27.020+00:00$

1.2.18. decrementMinutes

Function
  • datetime decrementMinutes(datetime dt, int n)

  • datetime decrementMinutes(datetime dt)

Synopsis

Decrement the minutes by a given amount or by 1.

Examples
rascal>import DateTime;
ok
rascal>N = now();
datetime: $2017-06-22T09:32:27.302+00:00$
rascal>decrementMinutes(N);
datetime: $2017-06-22T09:31:27.302+00:00$
rascal>decrementMinutes(N, 5);
datetime: $2017-06-22T09:27:27.302+00:00$

1.2.19. decrementSeconds

Function
  • datetime decrementSeconds(datetime dt, int n)

  • datetime decrementSeconds(datetime dt)

Synopsis

Decrement the seconds by a given amount or by 1.

Examples
rascal>import DateTime;
ok
rascal>N = now();
datetime: $2017-06-22T09:32:27.561+00:00$
rascal>decrementSeconds(N);
datetime: $2017-06-22T09:32:26.561+00:00$
rascal>decrementSeconds(N, 5);
datetime: $2017-06-22T09:32:22.561+00:00$

1.2.20. decrementMilliseconds

Function
  • datetime decrementMilliseconds(datetime dt, int n)

  • datetime decrementMilliseconds(datetime dt)

Synopsis

Decrement the milliseconds by a given amount or by 1.

Examples
rascal>import DateTime;
ok
rascal>N = now();
datetime: $2017-06-22T09:32:27.822+00:00$
rascal>decrementMilliseconds(N);
datetime: $2017-06-22T09:32:27.821+00:00$
rascal>decrementMilliseconds(N, 5);
datetime: $2017-06-22T09:32:27.817+00:00$

1.2.21. interval

Types
data interval
      = Interval(datetime begin, datetime end)
      ;
Synopsis

A closed interval on the time axis.

1.2.22. createInterval

Function

interval createInterval(datetime begin, datetime end)

Synopsis

Given two datetime values, create an interval.

Examples
rascal>import DateTime;
ok
rascal>B = now();
datetime: $2017-06-22T09:32:28.097+00:00$
rascal>E = incrementDays(B, 2);
datetime: $2017-06-24T09:32:28.097+00:00$
rascal>createInterval(B, E);
interval: Interval($2017-06-22T09:32:28.097+00:00$,$2017-06-24T09:32:28.097+00:00$)

1.2.23. Duration

Types
data Duration
      = duration(int years, int months, int days, int hours, int minutes, int seconds, int milliseconds)
      ;
Synopsis

A duration of time, measured in individual years, months, etc.

1.2.24. createDurationInternal

Function

tuple[int,int,int,int,int,int,int] createDurationInternal(datetime begin, datetime end)

1.2.25. createDuration

Function
  • Duration createDuration(datetime begin, datetime end)

  • Duration createDuration(interval i)

Synopsis

Create a new duration representing the duration between the begin and end dates.

Examples
rascal>import DateTime;
ok
rascal>B = now();
datetime: $2017-06-22T09:32:28.408+00:00$
rascal>E1 = incrementHours(B);
datetime: $2017-06-22T10:32:28.408+00:00$
rascal>createDuration(B, E1);
Duration: duration(0,0,0,1,0,0,0)
rascal>E2 = incrementMinutes(B);
datetime: $2017-06-22T09:33:28.408+00:00$
rascal>createDuration(B, E2);
Duration: duration(0,0,0,0,1,0,0)

1.2.26. daysInInterval

Function

int daysInInterval(interval i)

Synopsis

Return the number of days in an interval, including the begin and end days.

Examples
rascal>import DateTime;
ok
rascal>B = now();
datetime: $2017-06-22T09:32:28.892+00:00$
rascal>E = incrementDays(B, 2);
datetime: $2017-06-24T09:32:28.892+00:00$
rascal>I = createInterval(B, E);
interval: Interval($2017-06-22T09:32:28.892+00:00$,$2017-06-24T09:32:28.892+00:00$)
rascal>daysInInterval(I);
int: 2

1.2.27. daysDiff

Function

int daysDiff(datetime begin, datetime end)

Synopsis

Return the difference between two dates and/or datetimes in days.

Examples
rascal>import DateTime;
ok
rascal>B = now();
datetime: $2017-06-22T09:32:29.316+00:00$
rascal>E = incrementDays(B, 2);
datetime: $2017-06-24T09:32:29.316+00:00$
rascal>daysDiff(B, E);
int: 2

1.2.28. dateRangeByDay

Function

list[datetime] dateRangeByDay(interval i)

Synopsis

Given an interval, return a list of days.

Description

Given an interval i, return a list of days [i.begin, …​, i.end].

Examples
rascal>import DateTime;
ok
rascal>B = now();
datetime: $2017-06-22T09:32:29.630+00:00$
rascal>E = incrementDays(B, 2);
datetime: $2017-06-24T09:32:29.630+00:00$
rascal>I = createInterval(B, E);
interval: Interval($2017-06-22T09:32:29.630+00:00$,$2017-06-24T09:32:29.630+00:00$)
rascal>//dateRangeByDay(I);
[red]##Parse error##

1.2.29. parseDate

Function

datetime parseDate(str inputDate, str formatString)

Synopsis

Parse an input date given as a string using the given format string.

Examples
rascal>import DateTime;
ok
rascal>parseDate("2011-12-23", "yyyy-MM-dd");
datetime: $2011-12-23$
rascal>parseDate("20111223", "yyyyMMdd");
datetime: $2011-12-23$

1.2.30. parseDateInLocale

Function

datetime parseDateInLocale(str inputDate, str formatString, str locale)

Synopsis

Parse an input date given as a string using a specific locale and format string.

1.2.31. parseTime

Function

datetime parseTime(str inputTime, str formatString)

Synopsis

Parse an input time given as a string using the given format string.

Examples
rascal>import DateTime;
ok
rascal>parseTime("11/21/19", "HH/mm/ss");
datetime: $T11:21:19.000+01:00$

1.2.32. parseTimeInLocale

Function

datetime parseTimeInLocale(str inputTime, str formatString, str locale)

Synopsis

Parse an input time given as a string using a specific locale and format string.

1.2.33. parseDateTime

Function

datetime parseDateTime(str inputDateTime, str formatString)

Synopsis

Parse an input datetime given as a string using the given format string.

Examples
rascal>import DateTime;
ok
rascal>parseDateTime("2011/12/23/11/19/54", "YYYY/MM/dd/HH/mm/ss");
datetime: $2010-12-26T11:19:54.000+01:00$

1.2.34. parseDateTimeInLocale

Function

datetime parseDateTimeInLocale(str inputDateTime, str formatString, str locale)

Synopsis

Parse an input datetime given as a string using a specific locale and format string.

1.2.35. printDate

Function
  • str printDate(datetime inputDate, str formatString)

  • str printDate(datetime inputDate)

Synopsis

Print an input date using the given format string.

Examples
rascal>import DateTime;
ok
rascal>printDate(now());
str: "2017-06-22"
rascal>printDate(now(), "YYYYMMdd");
str: "20170622"

1.2.36. printDateInLocale

Function
  • str printDateInLocale(datetime inputDate, str formatString, str locale)

  • str printDateInLocale(datetime inputDate, str locale)

Synopsis

Print an input date using a specific locale and format string.

Examples
rascal>import DateTime;
ok
rascal>printDateInLocale(now(), "Europe/Netherlands");
str: "2017-06-22"
rascal>printDateInLocale(now(), "French");
str: "2017-06-22"

1.2.37. printTime

Function
  • str printTime(datetime inputTime, str formatString)

  • str printTime(datetime inputTime)

Synopsis

Print an input time using the given format string.

Examples
rascal>import DateTime;
ok
rascal>N = now();
datetime: $2017-06-22T09:32:30.786+00:00$
rascal>printTime(N);
str: "09:32:30.786+0000"
rascal>printTime(N, "HH/mm/ss");
str: "09/32/30"

1.2.38. printTimeInLocale

Function
  • str printTimeInLocale(datetime inputTime, str formatString, str locale)

  • str printTimeInLocale(datetime inputTime, str locale)

Synopsis

Print an input time using a specific locale and format string.

1.2.39. printDateTime

Function
  • str printDateTime(datetime inputDateTime, str formatString)

  • str printDateTime(datetime inputDateTime)

Synopsis

Print an input datetime using the given format string.

Examples
rascal>import DateTime;
ok
rascal>N = now();
datetime: $2017-06-22T09:32:31.057+00:00$
rascal>printDateTime(N);
str: "2017-06-22 09:32:31.057+0000"
rascal>printDateTime(N, "yyyy-MM-dd\'T\'HH:mm:ss.SSSZZ");
str: "2017-06-22T09:32:31.057+0000"
rascal>printDateTime(N, "YYYY/MM/dd/HH/mm/ss");
str: "2017/06/22/09/32/31"

1.2.40. printDateTimeInLocale

Function
  • str printDateTimeInLocale(datetime inputDateTime, str formatString, str locale)

  • str printDateTimeInLocale(datetime inputDateTime, str locale)

Synopsis

Print an input datetime using a specific locale and format string.

1.3. Exception

Usage

import Exception;

Synopsis

Exceptions thrown by the Rascal run-time.

1.3.1. RuntimeException

Types
data RuntimeException
      = Ambiguity(loc location, str nonterminal, str sentence)
      | ArithmeticException(str message)
      | AssertionFailed()
      | AssertionFailed(str label)
      | EmptyList()
      | EmptyMap()
      | EmptySet()
      | IndexOutOfBounds(int index)
      | IllegalArgument()
      | IllegalArgument(value v)
      | IllegalArgument(value v, str message)
      | InvalidArgument()
      | InvalidArgument(value v)
      | InvalidArgument(value v, str message)
      | InvalidURI(str uri)
      | InvalidUseOfDate(str message)
      | InvalidUseOfLocation(str message)
      | InvalidUseOfTime(str message)
      | IO(str message)
      | Java(str class, str message)
      | Java(str class, str message, RuntimeException cause)
      | JavaException(str class, str message)
      | JavaException(str class, str message, RuntimeException cause)
      | ModuleNotFound(str name)
      | NoMainFunction()
      | NoSuchAnnotation(str label)
      | NoSuchField(str name)
      | NoSuchKey(value key)
      | NotImplemented(str message)
      | MultipleKey(value key)
      | ParseError(loc location)
      | PathNotFound(loc l)
      | PathNotFound(set[loc] locs)
      | RegExpSyntaxError(str message)
      | StackOverflow()
      | UnavailableInformation(str message)
      | ImplodeError(str message)
      | NoSuchElement(value v)
      | PermissionDenied()
      | PermissionDenied(str message)
      | Timeout()
      ;
Synopsis

The Exception datatype used in all Rascal exceptions.

Description

Since declarations for ADTs are extensible, the user can add new exceptions when needed.

Exceptions are either generated by the Rascal run-time (e.g., IndexOutOfBounds) or they are generated by a throw. Exceptions can be caught with a try catch.

Examples

Import relevant libraries:

rascal>import Exception;
ok
rascal>import IO;
ok

Define the map weekend and do a subscription with a non-existing key:

rascal>weekend = ("saturday": 1, "sunday": 2);
map[str, int]: ("sunday":2,"saturday":1)
rascal>weekend["monday"];
Exception [debugger cannot break at null frame]: NoSuchKey("monday")

Repeat this, but catch the exception. We use variable N to track what happened:

rascal>N = 1;
int: 1
rascal>try {
>>>>>>>   N = weekend["monday"];
>>>>>>>} catch NoSuchKey(v):
>>>>>>>  N = 100;
int: 100
rascal>println(N);
1

1.4. IO

Usage

import IO;

Synopsis

Library functions for input/output.

Description

The following input/output functions are defined:

  • registerLocations: register a logical file scheme including the resolution method via a table.

  • unregisterLocations: undo the effect of [registerLocations]

  • resolveLocation:

  • appendToFile: Append a value to a file.

  • appendToFileEnc: Append a value to a file.

  • charsets: Returns all available character sets

  • canEncode: Returns whether this charset can be used for encoding (use with writeFile

  • bprintln: Print a value and return true.

  • exists: Check whether a given location exists.

  • find: Find a named file in a list of locations.

  • isDirectory: Check whether a given location is a directory.

  • iprint: Print an indented representation of a value.

  • iprintToFile: Print an indented representation of a value to the specified location.

  • iprintExp: Print an indented representation of a value and returns the value as result.

  • iprintlnExp: Print an indented representation of a value followed by a newline and returns the value as result.

  • iprintln: Print a indented representation of a value and add a newline at the end.

  • isFile: Check whether a given location is actually a file (and not a directory).

  • lastModified: Last modification date of a location.

  • listEntries: List the entries in a directory.

  • mkDirectory: Create a new directory.

  • print: Print a value without subsequent newline.

  • printExp: Print a value and return it as result.

  • printExp:

  • println: Print a value to the output stream and add a newline.

  • println:

  • printlnExp: Print a value followed by a newline and return it as result.

  • printlnExp:

  • rprint: Raw print of a value.

  • rprintln: Raw print of a value followed by newline.

  • readFile: Read the contents of a location and return it as string value.

  • readFileEnc: Read the contents of a location and return it as string value.

  • readFileBytes: Read the contents of a file and return it as a list of bytes

  • readFileLines: Read the contents of a file location and return it as a list of strings.

  • readFileLinesEnc: Read the contents of a file location and return it as a list of strings.

  • remove:

  • writeFile: Write values to a file.

  • writeFileBytes: Write a list of bytes to a file

  • writeFileEnc: Write values to a file.

  • touch: Changes the last modification date of a file

  • md5HashFile: Read the contents of a location and return its MD5 hash.

  • createLink:

  • toBase64:

  • copyFile:

  • copyDirectory:

1.4.1. registerLocations

Function

void registerLocations(str scheme, str authority, map[loc logical, loc physical] m)

Synopsis

register a logical file scheme including the resolution method via a table.

Description

Logical source location schemes, such as |java+interface://JRE/java/util/List| are used for precise qualified names of artifacts while abstracting from their physical location in a specific part of a file on disk or from some webserver or source repository location.

Using this function you can create your own schemes. The authority field is used for scoping the names you wish to resolve to certain projects. This way one name can resolve to different locations in different projects.

Benefits
  • Logical source locations are supported by IDE features such as hyperlinks

  • Logical source locations are supported by all IO functions as well

Pitfalls
  • repeated calls to registerLocations for the same scheme and authority will overwrite the m map.

  • the registry is an intentional memory leak; so make sure you use it wisely.

  • when the files references by the physical locations are being written to (edited, removed), then you may expect problems. The registry is not automatically invalidated.

1.4.2. unregisterLocations

Function

void unregisterLocations(str scheme, str authority)

Synopsis

undo the effect of [registerLocations]

Description

For debugging or for memory management you may wish to remove a lookup table.

1.4.3. resolveLocation

Function

loc resolveLocation(loc l)

1.4.4. appendToFile

Function

void appendToFile(loc file, value V…​) throws PathNotFound(loc file), IO(str msg)

Synopsis

Append a value to a file.

Description

Append a textual representation of some values to an existing or a newly created file:

  • If a value is a simple string, the quotes are removed and the contents are de-escaped.

  • If a value has a non-terminal type, the parse tree is unparsed to produce a value.

  • All other values are printed as-is.

  • Each value is terminated by a newline character.

Encoding

The existing file can be stored using any character set possible, if you know the character set, please use appendToFileEnc. Else the same method of deciding the character set is used as in readFile.

Pitfalls
  • The same encoding pitfalls as the readFile function.

1.4.5. appendToFileEnc

Function

void appendToFileEnc(loc file, str charset, value V…​) throws PathNotFound(loc file), IO(str msg)

Synopsis

Append a value to a file.

Description

Append a textual representation of some values to an existing or a newly created file:

  • If a value is a simple string, the quotes are removed and the contents are de-escaped.

  • If a value has a non-terminal type, the parse tree is unparsed to produce a value.

  • All other values are printed as-is.

  • Each value is terminated by a newline character.

Files are encoded using the charset provided.

1.4.6. charsets

Function

set[str] charsets()

Synopsis

Returns all available character sets.

1.4.7. canEncode

Function

set[str] canEncode(str charset)

Synopsis

Returns whether this charset can be used for encoding (use with writeFile)

1.4.8. bprintln

Function

bool bprintln(value arg)

Synopsis

Print a value and return true.

Description

Print a value and return true. This is useful for debugging complex Boolean expressions or comprehensions. The only difference between this function and println is that its return type is bool rather than void.

Examples
rascal>import IO;
ok
rascal>bprintln("Hello World");
Hello World

1.4.9. exists

Function

bool exists(loc file)

Synopsis

Check whether a given location exists.

Description

Check whether a certain location exists, i.e., whether an actual file is associated with it.

Examples
rascal>import IO;
ok

Does the library file IO.rsc exist?

rascal>exists(|std:///IO.rsc|);
bool: true

1.4.10. find

Function

loc find(str name, list[loc] path) throws PathNotFound

Synopsis

Find a named file in a list of locations.

Examples
rascal>import IO;
ok

Find the file IO.rsc in the standard library:

rascal>find("IO.rsc", [|std:///|]);
loc: |std:///IO.rsc|

1.4.11. isDirectory

Function

bool isDirectory(loc file)

Synopsis

Check whether a given location is a directory.

Description

Check whether the location file is a directory.

1.4.12. iprint

Function

void iprint(value arg, int lineLimit = 1000)

Synopsis

Print an indented representation of a value.

Description

See [IO-iprintExp] for a version that returns its argument as result and iprintln for a version that adds a newline and [IO-iprintToFile] for a version that prints to a file.

Examples
rascal>import IO;
ok
rascal>iprint(["fruits", ("spider" : 8, "snake" : 0), [10, 20, 30]]);
[
  "fruits",
  ("snake":0,"spider":8),
  [10,20,30]
]----

[[IO-iprintToFile]]
## iprintToFile

.Function
`void iprintToFile(loc file, value arg)`

.Synopsis
Print an indented representation of a value to the specified location.

.Description
See <<IO-iprint>> for a version that displays the result on the console
and <<IO-iprintExp>> for a version that returns its argument as result
and <<IO-iprintln>> for a version that adds a newline.

.Examples

[source,rascal-shell]

rascal>import IO; ok rascal>iprintToFile(|file:///tmp/fruits.txt|, ["fruits", ("spider" : 8, "snake" : 0), [10, 20, 30]]); ok

[[IO-iprintExp]]
## iprintExp

.Function
`&T iprintExp(&T v)`

.Synopsis
Print an indented representation of a value and returns the value as result.

.Description
See <<IO-iprintlnExp>> for a version that adds a newline.

.Examples

[source,rascal-shell]

rascal>import IO; ok rascal>iprintExp(["fruits", ("spider" : 8, "snake" : 0), [10, 20, 30]]); [ "fruits", ("snake":0,"spider":8), [10,20,30] ]----

1.4.13. iprintlnExp

Function

&T iprintlnExp(&T v)

Synopsis

Print an indented representation of a value followed by a newline and returns the value as result.

Description

See [IO-iprintExp] for a version that does not add a newline.

Examples
rascal>import IO;
ok
rascal>iprintlnExp(["fruits", ("spider" : 8, "snake" : 0), [10, 20, 30]]);
[
  "fruits",
  ("snake":0,"spider":8),
  [10,20,30]
]

1.4.14. iprintln

Function

void iprintln(value arg, int lineLimit = 1000)

Synopsis

Print a indented representation of a value and add a newline at the end.

Description

See iprintlnExp for a version that returns its argument as result and iprint for a version that does not add a newline.

By default we only print the first 1000 lines, if you want to print larger values, either use writeTextValueFile or change the limit with the lineLimit parameter.

Examples
rascal>import IO;
ok
rascal>iprintln(["fruits", ("spider" : 8, "snake" : 0), [10, 20, 30]]);
[
  "fruits",
  ("snake":0,"spider":8),
  [10,20,30]
]
rascal>iprintln([ {"hi"} | i <- [0..1000]], lineLimit = 10);
[
  {"hi"},
  {"hi"},
  {"hi"},
  {"hi"},
  {"hi"},
  {"hi"},
  {"hi"},
  {"hi"},
  {"hi"},
...

1.4.15. isFile

Function

bool isFile(loc file)

Synopsis

Check whether a given location is actually a file (and not a directory).

Description

Check whether location file is actually a file.

1.4.16. lastModified

Function

datetime lastModified(loc file)

Synopsis

Last modification date of a location.

Description

Returns last modification time of the file at location file.

Examples
rascal>import IO;
ok

Determine the last modification date of the Rascal standard library:

rascal>lastModified(|std:///IO.rsc|);
datetime: $2017-06-22T09:10:36.000+00:00$

1.4.17. listEntries

Function

list[str] listEntries(loc file)

Synopsis

List the entries in a directory.

Description

List the entries in directory file.

Examples
rascal>import IO;
ok

List all entries in the standard library:

rascal>listEntries(|std:///|);
list[str]: ["PreludeCompiled$1.class","Boolean.rsc","Distance.class","Map.rsc","PreludeCompiled.class","Relation.rsc","DateTime.rsc","demo","Prelude.class","ValueIO.rsc","ParseTree.rsc","Prelude$Backtrack.class","Traversal.rsc","Set.rsc","ListRelation.rsc","Prelude$1.class","Prelude.rsc","PreludeCompiled$Less.class","resource",".project","Prelude$IValueWrap.class","NodeComparator.class","List.rsc","PreludeCompiled$Sorting.class","PreludeCompiled$Backtrack.class","cobra","Node.rsc","Type.rsc","String.rsc","IO.rsc","StandardLibrary.rsc","util","Exception.rsc","Prelude$Sorting.class","Message.rsc","Type.class","lang","experiments","Prelude$Less.class","analysis","Prelude$ByteBufferBackedInputStream.class","Grammar.rsc"]

1.4.18. mkDirectory

Function

void mkDirectory(loc file) throws PathNotFound(loc file), IO(str msg)

Synopsis

Create a new directory.

Description

Create a directory at location file.

1.4.19. print

Function

void print(value arg)

Synopsis

Print a value without subsequent newline.

Description

Print a value on the output stream. See println for a version that adds a newline and [IO-printExp] for a version that returns its argument as value.

Examples

Note that the only difference with println is that no newline is added after the value is printed

rascal>import IO;
ok
rascal>print("Hello World");
Hello World----

NOTE: Since `print` does not add a newline, the prompt `ok` appears at a weird place, i.e.,
glued to the output of `print`.

[[IO-printExp]]
## printExp

.Function
* `&T printExp(&T v)`
* `&T printExp(str msg, &T v)`


.Synopsis
Print a value and return it as result.

.Examples
[source,rascal-shell]

rascal>import IO; ok rascal>printExp(3.14); 3.14rascal>printExp("The value of PI is approximately ", 3.14); The value of PI is approximately 3.14----

1.4.20. println

Function
  • void println(value arg)

  • void println()

Synopsis

Print a value to the output stream and add a newline.

Description

Print a value on the output stream followed by a newline. See print for a version that does not add a newline and printlnExp for a version that returns its argument as value.

Examples
rascal>import IO;
ok
rascal>println("Hello World");
Hello World

Introduce variable S and print it:

rascal>S = "Hello World";
str: "Hello World"
rascal>println(S);
Hello World

Introduce variable L and print it:

rascal>L = ["a", "b", "c"];
list[str]: ["a","b","c"]
rascal>println(L);
["a","b","c"]

Use a string template to print several values:

rascal>println("<S>: <L>");
Hello World: ["a","b","c"]

Just print a newline

rascal>println();

1.4.21. printlnExp

Function
  • &T printlnExp(&T v)

  • &T printlnExp(str msg, &T v)

Synopsis

Print a value followed by a newline and return it as result.

Examples
rascal>import IO;
ok
rascal>printlnExp(3.14);
3.14
rascal>printlnExp("The value of PI is approximately ", 3.14);
The value of PI is approximately 3.14
Since printExp does no produce a newline after its output, the result prompt real: 3.14 is glued to the output of printExp.

1.4.22. rprint

Function

void rprint(value arg)

Synopsis

Raw print of a value.

Pitfalls

This function is only available for internal use in the Rascal development team.

1.4.23. rprintln

Function

void rprintln(value arg)

Synopsis

Raw print of a value followed by newline.

Pitfalls

This function is only available for internal use in the Rascal development team.

1.4.24. readFile

Function

str readFile(loc file) throws PathNotFound(loc file), IO(str msg)

Synopsis

Read the contents of a location and return it as string value.

Description

Return the contents of a file location as a single string. Also see readFileLines.

Encoding

A text file can be encoded in many different character sets, most common are UTF8, ISO-8859-1, and ASCII. If you know the encoding of the file, please use the readFileEnc and readFileLinesEnc overloads. If you do not know, we try to detect this. This detection is explained below:

  • If the implementation of the used scheme in the location (e.g.,|project:///|) defines the charset of the file then this is used.

  • Otherwise if the file contains a UTF8/16/32 BOM, then this is used.

  • As a last resort the IO library uses heuristics to determine if UTF-8 or UTF-32 could work:

    • Are the first 32 bytes valid UTF-8? Then use UTF-8.

    • Are the first 32 bytes valid UTF-32? Then use UTF-32.

  • Finally, we fall back to the system default (as given by the Java Runtime Environment).

To summarize, we use UTF-8 by default, except if the location has available meta-data, the file contains a BOM, or the first 32 bytes of the file are not valid UTF-8.

Pitfalls
  • The second version of readFile with a string argument is deprecated.

  • In case encoding is not known, we try to estimate as best as we can.

  • We default to UTF-8, if the file was not encoded in UTF-8 but the first characters were valid UTF-8, you might get an decoding error or just strange looking characters.

1.4.25. readFileEnc

Function

str readFileEnc(loc file, str charset) throws PathNotFound(loc file), IO(str msg)

Synopsis

Read the contents of a location and return it as string value.

Description

Return the contents (decoded using the Character set supplied) of a file location as a single string. Also see readFileLinesEnc.

1.4.26. readFileBytes

Function

list[int] readFileBytes(loc file) throws PathNotFound(loc file), IO(str msg)

Synopsis

Read the contents of a file and return it as a list of bytes.

1.4.27. readFileLines

Function

list[str] readFileLines(loc file) throws PathNotFound(loc file), IO(str msg)

Synopsis

Read the contents of a file location and return it as a list of strings.

Description

Return the contents of a file location as a list of lines. Also see readFile.

Encoding

Look at readFile to understand how this function chooses the character set. If you know the character set used, please use readFileLinesEnc.

Pitfalls
  • In case encoding is not known, we try to estimate as best as we can (see [readFile]).

  • We default to UTF-8, if the file was not encoded in UTF-8 but the first characters were valid UTF-8, you might get an decoding error or just strange looking characters (see readFile).

1.4.28. readFileLinesEnc

Function

list[str] readFileLinesEnc(loc file, str charset) throws PathNotFound(loc file), IO(str msg)

Synopsis

Read the contents of a file location and return it as a list of strings.

Description

Return the contents (decoded using the Character set supplied) of a file location as a list of lines. Also see readFileLines.

1.4.29. remove

Function

void remove(loc file) throws IO(str msg)

1.4.30. writeFile

Function

void writeFile(loc file, value V…​) throws PathNotFound(loc file), IO(str msg)

Synopsis

Write values to a file.

Description

Write a textual representation of some values to a file:

  • If a value is a simple string, the quotes are removed and the contents are de-escaped.

  • If a value has a non-terminal type, the parse tree is unparsed to produce a value.

  • All other values are printed as-is.

  • Each value is terminated by a newline character.

Files are encoded in UTF-8, in case this is not desired, use writeFileEnc.

1.4.31. writeFileBytes

Function

void writeFileBytes(loc file, list[int] bytes) throws PathNotFound(loc file), IO(str msg)

Synopsis

Write a list of bytes to a file.

1.4.32. writeFileEnc

Function

void writeFileEnc(loc file, str charset, value V…​) throws PathNotFound(loc file), IO(str msg)

Synopsis

Write values to a file.

Description

Write a textual representation of some values to a file:

  • If a value is a simple string, the quotes are removed and the contents are de-escaped.

  • If a value has a non-terminal type, the parse tree is unparsed to produce a value.

  • All other values are printed as-is.

  • Each value is terminated by a newline character.

Files are encoded using the charset provided.

1.4.33. touch

Function

void touch(loc file) throws PathNotFound(loc file), IO(str msg)

Synopsis

Changes the last modification date of a file.

1.4.34. md5HashFile

Function

str md5HashFile(loc file) throws PathNotFound(loc file), IO(str msg)

Synopsis

Read the contents of a location and return its MD5 hash.

Description

MD5 hash the contents of a file location.

Function

str createLink(str title, str target)

1.4.36. toBase64

Function

str toBase64(loc file) throws PathNotFound(loc file), IO(str msg)

1.4.37. copyFile

Function

bool copyFile(loc source, loc target)

1.4.38. copyDirectory

Function

bool copyDirectory(loc source, loc target)

1.5. List

Usage

import List;

Synopsis

Library functions for lists.

Description

For operators on lists see List in the Rascal Language Reference.

The following functions are available for lists:

  • concat: Concatenate a list of lists.

  • delete: Delete an element from a list.

  • distribution: Get the distribution of the elements of the list. That

  • drop: Drop elements from the head of a list.

  • dup: Remove multiple occurrences of elements in a list. The first occurrence remains.

  • elementAt:

  • getOneFrom: Pick a random element from a list.

  • getFirstFrom: Pick first element from a list.

  • head: Get the first element(s) from a list.

  • head:

  • headTail: Split a list in a head and a tail.

  • index: A list of legal index values of a list.

  • indexOf: Index of first occurrence of an element in a list.

  • insertAt: Insert an element at a specific position in a list.

  • intercalate: Join a list of values into a string separated by a separator.

  • intersperse: Intersperses a list of values with a separator.

  • isEmpty: Test whether a list is empty.

  • last: Return the last element of a list, if any.

  • lastIndexOf: Return index of last occurrence of elt in lst, or -1 if elt is not found.

  • mapper: Apply a function to all list elements and return list of results.

  • max: Determine the largest element in a list.

  • merge: Merge the elements of two sorted lists into one list.

  • merge:

  • min: Determine the smallest element in a list.

  • mix: Mix the elements of two lists.

  • permutations: Compute all permutations of a list.

  • permutationsBag:

  • pop: Pop top element from list, return a tuple.

  • prefix: Return all but the last element of a list.

  • push: Push an element in front of a list.

  • reducer: Apply a function to successive elements of list and combine the results (deprecated).

  • remove:

  • removeFromBag:

  • removeFromBag:

  • reverse: Reverse a list.

  • size: Determine the number of elements in a list.

  • slice: Compute a sublist of a list.

  • sort: Sort the elements of a list.

  • sort:

  • shuffle: Shuffle a list.

  • shuffle: Shuffle a list with a seed.

  • split: Split a list into two halves.

  • sum:

  • sum: Sum the elements of a list.

  • tail: Get the tail element(s) from a list.

  • tail:

  • take: Get number of elements from the head of a list.

  • takeOneFrom: Remove an arbitrary element from a list, returns the element and the modified list.

  • takeWhile: Take elements from the front of the list as long as a predicate is true.

  • toMap: Convert a list of pairs to a map; first elements are associated with a set of second elements.

  • toMapUnique: Convert a list of tuples to a map; result must be a map.

  • top: Take the top element of a list.

  • toRel: Convert a list to a relation.

  • toSet: Convert a list to a set.

  • toString: Convert a list to a string.

  • itoString: Convert a list to an indented string.

  • unzip: Make a pair (triple) of lists from a list of pairs (triples).

  • unzip:

  • upTill: Returns the list 0,1..n-1.

  • zip: Make a list of pairs from two (three) lists of the same length.

  • zip:

1.5.1. concat

Function

list[&T] concat(list[list[&T]] xxs)

Synopsis

Concatenate a list of lists.

Examples
rascal>import List;
ok
rascal>concat([]);
list[void]: []
rascal>concat([[]]);
list[void]: []
rascal>concat([[1]]);
list[int]: [1]
rascal>concat([[1],[],[2,3]]);
list[int]: [1,2,3]
rascal>concat([[1,2],[3],[4,5],[]]);
list[int]: [1,2,3,4,5]

1.5.2. delete

Function

list[&T] delete(list[&T] lst, int n)

Synopsis

Delete an element from a list.

Description

Delete the n-th element from a list. A new list without the n-th element is returned as result. The IndexOutOfBounds exception is thrown when n is not a valid index.

Examples
rascal>import List;
ok
rascal>delete([1, 2, 3], 1);
list[int]: [1,3]
rascal>delete(["zebra", "elephant", "snake", "owl"], 2);
list[str]: ["zebra","elephant","owl"]

1.5.3. distribution

Function

map[&T element, int occurs] distribution(list[&T] lst)

Synopsis

Get the distribution of the elements of the list. That is how often does each element occur in the list?

Examples
rascal>import List;
ok
rascal>distribution([4,4,4,3,1,2,1,1,3,4]);
map[int, int]: (1:3,3:2,2:1,4:4)

1.5.4. drop

Function

list[&T] drop(int n, list[&T] lst)

Synopsis

Drop elements from the head of a list.

Description

Drop n elements (or size(lst) elements if size(lst) < n) from the head of lst. See take to get elements from the head of a list].

Examples
rascal>import List;
ok
rascal>drop(2, [5, 1, 7, 3]);
list[int]: [7,3]
rascal>drop(10, [5, 1, 7, 3]);
list[void]: []
rascal>drop(2, ["zebra", "elephant", "snake", "owl"]);
list[str]: ["snake","owl"]

1.5.5. dup

Function

list[&T] dup(list[&T] lst)

Synopsis

Remove multiple occurrences of elements in a list. The first occurrence remains.

Examples
rascal>import List;
ok
rascal>dup([3, 1, 5, 3, 1, 7, 1, 2]);
list[int]: [3,1,5,7,2]

1.5.6. elementAt

Function

&T elementAt(list[&T] lst, int index)

1.5.7. getOneFrom

Function

&T getOneFrom(list[&T] lst)

Synopsis

Pick a random element from a list.

Description

Get an arbitrary element from a list. See takeOneFrom for a function that also removes the selected element.

Examples
rascal>import List;
ok
rascal>getOneFrom(["zebra", "elephant", "snake", "owl"]);
str: "zebra"
rascal>getOneFrom(["zebra", "elephant", "snake", "owl"]);
str: "elephant"
rascal>getOneFrom(["zebra", "elephant", "snake", "owl"]);
str: "elephant"

1.5.8. getFirstFrom

Function

&T getFirstFrom(list[&T] lst)

Synopsis

Pick first element from a list.

Description

Get the first element from a list. As opposed to getOneFrom this function always returns the same (first) list element.

1.5.9. head

Function
  • &T head(list[&T] lst) throws EmptyList

  • list[&T] head(list[&T] lst, int n) throws IndexOutOfBounds

Synopsis

Get the first element(s) from a list.

Description
  • Returns the first element of a list or throws EmptyList when the list is empty. This is identical to [top].

  • Returns the first n elements of a list or throws IndexOutOfBounds when the list is too short. This is similar to [take].

Examples
rascal>import List;
ok

Get the first element:

rascal>head([1, 2, 3]);
int: 1
rascal>head(["zebra", "elephant", "snake", "owl"]);
str: "zebra"

An exception is thrown when taking the head of an empty list:

rascal>head([]);
Exception [debugger cannot break at null frame]: EmptyList()

Get the first n elements:

rascal>head([1, 2, 3, 4], 2);
list[int]: [1,2]
rascal>head(["zebra", "elephant", "snake", "owl"], 2);
list[str]: ["zebra","elephant"]

An exception is thrown when the second argument exceeds the length of the list:

rascal>head([1, 2, 3, 5], 5);
Exception [debugger cannot break at null frame]: IndexOutOfBounds(4)

1.5.10. headTail

Function

tuple[&T, list[&T]] headTail(list[&T] lst) throws EmptyList

Synopsis

Split a list in a head and a tail.

Description

This function is identical to pop.

Examples
rascal>import List;
ok
rascal>headTail([3, 1, 4, 5]);
tuple[int,list[int]]: <3,[1,4,5]>
rascal>pop([3, 1, 4, 5]);
tuple[int,list[int]]: <3,[1,4,5]>
rascal>headTail(["zebra", "elephant", "snake", "owl"]);
tuple[str,list[str]]: <"zebra",["elephant","snake","owl"]>

1.5.11. index

Function

list[int] index(list[&T] lst)

Synopsis

A list of legal index values of a list.

Description

Returns a list of all legal index values for a given list lst.

Examples
rascal>import List;
ok
rascal>index([1, 3, 5]);
list[int]: [0,1,2]
rascal>index(["zebra", "elephant", "snake", "owl"]);
list[int]: [0,1,2,3]
Benefits

This function is useful in for loops over lists.

1.5.12. indexOf

Function

int indexOf(list[&T] lst, &T elt)

Synopsis

Index of first occurrence of an element in a list.

Description

Return index of first occurrence of elt in lst, or -1 if elt is not found. Also see lastIndexOf.

Examples
rascal>import List;
ok
rascal>indexOf([3, 1, 4, 5], 4);
int: 2
rascal>indexOf([3, 1, 4, 5], 7);
int: -1
rascal>indexOf(["zebra", "elephant", "snake", "owl"], "snake");
int: 2
rascal>indexOf(["zebra", "elephant", "snake", "owl"], "eagle");
int: -1

1.5.13. insertAt

Function

list[&T] insertAt(list[&T] lst, int n, &T elm) throws IndexOutOfBounds

Synopsis

Insert an element at a specific position in a list.

Description

Returns a new list with the value of elm inserted at index position n of the old list.

Examples
rascal>import List;
ok
rascal>insertAt([1,2,3], 1, 5);
list[int]: [1,5,2,3]
rascal>insertAt(["zebra", "elephant", "snake", "owl"], 2, "eagle");
list[str]: ["zebra","elephant","eagle","snake","owl"]

An exception is thrown when the index position is outside the list:

rascal>insertAt([1,2,3], 10, 5);
Exception [debugger cannot break at null frame]: IndexOutOfBounds(10)

1.5.14. intercalate

Function

str intercalate(str sep, list[value] l)

Synopsis

Join a list of values into a string separated by a separator.

Examples
rascal>import List;
ok
rascal>intercalate("/", [3]);
str: "3"
rascal>intercalate("/", [3, 1, 4, 5]);
str: "3/1/4/5"
rascal>intercalate(", ", [3, 1, 4, 5]);
str: "3, 1, 4, 5"
rascal>intercalate(", ", ["zebra", "elephant", "snake", "owl"]);
str: "zebra, elephant, snake, owl"

1.5.15. intersperse

Function

list[&T] intersperse(&T sep, list[&T] xs)

Synopsis

Intersperses a list of values with a separator.

Examples
rascal>import List;
ok
rascal>intersperse(", ", ["a","b","c"]);
list[str]: ["a",", ","b",", ","c"]
rascal>intersperse(0, [1, 2, 3]);
list[int]: [1,0,2,0,3]
rascal>intersperse(1, []);
list[void]: []
rascal>intersperse([], [1]);
list[int]: [1]

1.5.16. isEmpty

Function

bool isEmpty(list[&T] lst)

Synopsis

Test whether a list is empty.

Description

Returns true when a list is empty and false otherwise.

Examples
rascal>import List;
ok
rascal>isEmpty([]);
bool: true
rascal>isEmpty([1, 2, 3]);
bool: false

1.5.17. last

Function

&T last(list[&T] lst) throws EmptyList

Synopsis

Return the last element of a list, if any.

Description

Also see tail that returns a list of one or more of the last elements of a list.

Examples
rascal>import List;
ok
rascal>last([1]);
int: 1
rascal>last([3, 1, 4, 5]);
int: 5
rascal>last(["zebra", "elephant", "snake", "owl"]);
str: "owl"
rascal>tail([3, 1, 4, 5]);
list[int]: [1,4,5]

1.5.18. lastIndexOf

Function

int lastIndexOf(list[&T] lst, &T elt)

Synopsis

Return index of last occurrence of elt in lst, or -1 if elt is not found.

Description

Also see indexOf.

Examples
rascal>import List;
ok
rascal>lastIndexOf([3, 1, 4, 5, 4], 4);
int: 4
rascal>lastIndexOf([3, 1, 4, 5, 4], 7);
int: -1
rascal>lastIndexOf(["zebra", "owl", "elephant", "snake", "owl"], "owl");
int: 4

1.5.19. mapper

Function

list[&U] mapper(list[&T] lst, &U (&T) fn)

Synopsis

Apply a function to all list elements and return list of results.

Description

Apply a function fn to each element of lst and return the list of results.

Examples
rascal>import List;
ok
rascal>int incr(int x) { return x + 1; }
ok
rascal>mapper([1, 2, 3, 4], incr);
list[int]: [2,3,4,5]

1.5.20. max

Function

&T max(list[&T] lst) throws EmptyList

Synopsis

Determine the largest element in a list.

Examples
rascal>import List;
ok
rascal>max([1, 3, 5, 2, 4]);
int: 5
rascal>max(["zebra", "elephant", "snake", "owl"]);
str: "zebra"

1.5.21. merge

Function
  • list[&T] merge(list[&T] left, list[&T] right)

  • list[&T] merge(list[&T] left, list[&T] right, bool (&T a, &T b) lessOrEqual)

Synopsis

Merge the elements of two sorted lists into one list.

Description

Merge the elements of two sorted lists into one list using the built-in ordering between values. Optional, a comparison function lessOrEqual may be given for a user-defined ordering between values.

Examples
rascal>import List;
ok
rascal>merge([1, 3, 5], [2, 7, 9, 15]);
list[int]: [1,2,3,5,7,9,15]
rascal>merge(["ape", "elephant", "owl", "snale", "zebra"], ["apple", "berry", "orange", "pineapple"]);
list[str]: ["ape","apple","berry","elephant","orange","owl","pineapple","snale","zebra"]

Merge two lists of strings and use their length as ordering:

rascal>import String;
ok
rascal>merge(["ape", "owl", "snale", "zebra", "elephant"], ["apple", "berry", "orange", "pineapple"], bool(str x, str y){ return size(x) <= size(y); });
list[str]: ["ape","owl","snale","zebra","apple","berry","orange","elephant","pineapple"]

1.5.22. min

Function

&T min(list[&T] lst)

Synopsis

Determine the smallest element in a list.

Examples
rascal>import List;
ok
rascal>min([1, 3, 5, 2, 4]);
int: 1
rascal>min(["zebra", "elephant", "snake", "owl"]);
str: "elephant"

1.5.23. mix

Function

list[&T] mix(list[&T] l, list[&T] r)

Synopsis

Mix the elements of two lists.

Description

Let n be the minimum of the length of the two lists l and r. mix returns a list in which the first n elements are taken alternately from the left and the right list, followed by the remaining elements of the longest list.

Examples
rascal>import List;
ok
rascal>mix([3, 1, 7, 5, 9], [15, 25, 35]);
list[int]: [3,15,1,25,7,35,5,9]
rascal>mix([3, 1, 7], [15, 25, 35, 45, 55]);
list[int]: [3,15,1,25,7,35,45,55]
rascal>mix([3, 1, 7], ["elephant", "snake"]);
list[value]: [3,"elephant",1,"snake",7]

1.5.24. permutations

Function

set[list[&T]] permutations(list[&T] lst)

Synopsis

Compute all permutations of a list.

Examples
rascal>import List;
ok
rascal>permutations([1,2,3]);
set[list[int]]: {
  [3,2,1],
  [1,2,3],
  [2,1,3],
  [1,3,2],
  [2,3,1],
  [3,1,2]
}

1.5.25. permutationsBag

Function

set[list[&T]] permutationsBag(map[&T element, int occurs] b)

1.5.26. pop

Function

tuple[&T, list[&T]] pop(list[&T] lst) throws EmptyList

Synopsis

Pop top element from list, return a tuple. .Description This function is identical to headTail. Also see push and top.

Examples
rascal>import List;
ok
rascal>pop([3, 1, 4, 5]);
tuple[int,list[int]]: <3,[1,4,5]>
rascal>headTail([3, 1, 4, 5]);
tuple[int,list[int]]: <3,[1,4,5]>
rascal>pop(["zebra", "elephant", "snake", "owl"]);
tuple[str,list[str]]: <"zebra",["elephant","snake","owl"]>

1.5.27. prefix

Function

list[&T] prefix(list[&T] lst)

Synopsis

Return all but the last element of a list.

Examples
rascal>import List;
ok
rascal>prefix([3, 1, 4, 5]);
list[int]: [3,1,4]
rascal>prefix([]);
list[void]: []
rascal>prefix(["zebra", "elephant", "snake", "owl"]);
list[str]: ["zebra","elephant","snake"]

1.5.28. push

Function

list[&T] push(&T elem, list[&T] lst)

Synopsis

Push an element in front of a list.

Description

Also see pop and top.

Examples
rascal>import List;
ok
rascal>push(7, [3, 1, 4, 5]);
list[int]: [7,3,1,4,5]
rascal>push("eagle", ["zebra", "elephant", "snake", "owl"]);
list[str]: ["eagle","zebra","elephant","snake","owl"]

1.5.29. reducer

Function

&T reducer(list[&T] lst, &T (&T, &T) fn, &T unit)

Synopsis

Apply a function to successive elements of list and combine the results (deprecated).

Description

Apply the function fn to successive elements of list lst starting with unit.

Examples
rascal>import List;
ok
rascal>int add(int x, int y) { return x + y; }
ok
rascal>reducer([10, 20, 30, 40], add, 0);
int: 100
Pitfalls

WARNING: This function is deprecated, use a reducer instead.

1.5.30. remove

Function

list[&T] remove(list[&T] lst, int indexToDelete)

1.5.31. removeFromBag

Function
  • map[&T element, int occurs] removeFromBag(map[&T element, int occurs] b, &T el)

  • map[&T element, int occurs] removeFromBag(map[&T element, int occurs] b, &T el, int nr)

1.5.32. reverse

Function

list[&T] reverse(list[&T] lst)

Synopsis

Reverse a list.

Description

Returns a list with the elements of lst in reverse order.

Examples
rascal>import List;
ok
rascal>reverse([1,4,2,3]);
list[int]: [3,2,4,1]
rascal>reverse(["zebra", "elephant", "snake", "owl"]);
list[str]: ["owl","snake","elephant","zebra"]

1.5.33. size

Function

int size(list[&T] lst)

Synopsis

Determine the number of elements in a list.

Examples
rascal>import List;
ok
rascal>size([20, 10, 30]);
int: 3
rascal>size(["zebra", "elephant", "snake", "owl"]);
int: 4

1.5.34. slice

Function

list[&T] slice(list[&T] lst, int begin, int len)

Synopsis

Compute a sublist of a list.

Description

Returns a sublist of lst from index start of length len.

In most cases it is better to use the built-in slice notation, see the example below.
Examples
rascal>import List;
ok
rascal>slice([10, 20, 30, 40, 50, 60], 2, 3);
list[int]: [30,40,50]
rascal>slice(["zebra", "elephant", "snake", "owl"], 1, 2);
list[str]: ["elephant","snake"]

Here are the equivalent expressions using the slice notation:

rascal>[10, 20, 30, 40, 50, 60][2 .. 5];
list[int]: [30,40,50]
rascal>["zebra", "elephant", "snake", "owl"][1 .. 3];
list[str]: ["elephant","snake"]
In the slice notation the upper bound is exclusive.

1.5.35. sort

Function
  • list[&T] sort(list[&T] lst)

  • list[&T] sort(list[&T] l, bool (&T a, &T b) less)

Synopsis

Sort the elements of a list.

Description

Sort the elements of a list:

  • Use the built-in ordering on values to compare list elements.

  • Give an additional lessThan function that will be used to compare elements.

Examples
rascal>import List;
ok
rascal>import String;
ok
rascal>sort([10, 4, -2, 11, 100, 5]);
list[int]: [-2,4,5,10,11,100]
rascal>fruits = ["mango", "strawberry", "pear", "pineapple", "banana", "grape", "kiwi"];
list[str]: ["mango","strawberry","pear","pineapple","banana","grape","kiwi"]
rascal>sort(fruits);
list[str]: ["banana","grape","kiwi","mango","pear","pineapple","strawberry"]
rascal>sort(fruits, bool(str a, str b){ return size(a) > size(b); });
list[str]: ["strawberry","pineapple","banana","mango","grape","kiwi","pear"]

1.5.36. shuffle

Function
  • list[&T] shuffle(list[&T] l)

  • list[&T] shuffle(list[&T] l, int seed)

Synopsis

Shuffle a list.

Description

Returns a random (unbiased) shuffled list.

Examples
rascal>import List;
ok
rascal>shuffle([1,4,2,3]);
list[int]: [3,2,1,4]
rascal>shuffle(["zebra", "elephant", "snake", "owl"]);
list[str]: ["owl","elephant","zebra","snake"]

1.5.37. split

Function

tuple[list[&T],list[&T]] split(list[&T] l)

Synopsis

Split a list into two halves.

Examples
rascal>import List;
ok
rascal>split([3, 1, 4, 5, 7]);
tuple[list[int],list[int]]: <[3,1],[4,5,7]>
rascal>split(["zebra", "elephant", "snake", "owl"]);
tuple[list[str],list[str]]: <["zebra","elephant"],["snake","owl"]>

1.5.38. sum

Function
  • (&T <:num) sum(list[(&T <:num)] _:[])

  • default (&T <:num) sum([(&T <: num) hd, *(&T <: num) tl])

1.5.39. tail

Function
  • list[&T] tail(list[&T] lst) throws EmptyList

  • list[&T] tail(list[&T] lst, int len) throws IndexOutOfBounds

Synopsis

Get the tail element(s) from a list.

Description
  • Return a list consisting of all but the first element of lst.

  • Return a list consisting of the last n elements of lst.

Examples

All but first element:

rascal>import List;
ok
rascal>tail([10,20,30]);
list[int]: [20,30]

Try an error case:

rascal>tail([]);
Exception [debugger cannot break at null frame]: EmptyList()

Last n elements:

rascal>tail([10, 20, 30, 40, 50, 60], 3);
list[int]: [40,50,60]

Try an error case:

rascal>tail([10, 20, 30, 40, 50, 60], 10);
Exception [debugger cannot break at null frame]: IndexOutOfBounds(4)

1.5.40. take

Function

list[&T] take(int n, list[&T] lst)

Synopsis

Get number of elements from the head of a list.

Description

Get n elements (or size(lst) elements if size(lst) < n) from the head of the list. See drop to remove elements from the head of a list.

Examples
rascal>import List;
ok
rascal>take(2, [3, 1, 4, 5]);
list[int]: [3,1]
rascal>take(6, [3, 1, 4, 5]);
list[int]: [3,1,4,5]
rascal>take(2, ["zebra", "elephant", "snake", "owl"]);
list[str]: ["zebra","elephant"]

1.5.41. takeOneFrom

Function

tuple[&T, list[&T]] takeOneFrom(list[&T] lst)

Synopsis

Remove an arbitrary element from a list, returns the element and the modified list.

Description

Select an arbitrary element from lst, and return a tuple consisting of:

  • the selected element, and

  • a new list consisting of all elements of lst except the selected element.

See getOneFrom to only selected an element from a list.

Examples
rascal>import List;
ok
rascal>takeOneFrom([10,20,30,40,50]);
tuple[int,list[int]]: <50,[10,20,30,40]>
rascal>takeOneFrom([10,20,30,40,50]);
tuple[int,list[int]]: <30,[10,20,40,50]>
rascal>takeOneFrom([10,20,30,40,50]);
tuple[int,list[int]]: <40,[10,20,30,50]>
rascal>takeOneFrom(["zebra", "elephant", "snake", "owl"]);
tuple[str,list[str]]: <"owl",["zebra","elephant","snake"]>
rascal>takeOneFrom(["zebra", "elephant", "snake", "owl"]);
tuple[str,list[str]]: <"owl",["zebra","elephant","snake"]>
rascal>takeOneFrom(["zebra", "elephant", "snake", "owl"]);
tuple[str,list[str]]: <"zebra",["elephant","snake","owl"]>

1.5.42. takeWhile

Function

list[&T] takeWhile(list[&T] lst, bool (&T a) take)

Synopsis

Take elements from the front of the list as long as a predicate is true.

Examples
rascal>import List;
ok
rascal>bool isEven(int a) = a mod 2 == 0;
ok
rascal>takeWhile([2,4,6,8,1,2,3,4,5],isEven);
list[int]: [2,4,6,8]

1.5.43. toMap

Function

map[&A,set[&B]] toMap(list[tuple[&A, &B]] lst) throws MultipleKey

Synopsis

Convert a list of pairs to a map; first elements are associated with a set of second elements.

Description

Convert a list of tuples to a map in which the first element of each tuple is associated with the set of second elements from all tuples with the same first element. Keys should be unique.

Examples
rascal>import List;
ok
rascal>toMap([<1,10>, <1, 11>, <2, 20>, <3, 30>, <3, 31>]);
map[int, set[int]]: (
  1:{10,11},
  3:{31,30},
  2:{20}
)
Pitfalls

toMap collects all values in tuples with the same first value in a set. Contrast this with toMapUnique that associates each first tuple value with the second tuple value, but imposes the constraint that those keys are unique.

1.5.44. toMapUnique

Function

map[&A,&B] toMapUnique(list[tuple[&A, &B]] lst) throws MultipleKey

Synopsis

Convert a list of tuples to a map; result must be a map.

Description

Convert a list of tuples to a map; result must be a map.

Examples
rascal>import List;
ok
rascal>toMapUnique([<1,10>, <2, 20>, <3, 30>]);
map[int, int]: (1:10,3:30,2:20)

Let’s explore an error case:

rascal>toMapUnique([<1,10>, <1, 11>, <2, 20>, <3, 30>]);
Exception [debugger cannot break at null frame]: MultipleKey(1)
Pitfalls

The keys in a map are unique by definition. toMapUnique throws a MultipleKey exception when the list contains more than one tuple with the same first value.

1.5.45. top

Function

&T top(list[&T] lst) throws EmptyList

Synopsis

Take the top element of a list. .Description This function is identical to [head]. Also see pop and push.

Examples
rascal>import List;
ok
rascal>top([3, 1, 4, 5]);
int: 3
rascal>top(["zebra", "elephant", "snake", "owl"]);
str: "zebra"

1.5.46. toRel

Function

rel[&T,&T] toRel(list[&T] lst)

Synopsis

Convert a list to a relation. .Description Convert a list to relation, where each tuple encodes which elements are followed by each other. This function will return an empty relation for empty lists and for singleton lists.

Examples
rascal>import List;
ok
rascal>toRel([3, 1, 4, 5]);
rel[int,int]: {
  <1,4>,
  <3,1>,
  <4,5>
}
rascal>toRel(["zebra", "elephant", "snake", "owl"]);
rel[str,str]: {
  <"snake","owl">,
  <"zebra","elephant">,
  <"elephant","snake">
}

1.5.47. toSet

Function

set[&T] toSet(list[&T] lst)

Synopsis

Convert a list to a set.

Description

Convert lst to a set.

Examples
rascal>import List;
ok
rascal>toSet([10, 20, 30, 40]);
set[int]: {10,40,20,30}
rascal>toSet(["zebra", "elephant", "snake", "owl"]);
set[str]: {"snake","owl","zebra","elephant"}

Note that the same can be done using splicing

rascal>l = [10,20,30,40];
list[int]: [10,20,30,40]
rascal>s = {*l};
set[int]: {10,40,20,30}

1.5.48. toString

Function

str toString(list[&T] lst)

Synopsis

Convert a list to a string.

Description

Convert lst to a string.

Examples
rascal>import List;
ok
rascal>toString([10, 20, 30]);
str: "[10,20,30]"
rascal>toString(["zebra", "elephant", "snake", "owl"]);
str: "[\"zebra\",\"elephant\",\"snake\",\"owl\"]"

1.5.49. itoString

Function

str itoString(list[&T] lst)

Synopsis

Convert a list to an indented string.

Description

Convert lst to a indented string.

Examples
rascal>import List;
ok
rascal>itoString([10, 20, 30]);
str: "[10,20,30]"
rascal>itoString(["zebra", "elephant", "snake", "owl"]);
str: "[\"zebra\",\"elephant\",\"snake\",\"owl\"]"

1.5.50. unzip

Function
  • tuple[list[&T],list[&U]] unzip(list[tuple[&T,&U]] lst)

  • tuple[list[&T],list[&U],list[&V]] unzip(list[tuple[&T,&U,&V]] lst)

Synopsis

Make a pair (triple) of lists from a list of pairs (triples).

Description

Also see unzip;

Examples
rascal>import List;
ok
rascal>unzip([<3,"thirty">, <1,"ten">, <4,"forty">]);
tuple[list[int],list[str]]: <[3,1,4],["thirty","ten","forty"]>
rascal>unzip([<3,"thirty",300>, <1,"ten",100>, <4,"forty",400>]);
tuple[list[int],list[str],list[int]]: <[3,1,4],["thirty","ten","forty"],[300,100,400]>

1.5.51. upTill

Function

list[int] upTill(int n)

Synopsis

Returns the list 0,1..n-1. .Description Returns the list 0, 1, .., n-1, this is slightly faster than [0..n], since the returned values are shared.

Examples
rascal>import List;
ok
rascal>upTill(10);
list[int]: [0,1,2,3,4,5,6,7,8,9]

1.5.52. zip

Function
  • list[tuple[&T first, &U second]] zip(list[&T] a, list[&U] b)

  • list[tuple[&T first, &U second, &V third]] zip(list[&T] a, list[&U] b, list[&V] c)

Synopsis

Make a list of pairs from two (three) lists of the same length.

Description

Also see unzip.

Examples
rascal>import List;
ok
rascal>zip([3, 1, 4], ["thirty", "ten", "forty"]);
lrel[int,str]: [
  <3,"thirty">,
  <1,"ten">,
  <4,"forty">
]
rascal>zip([3, 1, 4], ["thirty", "ten", "forty"], [300, 100, 400]);
lrel[int,str,int]: [
  <3,"thirty",300>,
  <1,"ten",100>,
  <4,"forty",400>
]

1.6. ListRelation

Usage

import ListRelation;

Synopsis

Library functions for list relations.

Description

For operators on listrelations see ListRelation in the Rascal Language Reference.

The following functions are defined for list relations :

1.6.1. carrier

Function
  • list[&T] carrier (lrel[&T,&T] R)

  • list[&T] carrier (lrel[&T,&T,&T] R)

  • list[&T] carrier (lrel[&T,&T,&T,&T] R)

  • list[&T] carrier (lrel[&T,&T,&T,&T,&T] R)

Synopsis

Return the list of all elements in any tuple in a list relation.

Examples
rascal>import ListRelation;
ok
rascal>carrier([<1,10>, <2,20>]);
list[int]: [1,10,2,20]
rascal>carrier([<1,10,100,1000>, <2,20,200,2000>]);
list[int]: [1,10,100,1000,2,20,200,2000]

1.6.2. carrierR

Function
  • lrel[&T,&T] carrierR (lrel[&T,&T] R, set[&T] S)

  • lrel[&T,&T,&T] carrierR (lrel[&T,&T,&T] R, set[&T] S)

  • lrel[&T,&T,&T,&T] carrierR (lrel[&T,&T,&T,&T] R, set[&T] S)

  • lrel[&T,&T,&T,&T,&T] carrierR (lrel[&T,&T,&T,&T,&T] R, set[&T] S)

Synopsis

A list relation restricted to certain element values in tuples.

Description

Returns list relation R restricted to tuples with elements in set S.

Examples
rascal>import ListRelation;
ok
rascal>carrierR([<1,10>, <2,20>, <3,30>], {10, 1, 20});
lrel[int,int]: [<1,10>]

1.6.3. carrierX

Function
  • lrel[&T,&T] carrierX (lrel[&T,&T] R, set[&T] S)

  • lrel[&T,&T,&T] carrierX (lrel[&T,&T,&T] R, set[&T] S)

  • lrel[&T,&T,&T,&T] carrierX (lrel[&T,&T,&T,&T] R, set[&T] S)

  • lrel[&T,&T,&T,&T,&T] carrierX (lrel[&T,&T,&T,&T,&T] R, set[&T] S)

Synopsis

A list relation excluding tuples containing certain values.

Description

Returns list relation R excluding tuples with some element in S.

Examples
rascal>import ListRelation;
ok
rascal>carrierX([<1,10>, <2,20>, <3,30>], {10, 1, 20});
lrel[int,int]: [<3,30>]

1.6.4. complement

Function
  • lrel[&T0, &T1] complement(lrel[&T0, &T1] R)

  • lrel[&T0, &T1, &T2] complement(lrel[&T0, &T1, &T2] R)

  • lrel[&T0, &T1, &T2, &T3] complement(lrel[&T0, &T1, &T2, &T3] R)

  • lrel[&T0, &T1, &T2, &T3, &T4] complement(lrel[&T0, &T1, &T2, &T3, &T4] R)

Synopsis

Complement of a list relation.

Description

Given a list relation R a new relation U can be constructed that contains all possible tuples with element values that occur at corresponding tuple positions in R. The function complement returns the complement of R relative to U, in other words: U - R.

Examples
rascal>import ListRelation;
ok

Declare R and compute corresponding U:

rascal>R = [<1,10>, <2, 20>, <3, 30>];
lrel[int,int]: [
  <1,10>,
  <2,20>,
  <3,30>
]
rascal>U = domain(R) * range(R);
lrel[int,int]: [
  <1,10>,
  <1,20>,
  <1,30>,
  <2,10>,
  <2,20>,
  <2,30>,
  <3,10>,
  <3,20>,
  <3,30>
]

Here is the complement of R computed in two ways:

rascal>U - R;
lrel[int,int]: [
  <1,20>,
  <1,30>,
  <2,10>,
  <2,30>,
  <3,10>,
  <3,20>
]
rascal>complement([<1,10>, <2, 20>, <3, 30>]);
lrel[int,int]: [
  <1,20>,
  <1,30>,
  <2,10>,
  <2,30>,
  <3,10>,
  <3,20>
]

1.6.5. domain

Function
  • list[&T0] domain(lrel[&T0,&T1] R)

  • list[&T0] domain(lrel[&T0,&T1,&T2] R)

  • list[&T0] domain(lrel[&T0,&T1,&T2,&T3] R)

  • list[&T0] domain(lrel[&T0,&T1,&T2,&T3,&T4] R)

Synopsis

Domain of a list relation: a list consisting of the first element of each tuple.

Examples
rascal>import ListRelation;
ok
rascal>domain([<1,10>, <2,20>]);
list[int]: [1,2]
rascal>domain([<"mon", 1>, <"tue", 2>]);
list[str]: ["mon","tue"]

1.6.6. domainR

Function
  • lrel[&T0,&T1] domainR (lrel[&T0,&T1] R, set[&T0] S)

  • lrel[&T0,&T1,&T2] domainR (lrel[&T0,&T1,&T2] R, set[&T0] S)

  • lrel[&T0,&T1,&T2,&T3] domainR (lrel[&T0,&T1,&T2,&T3] R, set[&T0] S)

  • lrel[&T0,&T1,&T2,&T3,&T4] domainR (lrel[&T0,&T1,&T2,&T3,&T4] R, set[&T0] S)

  • lrel[&T0,&T1] domainR (lrel[&T0,&T1] R, list[&T0] L)

  • lrel[&T0,&T1,&T2] domainR (lrel[&T0,&T1,&T2] R, list[&T0] L)

  • lrel[&T0,&T1,&T2,&T3] domainR (lrel[&T0,&T1,&T2,&T3] R, list[&T0] L)

  • lrel[&T0,&T1,&T2,&T3,&T4] domainR (lrel[&T0,&T1,&T2,&T3,&T4] R, list[&T0] L)

Synopsis

List relation restricted to certain domain elements.

Description

Restriction of a list relation R to tuples with first element in S.

Examples
rascal>import ListRelation;
ok
rascal>domainR([<1,10>, <2,20>, <3,30>], {3, 1});
lrel[int,int]: [
  <1,10>,
  <3,30>
]

1.6.7. domainX

Function
  • lrel[&T0,&T1] domainX (lrel[&T0,&T1] R, set[&T0] S)

  • lrel[&T0,&T1,&T2] domainX (lrel[&T0,&T1,&T2] R, set[&T0] S)

  • lrel[&T0,&T1,&T2,&T3] domainX (lrel[&T0,&T1,&T2,&T3] R, set[&T0] S)

  • lrel[&T0,&T1,&T2,&T3,&T4] domainX (lrel[&T0,&T1,&T2,&T3,&T4] R, set[&T0] S)

Synopsis

List relation excluding certain domain values.

Description

List relation R excluding tuples with first element in S.

Examples
rascal>import ListRelation;
ok
rascal>domainX([<1,10>, <2,20>, <3,30>], {3, 1});
lrel[int,int]: [<2,20>]

1.6.8. groupDomainByRange

Function

list[list[&U]] groupDomainByRange(lrel[&U dom, &T ran] input)

Synopsis

Make sets of elements in the domain that relate to the same element in the range.

Examples
rascal>import ListRelation;
ok
rascal>legs = [<"bird", 2>, <"dog", 4>, <"human", 2>, <"spider", 8>, <"millepede", 1000>, <"crab", 8>, <"cat", 4>];
lrel[str,int]: [
  <"bird",2>,
  <"dog",4>,
  <"human",2>,
  <"spider",8>,
  <"millepede",1000>,
  <"crab",8>,
  <"cat",4>
]
rascal>groupDomainByRange(legs);
list[list[str]]: [
  ["bird","human"],
  ["dog","cat"],
  ["spider","crab"],
  ["millepede"]
]

1.6.9. groupRangeByDomain

Function

list[list[&T]] groupRangeByDomain(lrel[&U dom, &T ran] input)

Synopsis

Make sets of elements in the range that relate to the same element in the domain.

Description
rascal>import ListRelation;
ok
rascal>skins = [<"bird", "feather">, <"dog", "fur">, <"tortoise", "shell">, <"human", "skin">, <"fish", "scale">, <"lizard", "scale">, <"crab", "shell">, <"cat", "fur">];
lrel[str,str]: [
  <"bird","feather">,
  <"dog","fur">,
  <"tortoise","shell">,
  <"human","skin">,
  <"fish","scale">,
  <"lizard","scale">,
  <"crab","shell">,
  <"cat","fur">
]
rascal>groupRangeByDomain(skins);
list[list[str]]: [
  ["feather"],
  ["fur"],
  ["shell"],
  ["skin"],
  ["scale"]
]

1.6.10. ident

Function

lrel[&T, &T] ident (list[&T] S)

Synopsis

The identity list relation.

Description

The identity list relation for set S.

Examples
rascal>import ListRelation;
ok
rascal>ident(["mon", "tue", "wed"]);
lrel[str,str]: [
  <"mon","mon">,
  <"tue","tue">,
  <"wed","wed">
]

1.6.11. invert

Function
  • lrel[ &T1,&T0] invert (lrel[&T0,&T1 ] R)

  • lrel[ &T2,&T1,&T0] invert (lrel[&T0,&T1,&T2 ] R)

  • lrel[ &T3,&T2,&T1,&T0] invert (lrel[&T0,&T1,&T2,&T3 ] R)

  • lrel[&T4,&T3,&T2,&T1,&T0] invert (lrel[&T0,&T1,&T2,&T3,&T4] R)

Synopsis

Invert the tuples in a list relation.

Examples
rascal>import ListRelation;
ok
rascal>invert([<1,10>, <2,20>]);
lrel[int,int]: [
  <10,1>,
  <20,2>
]

1.6.12. range

Function
  • list[&T1] range (lrel[&T0,&T1] R)

  • lrel[&T1,&T2] range (lrel[&T0,&T1, &T2] R)

  • lrel[&T1,&T2,&T3] range (lrel[&T0,&T1,&T2,&T3] R)

  • lrel[&T1,&T2,&T3,&T4] range (lrel[&T0,&T1,&T2,&T3,&T4] R)

Synopsis

The range composed of all but the first element of each tuple of a list relation.

Examples
rascal>import ListRelation;
ok
rascal>range([<1,10>, <2,20>]);
list[int]: [10,20]
rascal>range([<"mon", 1>, <"tue", 2>]);
list[int]: [1,2]

1.6.13. rangeR

Function
  • lrel[&T0,&T1] rangeR (lrel[&T0,&T1] R, set[&T1] S)

  • lrel[&T0,&T1] rangeR (lrel[&T0,&T1] R, list[&T1] L)

Synopsis

List relation restricted to certain range values.

Description

Restriction of binary list relation R to tuples with second element in set S.

Examples
rascal>import ListRelation;
ok
rascal>rangeR([<1,10>, <2,20>, <3,30>], {30, 10});
lrel[int,int]: [
  <1,10>,
  <3,30>
]

1.6.14. rangeX

Function
  • lrel[&T0,&T1] rangeX (lrel[&T0,&T1] R, set[&T1] S)

  • lrel[&T0,&T1] rangeX (lrel[&T0,&T1] R, list[&T1] S)

Synopsis

List relation excluding certain range values.

Description

Restriction of binary list relation R to tuples with second element not in set S.

Examples
rascal>import ListRelation;
ok
rascal>rangeX([<1,10>, <2,20>, <3,30>], {30, 10});
lrel[int,int]: [<2,20>]

1.6.15. toMap

Function

map[&T0,list[&T1]] toMap(lrel[&T0,&T1] R)

1.6.16. index

Function

map[&K, set[&V]] index(lrel[&K, &V] R)

Synopsis

Listes a binary list relation as a map

Description

Converts a binary list relation to a map of the domain to a set of the range.

Examples
rascal>import ListRelation;
ok
rascal>index([<1,10>, <2,20>, <3,30>, <30,10>]);
map[int, set[int]]: (
  1:{10},
  3:{30},
  2:{20},
  30:{10}
)

1.6.17. squeeze

Function

list[&T] squeeze(list[&T] xs)

1.7. Map

Usage

import Map;

Synopsis

Library functions for maps.

Description

For operators on maps see Map in the Rascal Language Reference.

The following functions are defined for maps:

  • delete: Delete a key from a map.

  • domain: Determine the domain (set of keys) of a map.

  • domainR: Map restricted to certain keys.

  • domainX: Map with certain keys excluded.

  • getOneFrom: Get a n arbitrary key from a map.

  • invert: Invert the (key,value) pairs in a map.

  • invertUnique: Invert the (key,value) pairs in a map.

  • isEmpty: Test whether a map is empty.

  • mapper: Apply a function to all (key, value) pairs in a map.

  • range: The range (set of values that correspond to its keys) of a map.

  • rangeR: Map restricted to certain values in (key,values) pairs.

  • rangeX: Map with certain values in (key,value) pairs excluded.

  • size: Number of (key, value) pairs in a map.

  • toList: Convert a map to a list of tuples.

  • toRel: Convert a map to a relation.

  • toRel:

  • toRel:

  • toString: Convert a map to a string.

  • itoString: Convert a map to a indented string.

1.7.1. delete

Function

map[&K,&V] delete(map[&K,&V] m, &K k)

Synopsis

Delete a key from a map.

Description

Returns the map m minus the key k.

Examples
rascal>import Map;
ok
rascal>delete(("apple":1,"pear":2), "apple");
map[str, int]: ("pear":2)

1.7.2. domain

Function

set[&K] domain(map[&K, &V] M)

Synopsis

Determine the domain (set of keys) of a map.

Description

Returns the domain (set of keys) of map M.

Examples
rascal>import Map;
ok
rascal>domain(("apple": 1, "pear": 2));
set[str]: {"pear","apple"}

1.7.3. domainR

Function

map[&K, &V] domainR(map[&K, &V] M, set[&K] S)

Synopsis

Map restricted to certain keys.

Description

Return the map M restricted to pairs with key in S.

Examples
rascal>import Map;
ok
rascal>domainR(("apple": 1, "pear": 2, "orange": 3), {"apple", "pear"});
map[str, int]: ("pear":2,"apple":1)

1.7.4. domainX

Function

map[&K, &V] domainX(map[&K, &V] M, set[&K] S)

Synopsis

Map with certain keys excluded.

Description

Return the map M restricted to pairs with key not in S.

Examples
rascal>import Map;
ok
rascal>domainX(("apple": 1, "pear": 2, "orange": 3), {"apple", "pear"});
map[str, int]: ("orange":3)

1.7.5. getOneFrom

Function

&K getOneFrom(map[&K, &V] M)

Synopsis

Get a n arbitrary key from a map.

Description

Returns an arbitrary key of map M.

Examples
rascal>import Map;
ok
rascal>getOneFrom(("apple": 1, "pear": 2, "pineapple": 3));
str: "pineapple"
rascal>getOneFrom(("apple": 1, "pear": 2, "pineapple": 3));
str: "pear"
rascal>getOneFrom(("apple": 1, "pear": 2, "pineapple": 3));
str: "pineapple"

1.7.6. invert

Function

map[&V, set[&K]] invert(map[&K, &V] M)

Synopsis

Invert the (key,value) pairs in a map.

Description

Returns inverted map in which each value in the old map M is associated with a set of key values from the old map. Also see invertUnique.

Examples
rascal>import Map;
ok
rascal>invert(("apple": 1, "pear": 2, "orange": 1));
map[int, set[str]]: (
  1:{"orange","apple"},
  2:{"pear"}
)

1.7.7. invertUnique

Function

map[&V, &K] invertUnique(map[&K, &V] M)

Synopsis

Invert the (key,value) pairs in a map.

Description

Returns a map with key and value inverted; the result should be a map. If the initial map contains duplicate values, the MultipleKey exception is raised since an attempt is made to create a map where more than one value would be associated with the same key.

Also see invert and Exception.

Examples
rascal>import Map;
ok
rascal>invertUnique(("apple": 1, "pear": 2, "orange": 3));
map[int, str]: (1:"apple",3:"orange",2:"pear")

Here is an examples that generates an exception:

rascal>invertUnique(("apple": 1, "pear": 2, "orange": 1));
Exception [debugger cannot break at null frame]: MultipleKey(1)

1.7.8. isEmpty

Function

bool isEmpty(map[&K, &V] M)

Synopsis

Test whether a map is empty.

Description

Returns true if map M is empty, and false otherwise.

Examples
rascal>import Map;
ok
rascal>isEmpty(());
bool: true
rascal>isEmpty(("apple": 1, "pear": 2, "orange": 3));
bool: false

1.7.9. mapper

Function

map[&K, &V] mapper(map[&K, &V] M, &L (&K) F, &W (&V) G)

Synopsis

Apply a function to all (key, value) pairs in a map.

Description

Apply the functions F and G to each key/value pair in a map and return the transformed map.

Examples
rascal>import Map;
ok
rascal>str prefix(str s) { return "X" + s; }
ok
rascal>int incr(int x) { return x + 1; }
ok
rascal>mapper(("apple": 1, "pear": 2, "orange": 3), prefix, incr);
map[str, int]: ("Xapple":2,"Xorange":4,"Xpear":3)

1.7.10. range

Function

set[&V] range(map[&K, &V] M)

Synopsis

The range (set of values that correspond to its keys) of a map.

Description

Returns the range (set of values) of map M.

Examples
rascal>import Map;
ok
rascal>range(("apple": 1, "pear": 2));
set[int]: {1,2}

1.7.11. rangeR

Function

map[&K, &V] rangeR(map[&K, &V] M, set[&V] S)

Synopsis

Map restricted to certain values in (key,values) pairs.

Description

Returns the map restricted to pairs with values in S.

Examples
rascal>import Map;
ok
rascal>rangeR(("apple": 1, "pear": 2, "orange": 3), {2, 3});
map[str, int]: ("pear":2,"orange":3)

1.7.12. rangeX

Function

map[&K, &V] rangeX(map[&K, &V] M, set[&V] S)

Synopsis

Map with certain values in (key,value) pairs excluded.

Description

Returns the map restricted to pairs with values not in S.

Examples
rascal>import Map;
ok
rascal>rangeX(("apple": 1, "pear": 2, "orange": 3), {2, 3});
map[str, int]: ("apple":1)

1.7.13. size

Function

int size(map[&K, &V] M)

Synopsis

Number of (key, value) pairs in a map.

Description

Returns the number of pairs in map M.

Examples
rascal>import Map;
ok
rascal>size(("apple": 1, "pear": 2, "orange": 3));
int: 3

1.7.14. toList

Function

list[tuple[&K, &V]] toList(map[&K, &V] M)

Synopsis

Convert a map to a list of tuples.

Examples
rascal>import Map;
ok
rascal>toList(("apple": 1, "pear": 2, "orange": 3));
lrel[str,int]: [
  <"apple",1>,
  <"orange",3>,
  <"pear",2>
]

1.7.15. toRel

Function
  • rel[&K,&V] toRel(map[&K,set[&V]] M)

  • rel[&K,&V] toRel(map[&K,list[&V]] M)

  • default java rel[&K, &V] toRel(map[&K, &V] M)

Synopsis

Convert a map to a relation.

Examples
rascal>import Map;
ok
rascal>toRel(("apple": 1, "pear": 2, "orange": 3));
rel[str,int]: {
  <"pear",2>,
  <"orange",3>,
  <"apple",1>
}

1.7.16. toString

Function

str toString(map[&K, &V] M)

Synopsis

Convert a map to a string.

Examples
rascal>import Map;
ok
rascal>toString(("apple": 1, "pear": 2, "orange": 3));
str: "(\"pear\":2,\"orange\":3,\"apple\":1)"

1.7.17. itoString

Function

str itoString(map[&K, &V] M)

Synopsis

Convert a map to a indented string.

Examples
rascal>import Map;
ok
rascal>itoString(("apple": 1, "pear": 2, "orange": 3));
str: "(\"pear\":2,\"orange\":3,\"apple\":1)"

1.8. Message

Usage

import Message;

Synopsis

A Message datatype that represents messages in the IDE.

Types
data Message = error(str msg, loc at)
             | warning(str msg, loc at)
             | info(str msg, loc at);
Description

Messages can be used to communicate information about source texts. They can be interpreted by IDEs to display type errors and warnings, etc. Message s are, for instance, used as annotations of algebraic data type. A very common example is to annotate parse trees with messages.

1.8.1. Message

Types
data Message
      = error(str msg, loc at)
      | warning(str msg, loc at)
      | info(str msg, loc at)
      ;
Description

Messages can be used to communicate information about source texts. They can be interpreted by IDE’s to display type errors and warnings, etc.

1.9. Node

Usage

import Node;

Synopsis

Library functions for nodes.

Description

For operators on nodes see Node in the Rascal Language Reference.

The following functions are defined for nodes:

1.9.1. arity

Function

int arity(node T)

Synopsis

Determine the number of children of a node.

Examples
rascal>import Node;
ok
rascal>arity("f"(10, "abc"));
int: 2
rascal>arity("f"(10, "abc", false));
int: 3

1.9.2. delAnnotation

Function

&T <: node delAnnotation(&T <: node x, str label)

Synopsis

Delete a specific annotation from a node.

Examples
rascal>import Node;
ok
rascal>F = setAnnotations("f"(10, "abc"), ("color" : "red", "size" : "large"));
node: "f"(10,"abc")[
  @size="large",
  @color="red"
]
rascal>delAnnotation(F, "size");
node: "f"(10,"abc")[
  @color="red"
]

1.9.3. delAnnotations

Function

&T <: node delAnnotations(&T <: node x)

Synopsis

Delete all annotations from a node.

Examples
rascal>import Node;
ok
rascal>F = setAnnotations("f"(10, "abc"), ("color" : "red", "size" : "large"));
node: "f"(10,"abc")[
  @size="large",
  @color="red"
]
rascal>delAnnotations(F);
node: "f"(10,"abc")

1.9.4. delAnnotationsRec

Function

&T delAnnotationsRec(&T v)

Synopsis

Delete recursively all annotations from all nodes in a value.

Examples
rascal>import Node;
ok
rascal>G = setAnnotations("g"("def"), ("level" : "20", "direction" : "north"));
node: "g"("def")[
  @level="20",
  @direction="north"
]
rascal>F = setAnnotations("f"(10, G), ("color" : "red", "size" : "large"));
node: "f"(
  10,
  "g"("def")[
    @level="20",
    @direction="north"
  ])[
  @size="large",
  @color="red"
]
rascal>delAnnotationsRec(F);
node: "f"(
  10,
  "g"("def"))

1.9.5. getAnnotations

Function

map[str,value] getAnnotations(node x)

Synopsis

Retrieve the annotations of a node value as a map.

Examples
rascal>import Node;
ok

Declare two string-valued annotation on nodes, named color, respectively, size:

rascal>anno str node@color;
[red]##Error: Not supported construct: anno str node@color;##
rascal>anno str node@size;
[red]##Error: Not supported construct: anno str node@size;##

Create a node with two annotations:

rascal>F = setAnnotations("f"(10, "abc"), ("color" : "red", "size" : "large"));
node: "f"(10,"abc")[
  @size="large",
  @color="red"
]

and retrieve those annotations:

rascal>getAnnotations(F);
map[str, str]: ("size":"large","color":"red")
rascal>F@color;
[red]##Error: Annotation color not declared on node or its supertypes IN 'F@color'##

1.9.6. getChildren

Function

list[value] getChildren(node T)

Synopsis

Get the children of a node.

Examples
rascal>import Node;
ok
rascal>getChildren("f"(10, "abc"));
list[value]: [10,"abc"]

1.9.7. getKeywordParameters

Function

map[str,value] getKeywordParameters(node T)

Synopsis

Get the keyword parameters of a node.

Examples
rascal>import Node;
ok
rascal>getKeywordParameters("f"(10, "abc", height=0));
map[str, int]: ("height":0)

1.9.8. setKeywordParameters

Function

&T <: node setKeywordParameters(&T <: node x, map[str,value] keywordParameters)

Synopsis

Set the keyword parameters of a node.

Examples
rascal>import Node;
ok
rascal>setKeywordParameters("f"(10, "abc"), ("height":0));
node: "f"(10,"abc",
  height=0)

1.9.9. getName

Function

str getName(node T)

Synopsis

Determine the name of a node.

Examples
rascal>import Node;
ok
rascal>getName("f"(10, "abc"));
str: "f"

1.9.10. makeNode

Function

node makeNode(str N, value V…​, map[str, value] keywordParameters = ())

Synopsis

Create a node given its function name and arguments.

Examples
rascal>import Node;
ok
rascal>makeNode("f", [10, "abc"]);
node: "f"(10,"abc")

1.9.11. setAnnotations

Function

&T <: node setAnnotations(&T <: node x, map[str, value] annotations)

Synopsis

Add a map of annotations to a node value.

Description

Set the annotations on node value x as described by the map annotations.

Examples
rascal>import Node;
ok
rascal>setAnnotations("f"(10, "abc"), ("color" : "red", "size" : "large"));
node: "f"(10,"abc")[
  @size="large",
  @color="red"
]
Pitfalls

This function may result in run-time type errors later if you store a value with a label that has an incomparable annotation type declared.

1.9.12. unset

Function
  • &T <: node unset(&T <: node x, str label)

  • &T <: node unset(&T <: node x)

Synopsis

Set a specific parameter back to default on a node.

1.9.13. unsetRec

Function

&T <: node unsetRec(&T <: node x)

1.9.14. toString

Function

str toString(node T)

Synopsis

Convert a node to a string.

Examples
rascal>import Node;
ok
rascal>F = setAnnotations("f"(10, "abc"), ("color" : "red", "size" : "large"));
node: "f"(10,"abc")[
  @size="large",
  @color="red"
]
rascal>toString(F);
str: "\"f\"(10,\"abc\")[@size=\"large\",@color=\"red\"]"

1.9.15. itoString

Function

str itoString(node T)

Synopsis

Convert a node to an indented string.

Examples
rascal>import Node;
ok
rascal>F = setAnnotations("f"(10, "abc"), ("color" : "red", "size" : "large"));
node: "f"(10,"abc")[
  @size="large",
  @color="red"
]
rascal>itoString(F);
str: "\"f\"(10,\"abc\")[\n  @size=\"large\",\n  @color=\"red\"\n]"

1.10. ParseTree

Usage

import ParseTree;

Synopsis

Library functions for parse trees.

Description

A concrete syntax tree or parse tree is an ordered, rooted tree that represents the syntactic structure of a string according to some formal grammar.

Most Rascal users will encounter parse trees in the form of concrete values. Expert users may find the detailed description here useful when writing generic functions on parse trees.

In Rascal parse trees, the interior nodes are labeled by rules of the grammar, while the leaf nodes are labeled by terminals (characters) of the grammar.

Tree is the universal parse tree data type in Rascal and can be used to represent parse trees for any language.

  • Tree is a subtype of the type node.

  • All types (non-terminals) declared in syntax definitions are sub-types of Tree.

  • All concrete syntax expressions produce parse trees with a type corresponding to a non-terminals.

  • Trees can be annotated in various ways, see features for IDE construction. Most importantly the \loc annotation always points to the source location of any (sub) parse tree.

Parse trees are usually analyzed and constructed using concrete syntax expressions and concrete syntax patterns.

Advanced users may want to create tools that analyze any parse tree, regardless of the syntax definition that generated it, you can manipulate them on the abstract level.

A parse tree is of type Tree using the auxiliary types Production, Symbol, Condition, Attr, Associativity, CharRange. Effectively, a parse tree is a nested tree structure of type Tree.

  • Most internal nodes are applications (appl) of a Production to a list of children Tree nodes. Production is the abstract representation of a rule in a syntax definition, which consists of a definition of an alternative for a Symbol by a list of Symbols.

  • The leaves of a parse tree are always characters (char), which have an integer index in the UTF8 table.

  • Some internal nodes encode ambiguity (amb) by pointing to a set of alternative Tree nodes.

The Production and Symbol types are an abstract notation for rules in syntax definitions, while the Tree type is the actual notation for parse trees.

Parse trees are called parse forests when they contain amb nodes.

You can analyze and manipulate parse trees in three ways:

The type of a parse tree is the symbol that it’s production produces, i.e. appl(prod(sort("A"),[],{}),[]) has type A. Ambiguity nodes Each such a non-terminal type has Tree as its immediate super-type.

Examples
rascal>import ParseTree;
ok
rascal>syntax A = "a";
ok

will make the following succeed:

rascal>parse(#A,"a") ==
>>>>>>>appl(
>>>>>>>  prod(
>>>>>>>    sort("A"),
>>>>>>>    [lit("a")],
>>>>>>>    {}),
>>>>>>>  [appl(
>>>>>>>      prod(
>>>>>>>        lit("a"),
>>>>>>>        [\char-class([range(97,97)])],
>>>>>>>        {}),
>>>>>>>      [char(97)])]);
bool: true

You see that the defined non-terminal A ends up as the production for the outermost node. As the only child is the tree for recognizing the literal a, which is defined to be a single a from the character-class [ a ].

When we use labels in the definitions, they also end up in the trees. The following definition

rascal>import ParseTree;
ok
rascal>lexical B= myB:"b";
ok
rascal>lexical C = myC:"c" B bLabel;
ok

Will make the following succeed:

rascal>parse(#C,"cb") ==
>>>>>>>appl(
>>>>>>>  prod(
>>>>>>>    label(
>>>>>>>      "myC",
>>>>>>>      lex("C")),
>>>>>>>    [
>>>>>>>      lit("c"),
>>>>>>>      label(
>>>>>>>        "bLabel",
>>>>>>>        lex("B"))
>>>>>>>    ],
>>>>>>>    {}),
>>>>>>>  [appl(
>>>>>>>      prod(
>>>>>>>        lit("c"),
>>>>>>>        [\char-class([range(99,99)])],
>>>>>>>        {}),
>>>>>>>      [char(99)]),appl(
>>>>>>>      prod(
>>>>>>>        label(
>>>>>>>          "myB",
>>>>>>>          lex("B")),
>>>>>>>        [lit("b")],
>>>>>>>        {}),
>>>>>>>      [appl(
>>>>>>>          prod(
>>>>>>>            lit("b"),
>>>>>>>            [\char-class([range(98,98)])],
>>>>>>>            {}),
>>>>>>>          [char(98)])])]);
bool: true

Here you see that the alternative name is a label around the first argument of prod while argument labels become labels in the list of children of a prod.

Pitfalls

For historical reasons the name of the annotation is "loc" and this interferes with the Rascal keyword loc for the type of source locations. Therefore the annotation name has to be escaped as \loc when it is declared or used.

The following functions and data types are declared for ParseTrees:

1.10.1. Tree

Types
data Tree
      = appl(Production prod, list[Tree] args)
      | cycle(Symbol symbol, int cycleLength)
      | amb(set[Tree] alternatives)
      | char(int character)
      ;
Synopsis

The Tree data type as produced by the parser.

Description

A Tree defines the trees normally found after parsing; additional constructors exist for execptional cases:

1 Parse tree constructor when parse succeeded.
2 Cyclic parsetree.
3 Ambiguous subtree.
4 A single character.

1.10.2. Production

Types
data Production
      = prod(Symbol def, list[Symbol] symbols, set[Attr] attributes)
      | regular(Symbol def)
      | error(Production prod, int dot)
      | skipped()
      ;
Synopsis

Production in ParseTrees

Description

The type Production is introduced in Type, see Production. Here we extend it with the symbols that can occur in a ParseTree. We also extend productions with basic combinators allowing to construct ordered and un-ordered compositions, and associativity groups.

1 A prod is a rule of a grammar, with a defined non-terminal, a list of terminal and/or non-terminal symbols and a possibly empty set of attributes.
2 A regular is a regular expression, i.e. a repeated construct.
3 A error represents a parse error.
4 A skipped represents skipped input during error recovery.
5 priority means ordered choice, where alternatives are tried from left to right;
6 assoc means all alternatives are acceptable, but nested on the declared side;
7 others means '…​', which is substituted for a choice among the other definitions;
8 reference means a reference to another production rule which should be substituted there, for extending priority chains and such.

1.10.3. Production

Types
data Production
      = \priority(Symbol def, list[Production] choices)
      | \associativity(Symbol def, Associativity \assoc, set[Production] alternatives)
      | \others(Symbol def)
      | \reference(Symbol def, str cons)
      ;

1.10.4. Attr

Types
data Attr
      = \assoc(Associativity \assoc)
      | \bracket()
      ;
Synopsis

Attributes in productions.

Description

An Attr (attribute) documents additional semantics of a production rule. Neither tags nor brackets are processed by the parser generator. Rather downstream processors are activated by these. Associativity is a parser generator feature though.

1.10.5. Associativity

Types
data Associativity
      = \left()
      | \right()
      | \assoc()
      | \non-assoc()
      ;
Synopsis

Associativity attribute.

Description

Associativity defines the various kinds of associativity of a specific production.

1.10.6. CharRange

Types
data CharRange
      = range(int begin, int end)
      ;
Synopsis

Character ranges and character class .Description

  • CharRange defines a range of characters.

  • A CharClass consists of a list of characters ranges.

1.10.7. CharClass

Types

list[CharRange]

1.10.8. Symbol

Types
data Symbol
      = \start(Symbol symbol)
      ;
Synopsis

Symbols that can occur in a ParseTree

Description

The type Symbol is introduced in Type, see Symbol, to represent the basic Rascal types, e.g., int, list, and rel. Here we extend it with the symbols that may occur in a ParseTree.

1 The start symbol wraps any symbol to indicate that it is a start symbol of the grammar and may occur at the root of a parse tree.
2 Context-free non-terminal
3 Lexical non-terminal
4 Layout symbols
5 Terminal symbols that are keywords
6 Parameterized context-free non-terminal
7 Parameterized lexical non-terminal
8 Terminal.
9 Case-insensitive terminal.
10 Character class
11 Empty symbol
12 Optional symbol
13 List of one or more symbols without separators
14 List of zero or more symbols without separators
15 List of one or more symbols with separators
16 List of zero or more symbols with separators
17 Alternative of symbols
18 Sequence of symbols
19 Conditional occurrence of a symbol.

1.10.9. Symbol

Types
data Symbol
      = \sort(str name)
      | \lex(str name)
      | \layouts(str name)
      | \keywords(str name)
      | \parameterized-sort(str name, list[Symbol] parameters)
      | \parameterized-lex(str name, list[Symbol] parameters)
      ;

1.10.10. Symbol

Types
data Symbol
      = \lit(str string)
      | \cilit(str string)
      | \char-class(list[CharRange] ranges)
      ;

1.10.11. Symbol

Types
data Symbol
      = \empty()
      | \opt(Symbol symbol)
      | \iter(Symbol symbol)
      | \iter-star(Symbol symbol)
      | \iter-seps(Symbol symbol, list[Symbol] separators)
      | \iter-star-seps(Symbol symbol, list[Symbol] separators)
      | \alt(set[Symbol] alternatives)
      | \seq(list[Symbol] symbols)
      ;

1.10.12. Symbol

Types
data Symbol
      = \conditional(Symbol symbol, set[Condition] conditions)
      ;

1.10.13. subtype

Function

bool subtype(Symbol::\sort(_), Symbol::\adt("Tree", _))

1.10.14. Condition

Types
data Condition
      = \follow(Symbol symbol)
      | \not-follow(Symbol symbol)
      | \precede(Symbol symbol)
      | \not-precede(Symbol symbol)
      | \delete(Symbol symbol)
      | \at-column(int column)
      | \begin-of-line()
      | \end-of-line()
      | \except(str label)
      ;
Synopsis

Datatype for declaring preconditions and postconditions on symbols

Description

A Condition can be attached to a symbol; it restricts the applicability of that symbol while parsing input text. For instance, follow requires that it is followed by another symbol and at-column requires that it occurs at a certain position in the current line of the input text.

1.10.15. priority

Function

Production priority(Symbol s, [*Production a, priority(Symbol t, list[Production] b), *Production c])

Synopsis

Nested priority is flattened.

1.10.16. associativity

Function
  • Production associativity(Symbol s, Associativity as, {*Production a, choice(Symbol t, set[Production] b)})

  • Production associativity(Symbol rhs, Associativity a, {associativity(rhs, Associativity b, set[Production] alts), *Production rest})

  • Production associativity(Symbol rhs, Associativity a, set[Production] rest)

  • Production associativity(Symbol s, Associativity as, {*Production a, priority(Symbol t, list[Production] b)})

Synopsis

Normalization of associativity.

Description
  • Choice (see the choice constructor in [Type-ParseTree]) under associativity is flattened.

  • Nested (equal) associativity is flattened.

  • Priority under an associativity group defaults to choice.

1.10.17. parse

Function
  • &T<:Tree parse(type[&T<:Tree] begin, str input, bool allowAmbiguity=false)

  • &T<:Tree parse(type[&T<:Tree] begin, str input, loc origin, bool allowAmbiguity=false)

  • &T<:Tree parse(type[&T<:Tree] begin, loc input, bool allowAmbiguity=false)

Synopsis

Parse input text (from a string or a location) and return a parse tree.

Description
  • Parse a string and return a parse tree.

  • Parse a string and return a parse tree, origin defines the original location of the input.

  • Parse the contents of resource input and return a parse tree.

Examples
rascal>import demo::lang::Exp::Concrete::NoLayout::Syntax;
ok
rascal>import ParseTree;
ok

Seeing that parse returns a parse tree:

rascal>parse(#Exp, "2+3");
Exp: (Exp) 2+3

Catching a parse error:

rascal>import IO;
ok
rascal>try {
>>>>>>>  Exp e = parse(#Exp, "2@3");
>>>>>>>}
>>>>>>>catch ParseError(loc l): {
>>>>>>>  println("I found a parse error at line <l.begin.line>, column <l.begin.column>");
>>>>>>>}
I found a parse error at line 1, column 1

1.10.18. unparse

Function

str unparse(Tree tree)

Synopsis

Yield the string of characters that form the leafs of the given parse tree.

Description

unparse is the inverse function of parse, i.e., for every syntactically correct string TXT of type S, the following holds:

unparse(parse(#S, TXT)) == TXT
Examples
rascal>import demo::lang::Exp::Concrete::NoLayout::Syntax;
ok
rascal>import ParseTree;
ok

First parse an expression, this results in a parse tree. Then unparse this parse tree:

rascal>unparse(parse(#Exp, "2+3"));
str: "2+3"

1.10.19. saveParser

Function

str saveParser(loc outFile)

Synopsis

Save the current object parser to a file.

Description

saveParser will save the current object parser (constructed from (imported) syntax declarations) to a file. The name of the parser class is returned, for reference.

The saved parser can be used later on by loading the parser class from the JAR file, instantiating it and calling the parse() method.

Examples
import ParseTree;
import demo::lang::Exp::Concrete::NoLayout::Syntax; (1)

saveParser(|file:///tmp/Exp.jar|); (2)
1 Import a grammar.
2 Save the parser to a JAR file.

1.10.20. printSymbol

Function

str printSymbol(Symbol sym, bool withLayout)

1.10.21. implode

Function

&T<:value implode(type[&T<:value] t, Tree tree)

Synopsis

Implode a parse tree according to a given (ADT) type.

Description

Given a grammar for a language, its sentences can be parsed and the result is a parse tree (or more precisely a value of type Tree). For many applications this is sufficient and the results are achieved by traversing and matching them using concrete patterns.

In other cases, the further processing of parse trees is better done in a more abstract form. The abstract syntax for a language is a data type that is used to represent programs in the language in an abstract form. Abstract syntax has the following properties:

  • It is "abstract" in the sense that it does not contain textual details such as parentheses, layout, and the like.

  • While a language has one grammar (also known as, concrete syntax) it may have several abstract syntaxes for different purposes: type analysis, code generation, etc.

The function implode bridges the gap between parse tree and abstract syntax tree. Given a parse tree and a Rascal type it traverses them simultaneously and constructs an abstract syntax tree (a value of the given type) as follows:

  • Literals, layout and empty (i.e. ()) nodes are skipped.

  • Regular */+ lists are imploded to `list`s or `set`s depending on what is expected in the ADT.

  • Ambiguities are imploded to `set`s.

  • If the expected type is str the tree is unparsed into a string. This happens for both lexical and context-free parse trees.

  • If a tree’s production has no label and a single AST (i.e. non-layout, non-literal) argument (for instance, an injection), the tree node is skipped, and implosion continues with the lone argument. The same applies to bracket productions, even if they are labeled.

  • If a tree’s production has no label, but more than one argument, the tree is imploded to a tuple (provided this conforms to the ADT).

  • Optionals are imploded to booleans if this is expected in the ADT. This also works for optional literals, as shown in the example below.

  • An optional is imploded to a list with zero or one argument, iff a list type is expected.

  • If the argument of an optional tree has a production with no label, containing a single list, then this list is spliced into the optional list.

  • For trees with (cons-)labeled productions, the corresponding constructor in the ADT corresponding to the non-terminal of the production is found in order to make the AST.

  • If the provided type is node, (cons-)labeled trees will be imploded to untyped `node`s. This means that any subtrees below it will be untyped nodes (if there is a label), tuples of nodes (if a label is absent), and strings for lexicals.

  • Unlabeled lexicals are imploded to str, int, real, bool depending on the expected type in the ADT. To implode lexical into types other than str, the PDB parse functions for integers and doubles are used. Boolean lexicals should match "true" or "false". NB: lexicals are imploded this way, even if they are ambiguous.

  • If a lexical tree has a cons label, the tree imploded to a constructor with that name and a single string-valued argument containing the tree’s yield.

An IllegalArgument exception is thrown if during implosion a tree is encountered that cannot be imploded to the expected type in the ADT. As explained above, this function assumes that the ADT type names correspond to syntax non-terminal names, and constructor names correspond to production labels. Labels of production arguments do not have to match with labels in ADT constructors.

Finally, source location annotations are propagated as annotations on constructor ASTs. To access them, the user is required to explicitly declare a location annotation on all ADTs used in implosion. In other words, for every ADT type T, add:

anno loc T@location;
Examples

Here are some examples for the above rules.

Example for rule 5

Given the grammar

syntax IDTYPE = Id ":" Type;
syntax Decls = decls: "declare" {IDTYPE ","}* ";";

Decls will be imploded as:

data Decls = decls(list[tuple[str,Type]]);

(assuming Id is a lexical non-terminal).

Example for rule 6

Given the grammar

syntax Formal = formal: "VAR"? {Id ","}+ ":" Type;

The corresponding ADT could be:

data Formal = formal(bool, list[str], Type);
Example for rule 8

Given the grammar

syntax Tag = "[" {Modifier ","}* "]";
syntax Decl = decl: Tag? Signature Body;

In this case, a Decl is imploded into the following ADT:

data Decl = decl(list[Modifier], Signature, Body);
Example for rule 9

Given the grammar

syntax Exp = left add: Exp "+" Exp;

Can be imploded into:

data Exp = add(Exp, Exp);

1.10.22. TreeSearchResult

Types
data TreeSearchResult[&T<:Tree]
      = treeFound(&T tree)
      | treeNotFound()
      ;
Synopsis

Tree search result type for treeAt.

1.10.23. treeAt

Function
  • TreeSearchResult[&T<:Tree] treeAt(type[&T<:Tree] t, loc l, a:appl(_, _))

  • default TreeSearchResult[&T<:Tree] treeAt(type[&T<:Tree] t, loc l, Tree root)

Synopsis

Select the innermost Tree of a given type which is enclosed by a given location.

1.10.24. sameType

Function
  • bool sameType(label(_,Symbol s),Symbol t)

  • bool sameType(Symbol s,label(_,Symbol t))

  • bool sameType(Symbol s,conditional(Symbol t,_))

  • bool sameType(conditional(Symbol s,_), Symbol t)

  • bool sameType(Symbol s, s)

  • default bool sameType(Symbol s, Symbol t)

1.10.25. isNonTerminalType

Function
  • bool isNonTerminalType(Symbol::\sort(str _))

  • bool isNonTerminalType(Symbol::\lex(str _))

  • bool isNonTerminalType(Symbol::\layouts(str _))

  • bool isNonTerminalType(Symbol::\keywords(str _))

  • bool isNonTerminalType(Symbol::\parameterized-sort(str _, list[Symbol] _))

  • bool isNonTerminalType(Symbol::\parameterized-lex(str _, list[Symbol] _))

  • bool isNonTerminalType(Symbol::\start(Symbol s))

  • default bool isNonTerminalType(Symbol s)

Synopsis

Determine if the given type is a non-terminal type.

1.11. Relation

Usage

import Relation;

Synopsis

Library functions for relations.

Description

For operators on relations see Relation in the Rascal Language Reference.

The following functions are defined for relations:

1.11.1. carrier

Function
  • set[&T] carrier (rel[&T,&T] R)

  • set[&T] carrier (rel[&T,&T,&T] R)

  • set[&T] carrier (rel[&T,&T,&T,&T] R)

  • set[&T] carrier (rel[&T,&T,&T,&T,&T] R)

Synopsis

Return the set of all elements in any tuple in a relation.

Examples
rascal>import Relation;
ok
rascal>carrier({<1,10>, <2,20>});
set[int]: {10,1,20,2}
rascal>carrier({<1,10,100,1000>, <2,20,200,2000>});
set[int]: {10,200,20,2,100,1000,1,2000}

1.11.2. carrierR

Function
  • rel[&T,&T] carrierR (rel[&T,&T] R, set[&T] S)

  • rel[&T,&T,&T] carrierR (rel[&T,&T,&T] R, set[&T] S)

  • rel[&T,&T,&T,&T] carrierR (rel[&T,&T,&T,&T] R, set[&T] S)

  • rel[&T,&T,&T,&T,&T] carrierR (rel[&T,&T,&T,&T,&T] R, set[&T] S)

Synopsis

A relation restricted to certain element values in tuples.

Description

Returns relation R restricted to tuples with elements in set S.

Examples
rascal>import Relation;
ok
rascal>carrierR({<1,10>, <2,20>, <3,30>}, {10, 1, 20});
rel[int,int]: {<1,10>}

1.11.3. carrierX

Function
  • rel[&T,&T] carrierX (rel[&T,&T] R, set[&T] S)

  • rel[&T,&T,&T] carrierX (rel[&T,&T,&T] R, set[&T] S)

  • rel[&T,&T,&T,&T] carrierX (rel[&T,&T,&T,&T] R, set[&T] S)

  • rel[&T,&T,&T,&T,&T] carrierX (rel[&T,&T,&T,&T,&T] R, set[&T] S)

Synopsis

A relation excluded tuples containing certain values.

Description

Returns relation R excluding tuples with some element in S.

Examples
rascal>import Relation;
ok
rascal>carrierX({<1,10>, <2,20>, <3,30>}, {10, 1, 20});
rel[int,int]: {<3,30>}

1.11.4. complement

Function
  • rel[&T0, &T1] complement(rel[&T0, &T1] R)

  • rel[&T0, &T1, &T2] complement(rel[&T0, &T1, &T2] R)

  • rel[&T0, &T1, &T2, &T3] complement(rel[&T0, &T1, &T2, &T3] R)

  • rel[&T0, &T1, &T2, &T3, &T4] complement(rel[&T0, &T1, &T2, &T3, &T4] R)

Synopsis

Complement of a relation.

Description

Given a relation R a new relation U can be constructed that contains all possible tuples with element values that occur at corresponding tuple positions in R. The function complement returns the complement of R relative to U, in other words: U - R.

Examples
rascal>import Relation;
ok

Declare R and compute corresponding U:

rascal>R = {<1,10>, <2, 20>, <3, 30>};
rel[int,int]: {
  <1,10>,
  <3,30>,
  <2,20>
}
rascal>U = domain(R) * range(R);
rel[int,int]: {
  <1,10>,
  <1,20>,
  <1,30>,
  <3,10>,
  <3,20>,
  <3,30>,
  <2,10>,
  <2,20>,
  <2,30>
}

Here is the complement of R computed in two ways:

rascal>U - R;
rel[int,int]: {
  <1,20>,
  <1,30>,
  <3,10>,
  <3,20>,
  <2,10>,
  <2,30>
}
rascal>complement({<1,10>, <2, 20>, <3, 30>});
rel[int,int]: {
  <1,20>,
  <1,30>,
  <3,10>,
  <3,20>,
  <2,10>,
  <2,30>
}

1.11.5. domain

Function
  • set[&T0] domain (rel[&T0,&T1] R)

  • set[&T0] domain (rel[&T0,&T1,&T2] R)

  • set[&T0] domain (rel[&T0,&T1,&T2,&T3] R)

  • set[&T0] domain (rel[&T0,&T1,&T2,&T3,&T4] R)

Synopsis

Domain of a relation: a set consisting of the first element of each tuple.

Examples
rascal>import Relation;
ok
rascal>domain({<1,10>, <2,20>});
set[int]: {1,2}
rascal>domain({<"mon", 1>, <"tue", 2>});
set[str]: {"tue","mon"}

1.11.6. domainR

Function
  • rel[&T0,&T1] domainR (rel[&T0,&T1] R, set[&T0] S)

  • rel[&T0,&T1,&T2] domainR (rel[&T0,&T1,&T2] R, set[&T0] S)

  • rel[&T0,&T1,&T2,&T3] domainR (rel[&T0,&T1,&T2,&T3] R, set[&T0] S)

  • rel[&T0,&T1,&T2,&T3,&T4] domainR (rel[&T0,&T1,&T2,&T3,&T4] R, set[&T0] S)

Synopsis

Relation restricted to certain domain elements.

Description

Restriction of a relation R to tuples with first element in S.

Examples
rascal>import Relation;
ok
rascal>domainR({<1,10>, <2,20>, <3,30>}, {3, 1});
rel[int,int]: {
  <1,10>,
  <3,30>
}

1.11.7. domainX

Function
  • rel[&T0,&T1] domainX (rel[&T0,&T1] R, set[&T0] S)

  • rel[&T0,&T1,&T2] domainX (rel[&T0,&T1,&T2] R, set[&T0] S)

  • rel[&T0,&T1,&T2,&T3] domainX (rel[&T0,&T1,&T2,&T3] R, set[&T0] S)

  • rel[&T0,&T1,&T2,&T3,&T4] domainX (rel[&T0,&T1,&T2,&T3,&T4] R, set[&T0] S)

Synopsis

Relation excluding certain domain values.

Description

Relation R excluded tuples with first element in S.

Examples
rascal>import Relation;
ok
rascal>domainX({<1,10>, <2,20>, <3,30>}, {3, 1});
rel[int,int]: {<2,20>}

1.11.8. groupDomainByRange

Function

set[set[&U]] groupDomainByRange(rel[&U dom, &T ran] input)

Synopsis

Make sets of elements in the domain that relate to the same element in the range.

Examples
rascal>import Relation;
ok
rascal>legs = {<"bird", 2>, <"dog", 4>, <"human", 2>, <"spider", 8>, <"millepede", 1000>, <"crab", 8>, <"cat", 4>};
rel[str,int]: {
  <"spider",8>,
  <"human",2>,
  <"crab",8>,
  <"cat",4>,
  <"bird",2>,
  <"dog",4>,
  <"millepede",1000>
}
rascal>groupDomainByRange(legs);
set[set[str]]: {
  {"human","bird"},
  {"cat","dog"},
  {"spider","crab"},
  {"millepede"}
}

1.11.9. groupRangeByDomain

Function

set[set[&T]] groupRangeByDomain(rel[&U dom, &T ran] input)

Synopsis

Make sets of elements in the range that relate to the same element in the domain.

Description
rascal>import Relation;
ok
rascal>skins = {<"bird", "feather">, <"dog", "fur">, <"tortoise", "shell">, <"human", "skin">, <"fish", "scale">, <"lizard", "scale">, <"crab", "shell">, <"cat", "fur">};
rel[str,str]: {
  <"tortoise","shell">,
  <"human","skin">,
  <"crab","shell">,
  <"fish","scale">,
  <"bird","feather">,
  <"dog","fur">,
  <"lizard","scale">,
  <"cat","fur">
}
rascal>groupRangeByDomain(skins);
set[set[str]]: {
  {"scale"},
  {"shell"},
  {"skin"},
  {"feather"},
  {"fur"}
}

1.11.10. ident

Function

rel[&T, &T] ident (set[&T] S)

Synopsis

The identity relation.

Description

The identity relation for set S.

Examples
rascal>import Relation;
ok
rascal>ident({"mon", "tue", "wed"});
rel[str,str]: {
  <"tue","tue">,
  <"mon","mon">,
  <"wed","wed">
}

1.11.11. invert

Function
  • rel[&T1, &T0] invert (rel[&T0, &T1] R)

  • rel[&T2, &T1, &T0] invert (rel[&T0, &T1, &T2] R)

  • rel[&T3, &T2, &T1, &T0] invert (rel[&T0, &T1, &T2, &T3] R)

  • rel[&T4, &T3, &T2, &T1, &T0] invert (rel[&T0, &T1, &T2, &T3, &T4] R)

Synopsis

Invert the tuples in a relation.

Examples
rascal>import Relation;
ok
rascal>invert({<1,10>, <2,20>});
rel[int,int]: {
  <10,1>,
  <20,2>
}

1.11.12. range

Function
  • set[&T1] range (rel[&T0,&T1] R)

  • rel[&T1,&T2] range (rel[&T0,&T1, &T2] R)

  • rel[&T1,&T2,&T3] range (rel[&T0,&T1,&T2,&T3] R)

  • rel[&T1,&T2,&T3,&T4] range (rel[&T0,&T1,&T2,&T3,&T4] R)

Synopsis

The range (i.e., all but the first element of each tuple) of a relation.

Examples
rascal>import Relation;
ok
rascal>range({<1,10>, <2,20>});
set[int]: {10,20}
rascal>range({<"mon", 1>, <"tue", 2>});
set[int]: {1,2}

1.11.13. rangeR

Function

rel[&T0,&T1] rangeR (rel[&T0,&T1] R, set[&T2] S)

Synopsis

Relation restricted to certain range values.

Description

Restriction of binary relation R to tuples with second element in set S.

Examples
rascal>import Relation;
ok
rascal>rangeR({<1,10>, <2,20>, <3,30>}, {30, 10});
rel[int,int]: {
  <1,10>,
  <3,30>
}

1.11.14. rangeX

Function

rel[&T0,&T1] rangeX (rel[&T0,&T1] R, set[&T2] S)

Synopsis

Relation excluding certain range values.

Description

Restriction of binary relation R to tuples with second element not in set S.

Examples
rascal>import Relation;
ok
rascal>rangeX({<1,10>, <2,20>, <3,30>}, {30, 10});
rel[int,int]: {<2,20>}

1.11.15. index

Function

map[&K, set[&V]] index(rel[&K, &V] R)

Synopsis

Indexes a binary relation as a map

Description

Converts a binary relation to a map of the domain to a set of the range.

Examples
rascal>import Relation;
ok
rascal>index({<1,10>, <2,20>, <3,30>, <30,10>});
map[int, set[int]]: (
  1:{10},
  3:{30},
  2:{20},
  30:{10}
)

1.12. Set

Usage

import Set;

Synopsis

Library functions for sets.

Description

For operators on sets see Set in the Rascal Language Reference.

The following functions are defined for sets:

  • classify: Classify elements in a set.

  • getOneFrom: Pick a random element from a set.

  • getFirstFrom: Get "first" element from a set.

  • group: Group elements in a set given an equivalence function.

  • index: Map set elements to a fixed index.

  • isEmpty: Test whether a set is empty.

  • mapper: Apply a function to all set elements and return set of results.

  • max: Determine the largest element of a set.

  • min: Determine the smallest element of a set.

  • power: Determine the powerset of a set.

  • power1: The powerset (excluding the empty set) of a set value.

  • reducer: Apply a function to successive elements of a set and combine the results (deprecated).

  • size: Determine the number of elements in a set.

  • sum:

  • sum: Sum the elements of a set.

  • getOneFrom: Pick an arbitrary element from a set.

  • takeOneFrom: Remove an arbitrary element from a set, returns the element and a set without that element.

  • takeFirstFrom: Remove "first" element from a set, returns the element and a set without that element.

  • toList: Convert a set to a list.

  • toMap: Convert a set of tuples to a map; each key is associated with a set of values.

  • toMapUnique: Convert a set of tuples to a map (provided that there are no multiple keys).

  • toString: Convert a set to a string.

  • itoString: Convert a set to an indented string.

  • sort: Sort the elements of a set.

  • sort:

  • union: Flatten a set of sets into a single set

1.12.1. classify

Function

map[&K,set[&V]] classify(set[&V] input, &K (&V) getClass)

Synopsis

Classify elements in a set.

Examples

We classify animals by their number of legs.

rascal>import Set;
ok

Create a map from animals to number of legs.

rascal>legs = ("bird": 2, "dog": 4, "human": 2, "snake": 0, "spider": 8, "millepede": 1000, "crab": 8, "cat": 4);
map[str, int]: ("snake":0,"spider":8,"human":2,"crab":8,"cat":4,"bird":2,"dog":4,"millepede":1000)

Define function nLegs that returns the number of legs for each animal (or 0 when the animal is unknown):

rascal>int nLegs(str animal){
>>>>>>>    return legs[animal] ? 0;
>>>>>>>}
ok

Now classify a set of animals:

rascal>classify({"bird", "dog", "human", "spider", "millepede", "zebra", "crab", "cat"}, nLegs);
map[int, set[str]]: (
  8:{"spider","crab"},
  2:{"human","bird"},
  4:{"cat","dog"},
  1000:{"millepede"},
  0:{"zebra"}
)

1.12.2. getOneFrom

Function

&T getOneFrom(set[&T] st) throws EmptySet

Synopsis

Pick a random element from a set.

Examples
rascal>import Set;
ok
rascal>getOneFrom({1,2,3,4});
int: 3
rascal>getOneFrom({1,2,3,4});
int: 4
rascal>getOneFrom({1,2,3,4});
int: 1
rascal>getOneFrom({1,2,3,4});
int: 4

1.12.3. getFirstFrom

Function

&T getFirstFrom(set[&T] st) throws EmptySet

Synopsis

Get "first" element from a set.

Description

Get "first" element of a set. Of course, sets are unordered and do not have a first element. However, we may assume that sets are internally ordered in some way and this ordering is reproducible. Applying getFirstFrom on the same set will always returns the same element.

Benefits

This function helps to make set-based code more deterministic, for instance, for testing purposes.

1.12.4. group

Function

set[set[&T]] group(set[&T] input, bool (&T a, &T b) similar)

Synopsis

Group elements in a set given an equivalence function.

Examples

We classify animals by their number of legs.

rascal>import Set;
ok

Create a map from animals to number of legs.

rascal>legs = ("bird": 2, "dog": 4, "human": 2, "snake": 0, "spider": 8, "millepede": 1000, "crab": 8, "cat": 4);
map[str, int]: ("snake":0,"spider":8,"human":2,"crab":8,"cat":4,"bird":2,"dog":4,"millepede":1000)

Define function nLegs that returns the number of legs fro each animal (or 0 when the animal is unknown):

rascal>int nLegs(str animal){
>>>>>>>    return legs[animal] ? 0;
>>>>>>>}
ok
rascal>bool similar(str a, str b) = nLegs(a) == nLegs(b);
ok

Now group a set of animals:

rascal>group({"bird", "dog", "human", "spider", "millepede", "zebra", "crab", "cat"}, similar);
Call stack (most recent first):
	group({"spider","zebra","human","crab","cat","bird","dog","millepede"}, OverloadedFunctionInstance[functions: ConsoleInput/similar(str();str();)#7/13], {})
		at |file:///export/scratch1/jenkins/home/workspace/usethesource_rascal_master-S5ZKBVP7G6AAXOCX5AHV2IJ2QL35PDF5FJHTCPD6ZB5NPZDM4Q3Q/src/org/rascalmpl/library/Set.rsc|(3413,65,<128,10>,<128,75>)
	main([])
An unexpected internal error occurred:
java.lang.RuntimeException: org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.InternalCompilerError: RascalPrimitive add: Illegal type combination: STR and LIST
	at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RVMonJVM.dynRun(RVMonJVM.java:548)
	at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RVMonJVM.executeRVMProgram(RVMonJVM.java:239)
	at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RVMJVM.executeRVMProgram(RVMJVM.java:137)
	at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.ExecutionTools.executeProgram(ExecutionTools.java:142)
	at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.ExecutionTools.executeProgram(ExecutionTools.java:101)
	at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.repl.CommandExecutor.executeModule(CommandExecutor.java:387)
	at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.repl.CommandExecutor.evalStatement(CommandExecutor.java:520)
	at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.repl.CommandExecutor.eval(CommandExecutor.java:441)
	at org.rascalmpl.library.experiments.tutor3.TutorCommandExecutor.evalPrint(TutorCommandExecutor.java:75)
	at org.rascalmpl.library.experiments.tutor3.Concept.preprocess(Concept.java:264)
	at org.rascalmpl.library.experiments.tutor3.Onthology.<init>(Onthology.java:131)
	at org.rascalmpl.library.experiments.tutor3.CourseCompiler.compileCourse(CourseCompiler.java:92)
	at org.rascalmpl.library.experiments.tutor3.CourseCompiler.main(CourseCompiler.java:258)
Caused by: org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.InternalCompilerError: RascalPrimitive add: Illegal type combination: STR and LIST
	at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RascalPrimitive$33.execute2(RascalPrimitive.java:805)
	at .ConsoleInput$Compiled.Set\group(set(parameter("T",value())(@boundGiven=false)):func(bool(),(label("a",parameter("T",value())(@boundGiven=false)),label("b",parameter("T",value())(@boundGiven=false))),()):)#94(Unknown Source)
	at .ConsoleInput$Compiled.ConsoleInput\main()#0(Unknown Source)
	at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RVMonJVM.dynRun(RVMonJVM.java:543)
	... 12 more
check compiler.

1.12.5. index

Function

map[&T,int] index(set[&T] s)

Synopsis

Map set elements to a fixed index.

Examples
rascal>import Set;
ok
rascal>index({"elephant", "zebra", "snake"});
map[str, int]: ("snake":2,"zebra":1,"elephant":0)

1.12.6. isEmpty

Function

bool isEmpty(set[&T] st)

Synopsis

Test whether a set is empty.

Description

Yields true if s is empty, and false otherwise.

Examples
rascal>import Set;
ok
rascal>isEmpty({1, 2, 3});
bool: false
rascal>isEmpty({});
bool: true

1.12.7. mapper

Function

set[&U] mapper(set[&T] st, &U (&T) fn)

Synopsis

Apply a function to all set elements and return set of results.

Description

Return a set obtained by applying function fn to all elements of set s.

Examples
rascal>import Set;
ok
rascal>int incr(int x) { return x + 1; }
ok
rascal>mapper({1, 2, 3, 4}, incr);
set[int]: {5,3,2,4}

1.12.8. max

Function

&T max(set[&T] st)

Synopsis

Determine the largest element of a set.

Examples
rascal>import Set;
ok
rascal>max({1, 3, 5, 2, 4});
int: 5
rascal>max({"elephant", "zebra", "snake"});
str: "zebra"

1.12.9. min

Function

&T min(set[&T] st)

Synopsis

Determine the smallest element of a set.

Examples
rascal>import Set;
ok
rascal>min({1, 3, 5, 4, 2});
int: 1

1.12.10. power

Function

set[set[&T]] power(set[&T] st)

Synopsis

Determine the powerset of a set.

Description

Returns a set with all subsets of s.

Examples
rascal>import Set;
ok
rascal>power({1,2,3,4});
set[set[int]]: {
  {},
  {1,2,4},
  {1},
  {3,2,4},
  {3},
  {1,3,2,4},
  {1,3},
  {2},
  {4},
  {1,2},
  {1,4},
  {3,2},
  {3,4},
  {1,3,2},
  {1,3,4},
  {2,4}
}

1.12.11. power1

Function

set[set[&T]] power1(set[&T] st)

Synopsis

The powerset (excluding the empty set) of a set value.

Description

Returns all subsets (excluding the empty set) of s.

Examples
rascal>import Set;
ok
rascal>power1({1,2,3,4});
set[set[int]]: {
  {1,2,4},
  {1},
  {3,2,4},
  {3},
  {1,3,2,4},
  {1,3},
  {2},
  {4},
  {1,2},
  {1,4},
  {3,2},
  {3,4},
  {1,3,2},
  {1,3,4},
  {2,4}
}

1.12.12. reducer

Function

&T reducer(set[&T] st, &T (&T,&T) fn, &T unit)

Synopsis

Apply a function to successive elements of a set and combine the results (deprecated).

Description

Apply the function fn to successive elements of set s starting with unit.

Examples
rascal>import Set;
ok
rascal>int add(int x, int y) { return x + y; }
ok
rascal>reducer({10, 20, 30, 40}, add, 0);
int: 100
Pitfalls
This function is deprecated, use a reducer instead.

1.12.13. size

Function

int size(set[&T] st)

Synopsis

Determine the number of elements in a set.

Examples
rascal>import Set;
ok
rascal>size({1,2,3,4});
int: 4
rascal>size({"elephant", "zebra", "snake"});
int: 3
rascal>size({});
int: 0

1.12.14. sum

Function
  • (&T <:num) sum(set[(&T <:num)] _:{})

  • default (&T <:num) sum({(&T <: num) e, *(&T <: num) r})

1.12.15. getOneFrom

Function

&T getOneFrom(set[&T] st) throws EmptySet

Synopsis

Pick an arbitrary element from a set.

Examples
rascal>import Set;
ok
rascal>getOneFrom({"elephant", "zebra", "snake"});
str: "elephant"
rascal>getOneFrom({"elephant", "zebra", "snake"});
str: "elephant"
rascal>getOneFrom({"elephant", "zebra", "snake"});
str: "zebra"
rascal>getOneFrom({"elephant", "zebra", "snake"});
str: "elephant"

1.12.16. takeOneFrom

Function

tuple[&T, set[&T]] takeOneFrom(set[&T] st) throws EmptySet

Synopsis

Remove an arbitrary element from a set, returns the element and a set without that element.

Description

Remove an arbitrary element from set s and return a tuple consisting of the element and a set without that element. Also see getOneFrom.

Examples
rascal>import Set;
ok
rascal>takeOneFrom({1, 2, 3, 4});
tuple[int,set[int]]: <3,{1,2,4}>
rascal>takeOneFrom({1, 2, 3, 4});
tuple[int,set[int]]: <1,{3,2,4}>
rascal>takeOneFrom({1, 2, 3, 4});
tuple[int,set[int]]: <2,{1,3,4}>

1.12.17. takeFirstFrom

Function

tuple[&T, set[&T]] takeFirstFrom(set[&T] st) throws EmptySet

Synopsis

Remove "first" element from a set, returns the element and a set without that element.

Description

element of a set.

1.12.18. toList

Function

list[&T] toList(set[&T] st)

Synopsis

Convert a set to a list.

Examples
rascal>import Set;
ok
rascal>toList({1, 2, 3, 4});
list[int]: [4,2,3,1]
rascal>toList({"elephant", "zebra", "snake"});
list[str]: ["elephant","zebra","snake"]

Note that the same result can be obtained using splicing:

rascal>s = {1,2,3,4};
set[int]: {1,3,2,4}
rascal>l = [*s];
list[int]: [1,3,2,4]
Pitfalls

Recall that the elements of a set are unordered and that there is no guarantee in which order the set elements will be placed in the resulting list.

1.12.19. toMap

Function

map[&A,set[&B]] toMap(rel[&A, &B] st)

Synopsis

Convert a set of tuples to a map; each key is associated with a set of values.

Description

Convert a set of tuples to a map in which the first element of each tuple is associated with the set of second elements of all tuples with the same first element.

Examples
rascal>import Set;
ok
rascal>toMap({<"a", 1>, <"b", 2>, <"a", 10>});
map[str, set[int]]: (
  "a":{10,1},
  "b":{2}
)

1.12.20. toMapUnique

Function

map[&A,&B] toMapUnique(rel[&A, &B] st) throws MultipleKey

Synopsis

Convert a set of tuples to a map (provided that there are no multiple keys).

Description

Convert a set of tuples to a map. The result should be a legal map (i.e., without multiple keys).

Examples
rascal>import Set;
ok
rascal>toMapUnique({<"a", 1>, <"b", 2>, <"c", 10>});
map[str, int]: ("a":1,"b":2,"c":10)

Now explore an erroneous example:

rascal>toMapUnique({<"a", 1>, <"b", 2>, <"a", 10>});
Exception [debugger cannot break at null frame]: MultipleKey("a")

1.12.21. toString

Function

str toString(set[&T] st)

Synopsis

Convert a set to a string.

Examples
rascal>import Set;
ok
rascal>toString({1, 2, 3});
str: "{1,3,2}"
rascal>toString({"elephant", "zebra", "snake"});
str: "{\"snake\",\"zebra\",\"elephant\"}"
Pitfalls

Recall that the elements of a set are unordered and that there is no guarantee in which order the set elements will be placed in the resulting string.

1.12.22. itoString

Function

str itoString(set[&T] st)

Synopsis

Convert a set to an indented string.

Examples
rascal>import Set;
ok
rascal>toString({1, 2, 3});
str: "{1,3,2}"
rascal>toString({"elephant", "zebra", "snake"});
str: "{\"snake\",\"zebra\",\"elephant\"}"
Pitfalls

Recall that the elements of a set are unordered and that there is no guarantee in which order the set elements will be placed in the resulting string.

1.12.23. sort

Function
  • list[&T] sort(set[&T] s)

  • list[&T] sort(set[&T] l, bool (&T a, &T b) less)

Synopsis

Sort the elements of a set.

Sort the elements of a set:

  • Use the built-in ordering on values to compare list elements.

  • Give an additional lessThan function that will be used to compare elements.

This function lessThan (<) function should implement a strict partial order, meaning:

  • that it is not reflexive, i.e. never a < a

  • is anti-symmetric, i.e. never a < b && b < a.

  • is transitive, i.e. if a < b and b < c then a < c.

Examples
rascal>import Set;
ok
rascal>import String;
ok
rascal>sort({10, 4, -2, 11, 100, 5});
list[int]: [-2,4,5,10,11,100]
rascal>fruits = {"mango", "strawberry", "pear", "pineapple", "banana", "grape", "kiwi"};
set[str]: {"mango","banana","pear","pineapple","grape","strawberry","kiwi"}
rascal>sort(fruits);
list[str]: ["banana","grape","kiwi","mango","pear","pineapple","strawberry"]
rascal>sort(fruits, bool(str a, str b){ return size(a) > size(b); });
list[str]: ["strawberry","pineapple","banana","mango","grape","kiwi","pear"]

1.12.24. union

Function

set[&T] union(set[set[&T]] sets)

Synopsis

Flatten a set of sets into a single set.

1.13. String

Usage

import String;

Synopsis

Library functions for strings.

Description

For operators on strings see String in the Rascal Language Reference.

The following functions are defined for strings:

  • center: Center a string in given space.

  • center:

  • charAt: Return character in a string by its index position.

  • chars: Return characters of a string.

  • contains: Check that a string contains another string.

  • endsWith: Check whether a string ends with a given substring.

  • escape: Replace single characters in a string.

  • findAll: Find all occurrences of a string in another string.

  • findFirst: Find the first occurrence of a string in another string.

  • findLast: Find the last occurrence of a string in another string.

  • isEmpty: Check whether a string is empty.

  • left: Left alignment of string in given space.

  • left:

  • replaceAll: Replace all occurrences of a string in another string.

  • replaceFirst: Replace the first occurrence of a string in another string.

  • replaceLast: Replace the last occurrence of a string in another string.

  • reverse: Return a string with all characters in reverse order.

  • right: Right alignment of a string value in a given space.

  • right:

  • size: Determine length of a string value.

  • startsWith: Check whether a string starts with a given prefix.

  • stringChar: Convert a character code into a string

  • stringChars: Convert a list of character codes into a string

  • isValidCharacter: Check that a given integer value is a valid Unicode code point

  • substring: Extract a substring from a string value.

  • substring:

  • toInt: Convert a string value to integer.

  • toInt:

  • toLowerCase: Convert the characters in a string value to lower case.

  • toReal: Convert a string value to real.

  • toUpperCase: Convert the characters in a string value to upper case.

  • trim: Returns string with leading and trailing whitespace removed.

  • squeeze: Squeeze repeated occurrences of characters.

  • split: Split a string into a list of strings based on a literal separator

  • capitalize:

  • uncapitalize:

  • toBase64:

  • fromBase64:

  • wrap: Word wrap a string to fit in a certain width.

  • format:

  • rexpMatch: Determine if a string matches the given (Java-syntax) regular expression

  • toLocation: Convert a string value to a (source code) location.

  • substitute: Substitute substrings in a string based on a substitution map from location to string.

1.13.1. center

Function
  • str center(str s, int n)

  • str center(str s, int n, str pad)

Synopsis

Center a string in given space.

Description
  • Center string s in string of length n using spaces.

  • Center string s in string of length n using pad as padding character.

Examples
rascal>import String;
ok
rascal>center("abc", 10);
str: "   abc    "
rascal>center("abc", 10, "x");
str: "xxxabcxxxx"

1.13.2. charAt

Function

int charAt(str s, int i) throws IndexOutOfBounds(str msg)

Synopsis

Return character in a string by its index position.

Description

Return the character at position i in string s as integer character code. Also see stringChar that converts character codes back to string.

Examples
rascal>import String;
ok
rascal>charAt("abc", 0);
int: 97
rascal>stringChar(charAt("abc", 0));
str: "a"

1.13.3. chars

Function

list[int] chars(str s)

Synopsis

Return characters of a string. .Description Return a list of the characters of s as integer character codes. Also see stringChars that converts character codes back to string.

Examples
rascal>import String;
ok
rascal>chars("abc");
list[int]: [97,98,99]
rascal>stringChars(chars("abc")) == "abc";
bool: true

1.13.4. contains

Function

bool contains(str input, str find)

Synopsis

Check that a string contains another string.

Description

Check whether the string find occurs as substring in the string subject.

Examples
rascal>import String;
ok
rascal>contains("abracadabra", "bra");
bool: true
rascal>contains("abracadabra", "e");
bool: false

1.13.5. endsWith

Function

bool endsWith(str subject, str suffix)

Synopsis

Check whether a string ends with a given substring.

Description

Yields true if string subject ends with the string suffix.

Examples
rascal>import String;
ok
rascal>endsWith("Hello.rsc", ".rsc");
bool: true

1.13.6. escape

Function

str escape(str subject, map[str,str] mapping)

Synopsis

Replace single characters in a string.

Description

Return a copy of subject in which each single character key in replacements has been replaced by its associated value.

Examples
rascal>import String;
ok
rascal>import IO;
ok
rascal>escape("abracadabra", ("a" : "AA", "c" : "C"));
str: "AAbrAACAAdAAbrAA"
rascal>L = escape("\"Good Morning\", he said", ("\"": "\\\""));
str: "\\\"Good Morning\\\", he said"
rascal>println(L);
\"Good Morning\", he said

1.13.7. findAll

Function

list[int] findAll(str subject, str find)

Synopsis

Find all occurrences of a string in another string.

Description

Find all occurrences of string find in string subject. The result is a (possible empty) list of positions where find matches.

See also findFirst and findLast.

Examples
rascal>import String;
ok
rascal>findAll("abracadabra", "a");
list[int]: [0,3,5,7,10]
rascal>findAll("abracadabra", "bra");
list[int]: [1,8]
rascal>findAll("abracadabra", "e");
list[void]: []

1.13.8. findFirst

Function

int findFirst(str subject, str find)

Synopsis

Find the first occurrence of a string in another string.

Description

Find the first occurrence of string find in string subject. The result is either a position in subject or -1 when find is not found.

Also see findAll and findLast.

Examples
rascal>import String;
ok
rascal>findFirst("abracadabra", "a");
int: 0
rascal>findFirst("abracadabra", "bra");
int: 1
rascal>findFirst("abracadabra", "e");
int: -1

1.13.9. findLast

Function

int findLast(str subject, str find)

Synopsis

Find the last occurrence of a string in another string.

Description

Find the last occurrence of string find in string subject. The result is either a position in subject or -1 when find is not found.

Also see findAll and findFirst.

Examples
rascal>import String;
ok
rascal>findLast("abracadabra", "a");
int: 10
rascal>findLast("abracadabra", "bra");
int: 8
rascal>findLast("abracadabra", "e");
int: -1

1.13.10. isEmpty

Function

bool isEmpty(str s)

Synopsis

Check whether a string is empty.

Description

Returns true if string s is empty.

Examples
rascal>import String;
ok
rascal>isEmpty("");
bool: true
rascal>isEmpty("abc");
bool: false

1.13.11. left

Function
  • str left(str s, int n)

  • str left(str s, int n, str pad)

Synopsis

Left alignment of string in given space.

Description
  • Left align string s in string of length n using spaces.

  • Left align string s in string of length n using pad as pad character.

Examples
rascal>import String;
ok
rascal>left("abc", 10);
str: "abc       "
rascal>left("abc", 10, "x");
str: "abcxxxxxxx"

1.13.12. replaceAll

Function

str replaceAll(str subject, str find, str replacement)

Synopsis

Replace all occurrences of a string in another string.

Description

Return a copy of subject in which all occurrences of find (if any) have been replaced by replacement. Also see replaceFirst and replaceLast.

Examples
rascal>import String;
ok
rascal>replaceAll("abracadabra", "a", "A");
str: "AbrAcAdAbrA"
rascal>replaceAll("abracadabra", "ra", "RARA");
str: "abRARAcadabRARA"
rascal>replaceAll("abracadabra", "cra", "CRA");
str: "abracadabra"
Pitfalls

Note that find is a string (as opposed to, for instance, a regular expression in Java).

1.13.13. replaceFirst

Function

str replaceFirst(str subject, str find, str replacement)

Synopsis

Replace the first occurrence of a string in another string.

Description

Return a copy of subject in which the first occurrence of find (if it exists) has been replaced by replacement. Also see replaceAll and replaceLast.

Examples
rascal>import String;
ok
rascal>replaceFirst("abracadabra", "a", "A");
str: "Abracadabra"
rascal>replaceFirst("abracadabra", "ra", "RARA");
str: "abRARAcadabra"
rascal>replaceFirst("abracadabra", "cra", "CRA");
str: "abracadabra"
Pitfalls

Note that find is a string (as opposed to, for instance, a regular expression in Java).

1.13.14. replaceLast

Function

str replaceLast(str subject, str find, str replacement)

Synopsis

Replace the last occurrence of a string in another string.

Description

Return a copy of subject in which the last occurrence of find (if it exists) has been replaced by replacement. Also see replaceFirst and replaceLast.

Examples
rascal>import String;
ok
rascal>replaceLast("abracadabra", "a", "A");
str: "abracadabrA"
rascal>replaceLast("abracadabra", "ra", "RARA");
str: "abracadabRARA"
rascal>replaceLast("abracadabra", "cra", "CRA");
str: "abracadabra"
Pitfalls

Note that find is a string (as opposed to, for instance, a regular expression in Java).

1.13.15. reverse

Function

str reverse(str s)

Synopsis

Return a string with all characters in reverse order.

Description

Returns string with all characters of string s in reverse order.

Examples
rascal>import String;
ok
rascal>reverse("abc");
str: "cba"

1.13.16. right

Function
  • str right(str s, int n)

  • str right(str s, int n, str pad)

Synopsis

Right alignment of a string value in a given space.

Description
  • Right align string s in string of length n using spaces.

  • Right align string s in string of length n using pad as pad character.

Examples
rascal>import String;
ok
rascal>right("abc", 10);
str: "       abc"
rascal>right("abc", 10, "x");
str: "xxxxxxxabc"

1.13.17. size

Function

int size(str s)

Synopsis

Determine length of a string value.

Description

Returns the length (number of characters) in string s.

Examples
rascal>import String;
ok
rascal>size("abc");
int: 3
rascal>size("");
int: 0

1.13.18. startsWith

Function

bool startsWith(str subject, str prefix)

Synopsis

Check whether a string starts with a given prefix.

Description

Yields true if string subject starts with the string prefix.

Examples
rascal>import String;
ok
rascal>startsWith("Hello.rsc", "Hell");
bool: true

1.13.19. stringChar

Function

str stringChar(int char) throws IllegalArgument(int character)

Synopsis

Convert a character code into a string.

1.13.20. stringChars

Function

str stringChars(list[int] chars) throws IllegalArgument(int character)

Synopsis

Convert a list of character codes into a string.

1.13.21. isValidCharacter

Function

bool isValidCharacter(int ch)

Synopsis

Check that a given integer value is a valid Unicode code point.

1.13.22. substring

Function
  • str substring(str s, int begin)

  • str substring(str s, int begin, int end)

Synopsis

Extract a substring from a string value.

Description
  • Yields substring of string s from index begin to the end of the string.

  • Yields substring of string s from index begin to (but not including) index end.

Examples
rascal>import String;
ok
rascal>substring("abcdef", 2);
str: "cdef"
rascal>substring("abcdef", 2, 4);
str: "cd"

1.13.23. toInt

Function
  • int toInt(str s) throws IllegalArgument

  • int toInt(str s, int r) throws IllegalArgument

Synopsis

Convert a string value to integer.

Description
  • Converts string s to integer.

  • Convert string s to integer using radix r.

Throws IllegalArgument when s cannot be converted.

Examples
rascal>import String;
ok
rascal>toInt("11");
int: 11
rascal>toInt("11", 8);
int: 9

Now try an erroneous argument:

rascal>toInt("abc");
Exception [debugger cannot break at null frame]: IllegalArgument("abc","For input string: \"abc\"")

1.13.24. toLowerCase

Function

str toLowerCase(str s)

Synopsis

Convert the characters in a string value to lower case.

Description

Convert all characters in string s to lowercase. Also see toUpperCase.

Examples
rascal>import String;
ok
rascal>toLowerCase("AaBbCc123");
str: "aabbcc123"

1.13.25. toReal

Function

real toReal(str s)

Synopsis

Convert a string value to real.

Description

Converts string s to a real. Throws IllegalArgument when s cannot be converted.

Examples
rascal>import String;
ok
rascal>toReal("2.5e-3");
real: 0.0025
rascal>toReal("123");
real: 123.
rascal>toReal("abc");
Exception [debugger cannot break at null frame]: IllegalArgument()

1.13.26. toUpperCase

Function

str toUpperCase(str s)

Synopsis

Convert the characters in a string value to upper case.

Description

Converts all characters in string s to upper case.

Also see toLowerCase.

Examples
rascal>import String;
ok
rascal>toUpperCase("AaBbCc123");
str: "AABBCC123"

1.13.27. trim

Function

str trim(str s)

Synopsis

Returns string with leading and trailing whitespace removed.

Examples
rascal>import String;
ok
rascal>trim("  jelly
>>>>>>>beans  ");
str: "jelly\nbeans"

1.13.28. squeeze

Function

str squeeze(str src, str charSet)

Synopsis

Squeeze repeated occurrences of characters. .Description Squeeze repeated occurrences in src of characters in charSet removed. See Apache for the allowed syntax in charSet.

Examples
rascal>import String;
ok
rascal>squeeze("hello", "el");
str: "helo"

1.13.29. split

Function

list[str] split(str sep, str src)

Synopsis

Split a string into a list of strings based on a literal separator.

1.13.30. capitalize

Function

str capitalize(str src)

1.13.31. uncapitalize

Function

str uncapitalize(str src)

1.13.32. toBase64

Function

str toBase64(str src)

1.13.33. fromBase64

Function

str fromBase64(str src)

1.13.34. wrap

Function

str wrap(str src, int wrapLength)

Synopsis

Word wrap a string to fit in a certain width.

Description

Inserts newlines in a string in order to fit the string in a certain width. It only breaks on spaces (' ').

1.13.35. format

Function

str format(str s, str dir, int n, str pad)

1.13.36. rexpMatch

Function

bool rexpMatch(str s, str re)

Synopsis

Determine if a string matches the given (Java-syntax) regular expression.

1.13.37. toLocation

Function

loc toLocation(str s)

Synopsis

Convert a string value to a (source code) location.

Description
  • Converts string s to a location.

  • If the scheme is not provided, it is assumed to be cwd.

Examples
rascal>import String;
ok
rascal>toLocation("http://grammarware.net");
loc: |http://grammarware.net|
rascal>toLocation("document.xml");
loc: |cwd:///document.xml|

1.13.38. substitute

Function

str substitute(str src, map[loc,str] s)

Synopsis

Substitute substrings in a string based on a substitution map from location to string.

Examples
rascal>import String;
ok
rascal>substitute("abc", (|stdin://|(1,1): "d"))
[red]##Error: Expected 4 arguments: int, int, tuple[int,int], and tuple[int,int] IN '|stdin://|(1,1)'##

1.14. Type

Usage

import Type;

Synopsis

Rascal’s type system, implemented in Rascal itself.

Description

The goal of this module is to provide:

  • reflection capabilities that are useful for deserialization and validation of data, and

  • to provide the basic building blocks for syntax trees (see ParseTree)

The following definition is built into Rascal:

data type[&T] = type(Symbol symbol, map[Symbol,Production] definitions);

The # operator will always produce a value of type[&T], where &T is bound to the type that was reified.

Examples
rascal>import Type;
ok
rascal>#int
type[int]: type(
  int(),
  ())
rascal>#rel[int,int]
type[rel[int,int]]: type(
  rel([
      int(),
      int()
    ]),
  ())
rascal>data B = t();
ok
rascal>#B
type[B]: type(
  adt(
    "B",
    []),
  (adt(
      "B",
      []):choice(
      adt(
        "B",
        []),
      {cons(
          label(
            "t",
            adt(
              "B",
              [])),
          [],
          [],
          {})})))
rascal>syntax A = "a";
ok
rascal>#A;
type[A]: type(
  sort("A"),
  (
    layouts("$default$"):choice(
      layouts("$default$"),
      {prod(
          layouts("$default$"),
          [],
          {})}),
    empty():choice(
      empty(),
      {prod(
          empty(),
          [],
          {})}),
    sort("A"):choice(
      sort("A"),
      {prod(
          sort("A"),
          [lit("a")],
          {})})
  ))
rascal>type(\int(),())
type[int]: type(
  int(),
  ())

The following functions are provided on types:

1.14.1. Symbol

Types
data Symbol
      = \int()
      | \bool()
      | \real()
      | \rat()
      | \str()
      | \num()
      | \node()
      | \void()
      | \value()
      | \loc()
      | \datetime()
      ;
Synopsis

A Symbol represents a Rascal Type.

Description

Symbols are values that represent Rascal’s types. These are the atomic types. We define here:

1 Atomic types.
2 Labels that are used to give names to symbols, such as field names, constructor names, etc.
3 Composite types.
4 Parameters that represent a type variable.

In ParseTree, see Symbol, Symbols will be further extended with the symbols that may occur in a ParseTree.

1.14.2. Symbol

Types
data Symbol
      = \label(str name, Symbol symbol)
      ;

1.14.3. Symbol

Types
data Symbol
      = \set(Symbol symbol)
      | \rel(list[Symbol] symbols)
      | \lrel(list[Symbol] symbols)
      | \tuple(list[Symbol] symbols)
      | \list(Symbol symbol)
      | \map(Symbol from, Symbol to)
      | \bag(Symbol symbol)
      | \adt(str name, list[Symbol] parameters)
      | \cons(Symbol \adt, str name, list[Symbol] parameters)
      | \alias(str name, list[Symbol] parameters, Symbol aliased)
      | \func(Symbol ret, list[Symbol] parameters, list[Symbol] kwTypes)
      | \func(Symbol ret, list[Symbol] parameters)
      | \overloaded(set[Symbol] alternatives)
      | \var-func(Symbol ret, list[Symbol] parameters, Symbol varArg)
      | \reified(Symbol symbol)
      ;

1.14.4. Symbol

Types
data Symbol
      = \parameter(str name, Symbol bound)
      ;

1.14.5. Production

Types
data Production
      = \cons(Symbol def, list[Symbol] symbols, list[Symbol] kwTypes, set[Attr] attributes)
      | \func(Symbol def, list[Symbol] symbols, list[Symbol] kwTypes, set[Attr] attributes /*, str code = "", map[str,value] bindings = (), loc cpe = |unknown:///|*/)
      | \choice(Symbol def, set[Production] alternatives)
      | \composition(Production lhs, Production rhs)
      ;
Synopsis

A production in a grammar or constructor in a data type.

Description

Productions represent abstract (recursive) definitions of abstract data type constructors and functions:

  • cons: a constructor for an abstract data type.

  • func: a function.

  • choice: the choice between various alternatives.

  • composition: composition of two productions.

In ParseTree, see Production, Productions will be further extended and will be used to represent productions in syntax rules.

1.14.6. Attr

Types
data Attr
      = \tag(value \tag)
      ;
Synopsis

Attributes register additional semantics annotations of a definition.

[[Type-\var-func]] ## \var-func

Function

Symbol \var-func(Symbol ret, list[Symbol] parameters, Symbol varArg)

Synopsis

Transform a function with varargs (…​) to a normal function with a list argument.

1.14.7. choice

Function

Production choice(Symbol s, set[Production] choices)

Synopsis

Normalize the choice between alternative productions.

Description

Nested choice is flattened.

1.14.8. subtype

Function
  • bool subtype(type[&T] t, type[&U] u)

  • bool subtype(Symbol s, s)

  • default bool subtype(Symbol s, Symbol t)

  • bool subtype(Symbol _, Symbol::\value())

  • bool subtype(Symbol::\void(), Symbol _)

  • bool subtype(Symbol::\cons(Symbol a, _, list[Symbol] _), a)

  • bool subtype(Symbol::\cons(Symbol a, str name, list[Symbol] ap), Symbol::\cons(a,name,list[Symbol] bp))

  • bool subtype(Symbol::\adt(str _, list[Symbol] _), Symbol::\node())

  • bool subtype(Symbol::\adt(str n, list[Symbol] l), Symbol::\adt(n, list[Symbol] r))

  • bool subtype(Symbol::\alias(str _, list[Symbol] _, Symbol aliased), Symbol r)

  • bool subtype(Symbol l, \alias(str _, list[Symbol] _, Symbol aliased))

  • bool subtype(Symbol::\int(), Symbol::\num())

  • bool subtype(Symbol::\rat(), Symbol::\num())

  • bool subtype(Symbol::\real(), Symbol::\num())

  • bool subtype(Symbol::\tuple(list[Symbol] l), \tuple(list[Symbol] r))

  • bool subtype(Symbol::\list(Symbol s), Symbol::\list(Symbol t))

  • bool subtype(Symbol::\lrel(list[Symbol] l), Symbol::\lrel(list[Symbol] r))

  • bool subtype(Symbol::\list(Symbol s), Symbol::\lrel(list[Symbol] r))

  • bool subtype(Symbol::\lrel(list[Symbol] l), \list(Symbol r))

  • bool subtype(Symbol::\set(Symbol s), Symbol::\set(Symbol t))

  • bool subtype(Symbol::\rel(list[Symbol] l), Symbol::\rel(list[Symbol] r))

  • bool subtype(Symbol::\set(Symbol s), Symbol::\rel(list[Symbol] r))

  • bool subtype(Symbol::\rel(list[Symbol] l), Symbol::\set(Symbol r))

  • bool subtype(Symbol::\bag(Symbol s), Symbol::\bag(Symbol t))

  • bool subtype(Symbol::\map(Symbol from1, Symbol to1), Symbol::\map(Symbol from2, Symbol to2))

  • bool subtype(Symbol::\func(Symbol r1, list[Symbol] p1, list[Symbol] _), Symbol f2)

  • bool subtype(Symbol f2, Symbol::\func(Symbol r1, list[Symbol] p1, list[Symbol] _))

  • bool subtype(Symbol::\func(Symbol r1, list[Symbol] p1), Symbol::\func(Symbol r2, list[Symbol] p2))

  • bool subtype(Symbol::\parameter(str _, Symbol bound), Symbol r)

  • bool subtype(Symbol l, Symbol::\parameter(str _, Symbol bound))

  • bool subtype(Symbol::\label(str _, Symbol s), Symbol t)

  • bool subtype(Symbol s, Symbol::\label(str _, Symbol t))

  • bool subtype(Symbol::\reified(Symbol s), Symbol::\reified(Symbol t))

  • bool subtype(Symbol::\reified(Symbol s), Symbol::\node())

  • bool subtype(list[Symbol] l, list[Symbol] r)

  • default bool subtype(list[Symbol] l, list[Symbol] r)

Synopsis

Subtype on types.

1.14.9. comparable

Function

bool comparable(Symbol s, Symbol t)

Synopsis

Check if two types are comparable, i.e., have a common supertype.

1.14.10. equivalent

Function

bool equivalent(Symbol s, Symbol t)

Synopsis

Check if two types are equivalent.

1.14.11. eq

Function

bool eq(value x, value y)

Synopsis

Structural equality between values.

Description

The difference is that no implicit coercions are done between values of incomparable types, such as == does for int, real and rat.

Examples
rascal>import Type;
ok
rascal>1 == 1.0
bool: true
rascal>eq(1,1.0)
bool: false

1.14.12. lub

Function
  • Symbol lub(Symbol s, s)

  • default Symbol lub(Symbol s, Symbol t)

  • Symbol lub(Symbol::\value(), Symbol t)

  • Symbol lub(Symbol s, Symbol::\value())

  • Symbol lub(Symbol::\void(), Symbol t)

  • Symbol lub(Symbol s, Symbol::\void())

  • Symbol lub(Symbol::\int(), Symbol::\num())

  • Symbol lub(Symbol::\int(), Symbol::\real())

  • Symbol lub(Symbol::\int(), Symbol::\rat())

  • Symbol lub(Symbol::\rat(), Symbol::\num())

  • Symbol lub(Symbol::\rat(), Symbol::\real())

  • Symbol lub(Symbol::\rat(), Symbol::\int())

  • Symbol lub(Symbol::\real(), Symbol::\num())

  • Symbol lub(Symbol::\real(), Symbol::\int())

  • Symbol lub(Symbol::\real(), Symbol::\rat())

  • Symbol lub(Symbol::\num(), Symbol::\int())

  • Symbol lub(Symbol::\num(), Symbol::\real())

  • Symbol lub(Symbol::\num(), Symbol::\rat())

  • Symbol lub(Symbol::\set(Symbol s), Symbol::\set(Symbol t))

  • Symbol lub(Symbol::\set(Symbol s), Symbol::\rel(list[Symbol] ts))

  • Symbol lub(Symbol::\rel(list[Symbol] ts), Symbol::\set(Symbol s))

  • Symbol lub(Symbol::\rel(list[Symbol] l), Symbol::\rel(list[Symbol] r))

  • Symbol lub(Symbol::\rel(list[Symbol] l), Symbol::\rel(list[Symbol] r))

  • Symbol lub(Symbol::\rel(list[Symbol] l), Symbol::\rel(list[Symbol] r))

  • Symbol lub(Symbol::\rel(list[Symbol] l), Symbol::\rel(list[Symbol] r))

  • Symbol lub(Symbol::\rel(list[Symbol] l), Symbol::\rel(list[Symbol] r))

  • Symbol lub(Symbol::\rel(list[Symbol] l), Symbol::\rel(list[Symbol] r))

  • Symbol lub(Symbol::\list(Symbol s), Symbol::\list(Symbol t))

  • Symbol lub(Symbol::\list(Symbol s), \lrel(list[Symbol] ts))

  • Symbol lub(Symbol::\lrel(list[Symbol] ts), Symbol::\list(Symbol s))

  • Symbol lub(Symbol::\lrel(list[Symbol] l), Symbol::\lrel(list[Symbol] r))

  • Symbol lub(Symbol::\lrel(list[Symbol] l), Symbol::\lrel(list[Symbol] r))

  • Symbol lub(Symbol::\lrel(list[Symbol] l), Symbol::\lrel(list[Symbol] r))

  • Symbol lub(Symbol::\lrel(list[Symbol] l), Symbol::\lrel(list[Symbol] r))

  • Symbol lub(Symbol::\lrel(list[Symbol] l), Symbol::\lrel(list[Symbol] r))

  • Symbol lub(Symbol::\lrel(list[Symbol] l), Symbol::\lrel(list[Symbol] r))

  • Symbol lub(Symbol::\tuple(list[Symbol] l), Symbol::\tuple(list[Symbol] r))

  • Symbol lub(Symbol::\tuple(list[Symbol] l), Symbol::\tuple(list[Symbol] r))

  • Symbol lub(Symbol::\tuple(list[Symbol] l), Symbol::\tuple(list[Symbol] r))

  • Symbol lub(Symbol::\tuple(list[Symbol] l), Symbol::\tuple(list[Symbol] r))

  • Symbol lub(Symbol::\tuple(list[Symbol] l), Symbol::\tuple(list[Symbol] r))

  • Symbol lub(Symbol::\map(\label(str lfl, Symbol lf), \label(str ltl, Symbol lt)), Symbol::\map(\label(str rfl, Symbol rf), \label(str rtl, Symbol rt)))

  • Symbol lub(Symbol::\map(\label(str lfl, Symbol lf), \label(str ltl, Symbol lt)), Symbol::\map(\label(str rfl, Symbol rf), \label(str rtl, Symbol rt)))

  • Symbol lub(Symbol::\map(\label(str lfl, Symbol lf), \label(str ltl, Symbol lt)), Symbol::\map(Symbol rf, Symbol rt))

  • Symbol lub(Symbol::\map(Symbol lf, Symbol lt), Symbol::\map(\label(str rfl, Symbol rf), \label(str rtl, Symbol rt)))

  • Symbol lub(Symbol::\map(Symbol lf, Symbol lt), Symbol::\map(Symbol rf, Symbol rt))

  • Symbol lub(Symbol::\bag(Symbol s), Symbol::\bag(Symbol t))

  • Symbol lub(Symbol::\adt(str n, list[Symbol] _), Symbol::\node())

  • Symbol lub(Symbol::\node(), \adt(str n, list[Symbol] _))

  • Symbol lub(Symbol::\adt(str n, list[Symbol] lp), Symbol::\adt(n, list[Symbol] rp))

  • Symbol lub(Symbol::\adt(str n, list[Symbol] lp), Symbol::\adt(n, list[Symbol] rp))

  • Symbol lub(Symbol::\adt(str n, list[Symbol] lp), Symbol::\adt(str m, list[Symbol] rp))

  • Symbol lub(Symbol::\adt(str ln, list[Symbol] lp), Symbol::\cons(Symbol b, _, list[Symbol] _))

  • Symbol lub(Symbol::\cons(Symbol la, _, list[Symbol] _), Symbol::\cons(Symbol ra, _, list[Symbol] _))

  • Symbol lub(Symbol::\cons(Symbol a, _, list[Symbol] lp), Symbol::\adt(str n, list[Symbol] rp))

  • Symbol lub(Symbol::\cons(Symbol _, _, list[Symbol] _), Symbol::\node())

  • Symbol lub(Symbol::\alias(str _, list[Symbol] _, Symbol aliased), Symbol r)

  • Symbol lub(Symbol l, \alias(str _, list[Symbol] _, Symbol aliased))

Synopsis

The least-upperbound (lub) between two types.

Description

This function documents and implements the lub operation in Rascal’s type system.

1.14.13. keepParams

Function

bool keepParams(Symbol::\parameter(str s1, Symbol bound1), Symbol::\parameter(str s2, Symbol bound2))

1.14.14. lub

Function
  • Symbol lub(Symbol l:Symbol::\parameter(str s1, Symbol bound1), Symbol r:Symbol::\parameter(str s2, Symbol bound2))

  • Symbol lub(Symbol l:Symbol::\parameter(str s1, Symbol bound1), Symbol r:Symbol::\parameter(str s2, Symbol bound2))

  • Symbol lub(Symbol::\parameter(str _, Symbol bound), Symbol r)

  • Symbol lub(Symbol l, Symbol::\parameter(str _, Symbol bound))

  • Symbol lub(Symbol::\reified(Symbol l), Symbol::\reified(Symbol r))

  • Symbol lub(Symbol::\reified(Symbol l), Symbol::\node())

  • Symbol lub(Symbol::\func(Symbol lr, list[Symbol] lp, list[Symbol] lkw), Symbol::\func(Symbol rr, list[Symbol] rp, list[Symbol] rkw))

  • Symbol lub(Symbol::\label(_,Symbol l), Symbol r)

  • Symbol lub(Symbol l, Symbol::\label(_,Symbol r))

  • list[Symbol] lub(list[Symbol] l, list[Symbol] r)

  • default list[Symbol] lub(list[Symbol] l, list[Symbol] r)

1.14.15. allLabeled

Function

bool allLabeled(list[Symbol] l)

1.14.16. noneLabeled

Function

bool noneLabeled(list[Symbol] l)

1.14.17. getLabels

Function

list[str] getLabels(list[Symbol] l)

1.14.18. addLabels

Function
  • list[Symbol] addLabels(list[Symbol] l, list[str] s)

  • default list[Symbol] addLabels(list[Symbol] l, list[str] s)

1.14.19. stripLabels

Function

list[Symbol] stripLabels(list[Symbol] l)

1.14.20. getParamLabels

Function

list[str] getParamLabels(list[Symbol] l)

1.14.21. addParamLabels

Function
  • list[Symbol] addParamLabels(list[Symbol] l, list[str] s)

  • default list[Symbol] addParamLabels(list[Symbol] l, list[str] s)

1.14.22. glb

Function
  • Symbol glb(Symbol s, s)

  • default Symbol glb(Symbol s, Symbol t)

  • Symbol glb(Symbol::\void(), Symbol t)

  • Symbol glb(Symbol s, Symbol::\void())

  • Symbol glb(Symbol::\value(), Symbol t)

  • Symbol glb(Symbol s, Symbol::\value())

  • Symbol glb(Symbol::\int(), Symbol::\num())

  • Symbol glb(Symbol::\num(), Symbol::\int())

  • Symbol glb(Symbol::\rat(),Symbol::\num())

  • Symbol glb(Symbol::\num(), Symbol::\rat())

  • Symbol glb(Symbol::\real(), Symbol::\num())

  • Symbol glb(Symbol::\num(), Symbol::\real())

  • Symbol glb(Symbol::\set(Symbol s), Symbol::\set(Symbol t))

  • Symbol glb(Symbol::\set(Symbol s), Symbol::\rel(list[Symbol] ts))

  • Symbol glb(Symbol::\rel(list[Symbol] ts), Symbol::\set(Symbol s))

  • Symbol glb(Symbol::\rel(list[Symbol] l), Symbol::\rel(list[Symbol] r))

  • Symbol glb(Symbol::\rel(list[Symbol] l), Symbol::\rel(list[Symbol] r))

  • Symbol glb(Symbol::\rel(list[Symbol] l), Symbol::\rel(list[Symbol] r))

  • Symbol glb(Symbol::\rel(list[Symbol] l), Symbol::\rel(list[Symbol] r))

  • Symbol glb(Symbol::\rel(list[Symbol] l), Symbol::\rel(list[Symbol] r))

  • Symbol glb(Symbol::\rel(list[Symbol] l), Symbol::\rel(list[Symbol] r))

  • Symbol glb(Symbol::\list(Symbol s), Symbol::\list(Symbol t))

  • Symbol glb(Symbol::\list(Symbol s), Symbol::\lrel(list[Symbol] ts))

  • Symbol glb(Symbol::\lrel(list[Symbol] ts), Symbol::\list(Symbol s))

  • Symbol glb(Symbol::\lrel(list[Symbol] l), Symbol::\lrel(list[Symbol] r))

  • Symbol glb(Symbol::\lrel(list[Symbol] l), Symbol::\lrel(list[Symbol] r))

  • Symbol glb(Symbol::\lrel(list[Symbol] l), Symbol::\lrel(list[Symbol] r))

  • Symbol glb(Symbol::\lrel(list[Symbol] l), Symbol::\lrel(list[Symbol] r))

  • Symbol glb(Symbol::\lrel(list[Symbol] l), Symbol::\lrel(list[Symbol] r))

  • Symbol glb(Symbol::\lrel(list[Symbol] l), Symbol::\lrel(list[Symbol] r))

  • Symbol glb(Symbol::\tuple(list[Symbol] l), Symbol::\tuple(list[Symbol] r))

  • Symbol glb(Symbol::\tuple(list[Symbol] l), Symbol::\tuple(list[Symbol] r))

  • Symbol glb(Symbol::\tuple(list[Symbol] l), Symbol::\tuple(list[Symbol] r))

  • Symbol glb(Symbol::\tuple(list[Symbol] l), Symbol::\tuple(list[Symbol] r))

  • Symbol glb(Symbol::\tuple(list[Symbol] l), Symbol::\tuple(list[Symbol] r))

  • Symbol glb(Symbol::\map(\label(str lfl, Symbol lf), \label(str ltl, Symbol lt)), Symbol::\map(\label(str rfl, Symbol rf), \label(str rtl, Symbol rt)))

  • Symbol glb(Symbol::\map(\label(str lfl, Symbol lf), \label(str ltl, Symbol lt)), Symbol::\map(\label(str rfl, Symbol rf), \label(str rtl, Symbol rt)))

  • Symbol glb(Symbol::\map(\label(str lfl, Symbol lf), \label(str ltl, Symbol lt)), Symbol::\map(Symbol rf, Symbol rt))

  • Symbol glb(Symbol::\map(Symbol lf, Symbol lt), Symbol::\map(\label(str rfl, Symbol rf), \label(str rtl, Symbol rt)))

  • Symbol glb(Symbol::\map(Symbol lf, Symbol lt), Symbol::\map(Symbol rf, Symbol rt))

  • Symbol glb(Symbol::\bag(Symbol s), Symbol::\bag(Symbol t))

  • Symbol glb(Symbol::\adt(str n, list[Symbol] _), Symbol::\node())

  • Symbol glb(\node(), Symbol::\adt(str n, list[Symbol] _))

  • Symbol glb(Symbol::\adt(str n, list[Symbol] lp), Symbol::\adt(n, list[Symbol] rp))

  • Symbol glb(Symbol::\adt(str n, list[Symbol] lp), Symbol::\adt(n, list[Symbol] rp))

  • Symbol glb(Symbol::\adt(str n, list[Symbol] lp), Symbol::\adt(str m, list[Symbol] rp))

  • Symbol glb(Symbol::\adt(str ln, list[Symbol] lp), Symbol::\cons(Symbol b, _, list[Symbol] _))

  • Symbol glb(Symbol::\cons(Symbol la, _, list[Symbol] _), Symbol::\cons(Symbol ra, _, list[Symbol] _))

  • Symbol glb(Symbol::\cons(Symbol a, _, list[Symbol] lp), Symbol::\adt(str n, list[Symbol] rp))

  • Symbol glb(Symbol::\cons(Symbol _, _, list[Symbol] _), \node())

  • Symbol glb(Symbol::\alias(str _, list[Symbol] _, Symbol aliased), Symbol r)

  • Symbol glb(Symbol l, Symbol::\alias(str _, list[Symbol] _, Symbol aliased))

  • Symbol glb(Symbol::\parameter(str _, Symbol bound), Symbol r)

  • Symbol glb(Symbol l, Symbol::\parameter(str _, Symbol bound))

  • Symbol glb(Symbol::\reified(Symbol l), Symbol::\reified(Symbol r))

  • Symbol glb(Symbol::\reified(Symbol l), Symbol::\node())

  • Symbol glb(Symbol::\func(Symbol lr, list[Symbol] lp, list[Symbol] lkw), Symbol::\func(Symbol rr, list[Symbol] rp, list[Symbol] rkw))

  • Symbol glb(Symbol::\label(_,Symbol l), Symbol r)

  • Symbol glb(Symbol l, Symbol::\label(_,Symbol r))

  • list[Symbol] glb(list[Symbol] l, list[Symbol] r)

  • default list[Symbol] glb(list[Symbol] l, list[Symbol] r)

Synopsis

The greatest lower bound (glb) between two types.

Description

This function documents and implements the glb operation in Rascal’s type system.

1.14.23. Exception

Types
data Exception
      = typeCastException(Symbol from, type[value] to)
      ;

1.14.24. typeCast

Function

&T typeCast(type[&T] typ, value v)

1.14.25. make

Function
  • &T make(type[&T] typ, str name, list[value] args)

  • &T make(type[&T] typ, str name, list[value] args, map[str,value] keywordArgs)

Synopsis

Instantiate an ADT constructor of a given type with the given children and optional keyword arguments.

Description

This function will build a constructor if the definition exists and throw an exception otherwise.

1.14.26. typeOf

Function

Symbol typeOf(value v)

Synopsis

Returns the dynamic type of a value as a reified type.

Description

As opposed to the # operator, which produces the type of a value statically, this function produces the dynamic type of a value, represented by a symbol.

Examples
rascal>import Type;
ok
rascal>value x = 1;
int: 1
rascal>typeOf(x)
Symbol: int()
Pitfalls
  • Note that the typeOf function does not produce definitions, like the reify operator # does, since values may escape the scope in which they’ve been constructed leaving their contents possibly undefined.

1.14.27. isIntType

Function
  • bool isIntType(Symbol::\alias(,,Symbol at))

  • bool isIntType(Symbol::\parameter(_,Symbol tvb))

  • bool isIntType(Symbol::\label(_,Symbol lt))

  • bool isIntType(Symbol::\int())

  • default bool isIntType(Symbol _)

Synopsis

Determine if the given type is an int.

1.14.28. isBoolType

Function
  • bool isBoolType(Symbol::\alias(,,Symbol at))

  • bool isBoolType(Symbol::\parameter(_,Symbol tvb))

  • bool isBoolType(Symbol::\label(_,Symbol lt))

  • bool isBoolType(Symbol::\bool())

  • default bool isBoolType(Symbol _)

Synopsis

Determine if the given type is a bool.

1.14.29. isRealType

Function
  • bool isRealType(Symbol::\alias(,,Symbol at))

  • bool isRealType(Symbol::\parameter(_,Symbol tvb))

  • bool isRealType(Symbol::\label(_,Symbol lt))

  • bool isRealType(Symbol::\real())

  • default bool isRealType(Symbol _)

Synopsis

Determine if the given type is a real.

1.14.30. isRatType

Function
  • bool isRatType(Symbol::\alias(,,Symbol at))

  • bool isRatType(Symbol::\parameter(_,Symbol tvb))

  • bool isRatType(Symbol::\label(_,Symbol lt))

  • bool isRatType(Symbol::\rat())

  • default bool isRatType(Symbol _)

Synopsis

Determine if the given type is a rational.

1.14.31. isStrType

Function
  • bool isStrType(Symbol::\alias(,,Symbol at))

  • bool isStrType(Symbol::\parameter(_,Symbol tvb))

  • bool isStrType(Symbol::\label(_,Symbol lt))

  • bool isStrType(Symbol::\str())

  • default bool isStrType(Symbol _)

Synopsis

Determine if the given type is a string.

1.14.32. isNumType

Function
  • bool isNumType(Symbol::\alias(,,Symbol at))

  • bool isNumType(Symbol::\parameter(_,Symbol tvb))

  • bool isNumType(Symbol::\label(_,Symbol lt))

  • bool isNumType(Symbol::\num())

  • default bool isNumType(Symbol _)

Synopsis

Determine if the given type is a num.

1.14.33. isNodeType

Function
  • bool isNodeType(Symbol::\alias(,,Symbol at))

  • bool isNodeType(Symbol::\parameter(_,Symbol tvb))

  • bool isNodeType(Symbol::\label(_,Symbol lt))

  • bool isNodeType(Symbol::\node())

  • bool isNodeType(Symbol::\adt(,))

  • default bool isNodeType(Symbol _)

Synopsis

Determine if the given type is a node.

1.14.34. isVoidType

Function
  • bool isVoidType(Symbol::\alias(,,Symbol at))

  • bool isVoidType(Symbol::\parameter(_,Symbol tvb))

  • bool isVoidType(Symbol::\label(_,Symbol lt))

  • bool isVoidType(Symbol::\void())

  • default bool isVoidType(Symbol _)

Synopsis

Determine if the given type is a void.

1.14.35. isValueType

Function
  • bool isValueType(Symbol::\alias(,,Symbol at))

  • bool isValueType(Symbol::\parameter(_,Symbol tvb))

  • bool isValueType(Symbol::\label(_,Symbol lt))

  • bool isValueType(Symbol::\value())

  • default bool isValueType(Symbol _)

Synopsis

Determine if the given type is a value.

1.14.36. isLocType

Function
  • bool isLocType(Symbol::\alias(,,Symbol at))

  • bool isLocType(Symbol::\parameter(_,Symbol tvb))

  • bool isLocType(Symbol::\label(_,Symbol lt))

  • bool isLocType(Symbol::\loc())

  • default bool isLocType(Symbol _)

Synopsis

Determine if the given type is a loc.

1.14.37. isDateTimeType

Function
  • bool isDateTimeType(Symbol::\alias(,,Symbol at))

  • bool isDateTimeType(Symbol::\parameter(_,Symbol tvb))

  • bool isDateTimeType(Symbol::\label(_,Symbol lt))

  • bool isDateTimeType(Symbol::\datetime())

  • default bool isDateTimeType(Symbol _)

Synopsis

Determine if the given type is a datetime.

1.14.38. isSetType

Function
  • bool isSetType(Symbol::\alias(,,Symbol at))

  • bool isSetType(Symbol::\parameter(_,Symbol tvb))

  • bool isSetType(Symbol::\label(_,Symbol lt))

  • bool isSetType(Symbol::\set(_))

  • bool isSetType(Symbol::\rel(_))

  • default bool isSetType(Symbol _)

Synopsis

Determine if the given type is a set.

1.14.39. isRelType

Function
  • bool isRelType(Symbol::\alias(,,Symbol at))

  • bool isRelType(Symbol::\parameter(_,Symbol tvb))

  • bool isRelType(Symbol::\label(_,Symbol lt))

  • bool isRelType(Symbol::\rel(_))

  • bool isRelType(Symbol::\set(Symbol tp))

  • default bool isRelType(Symbol _)

Synopsis

Determine if the given type is a relation.

1.14.40. isListRelType

Function
  • bool isListRelType(Symbol::\alias(,,Symbol at))

  • bool isListRelType(Symbol::\parameter(_,Symbol tvb))

  • bool isListRelType(Symbol::\label(_,Symbol lt))

  • bool isListRelType(Symbol::\lrel(_))

  • bool isListRelType(Symbol::\list(Symbol tp))

  • default bool isListRelType(Symbol _)

Synopsis

Determine if the given type is a list relation.

1.14.41. isTupleType

Function
  • bool isTupleType(Symbol::\alias(,,Symbol at))

  • bool isTupleType(Symbol::\parameter(_,Symbol tvb))

  • bool isTupleType(Symbol::\label(_,Symbol lt))

  • bool isTupleType(Symbol::\tuple(_))

  • default bool isTupleType(Symbol _)

Synopsis

Determine if the given type is a tuple.

1.14.42. isListType

Function
  • bool isListType(Symbol::\alias(,,Symbol at))

  • bool isListType(Symbol::\parameter(_,Symbol tvb))

  • bool isListType(Symbol::\label(_,Symbol lt))

  • bool isListType(Symbol::\list(_))

  • bool isListType(Symbol::\lrel(_))

  • default bool isListType(Symbol _)

Synopsis

Determine if the given type is a list.

1.14.43. isListRelType

Function
  • bool isListRelType(Symbol::\alias(,,Symbol at))

  • bool isListRelType(Symbol::\parameter(_,Symbol tvb))

  • bool isListRelType(Symbol::\label(_,Symbol lt))

  • bool isListRelType(Symbol::\lrel(_))

  • default bool isListRelType(Symbol _)

Synopsis

Determine if the given type is a list relation.

1.14.44. isMapType

Function
  • bool isMapType(Symbol::\alias(,,Symbol at))

  • bool isMapType(Symbol::\parameter(_,Symbol tvb))

  • bool isMapType(Symbol::\label(_,Symbol lt))

  • bool isMapType(Symbol::\map(,))

  • default bool isMapType(Symbol _)

Synopsis

Determine if the given type is a map.

1.14.45. isBagType

Function
  • bool isBagType(Symbol::\alias(,,Symbol at))

  • bool isBagType(Symbol::\parameter(_,Symbol tvb))

  • bool isBagType(Symbol::\label(_,Symbol lt))

  • bool isBagType(Symbol::\bag(_))

  • default bool isBagType(Symbol _)

Synopsis

Determine if the given type is a bag (bags are not yet implemented).

1.14.46. isADTType

Function
  • bool isADTType(Symbol::\alias(,,Symbol at))

  • bool isADTType(Symbol::\parameter(_,Symbol tvb))

  • bool isADTType(Symbol::\label(_,Symbol lt))

  • bool isADTType(Symbol::\adt(,))

  • bool isADTType(Symbol::\reified(_))

  • default bool isADTType(Symbol _)

Synopsis

Determine if the given type is an Abstract Data Type (ADT).

1.14.47. isConstructorType

Function
  • bool isConstructorType(Symbol::\alias(,,Symbol at))

  • bool isConstructorType(Symbol::\parameter(_,Symbol tvb))

  • bool isConstructorType(Symbol::\label(_,Symbol lt))

  • bool isConstructorType(Symbol::\cons(Symbol _,str _,list[Symbol] _))

  • default bool isConstructorType(Symbol _)

Synopsis

Determine if the given type is a constructor.

1.14.48. isAliasType

Function
  • bool isAliasType(Symbol::\alias(,,_))

  • bool isAliasType(Symbol::\parameter(_,Symbol tvb))

  • bool isAliasType(Symbol::\label(_,Symbol lt))

  • default bool isAliasType(Symbol _)

Synopsis

Determine if the given type is an alias.

1.14.49. isFunctionType

Function
  • bool isFunctionType(Symbol::\alias(,,Symbol at))

  • bool isFunctionType(Symbol::\parameter(_,Symbol tvb))

  • bool isFunctionType(Symbol::\label(_,Symbol lt))

  • bool isFunctionType(Symbol::\func(,,_))

  • bool isFunctionType(Symbol::\func(,))

  • default bool isFunctionType(Symbol _)

Synopsis

Determine if the given type is a function.

1.14.50. isReifiedType

Function
  • bool isReifiedType(Symbol::\alias(,,Symbol at))

  • bool isReifiedType(Symbol::\parameter(_,Symbol tvb))

  • bool isReifiedType(Symbol::\label(_,Symbol lt))

  • bool isReifiedType(Symbol::\reified(_))

  • default bool isReifiedType(Symbol _)

Synopsis

Determine if the given type is a reified type.

1.14.51. isTypeVar

Function
  • bool isTypeVar(Symbol::\parameter(,))

  • bool isTypeVar(Symbol::\alias(,,Symbol at))

  • bool isTypeVar(Symbol::\label(_,Symbol lt))

  • default bool isTypeVar(Symbol _)

Synopsis

Determine if the given type is an type variable (parameter).

1.15. ValueIO

Usage

import ValueIO;

Synopsis

Library functions for reading and writing values in textual and binary format.

1.15.1. readValueFile

Function

value readValueFile(loc file)

Synopsis

Read a value from a binary file in PBF format.

1.15.2. getFileLength

Function

int getFileLength(loc file)

Synopsis

Get length of a file in number of bytes.

1.15.3. readBinaryValueFile

Function
  • &T readBinaryValueFile(type[&T] result, loc file)

  • value readBinaryValueFile(loc file)

Synopsis

Read a typed value from a binary file.

1.15.4. readTextValueFile

Function
  • &T readTextValueFile(type[&T] result, loc file)

  • value readTextValueFile(loc file)

Synopsis

Read a typed value from a text file.

1.15.5. readTextValueFileWithEmbeddedTypes

Function

&T readTextValueFileWithEmbeddedTypes(type[&T] result, loc file)

Synopsis

If you have written a file containing reified types, then you can use this function to read them back.

1.15.6. readTextValueString

Function
  • value readTextValueString(str input)

  • &T readTextValueString(type[&T] result, str input)

Synopsis

Parse a textual string representation of a value.

1.15.7. writeBinaryValueFile

Function

void writeBinaryValueFile(loc file, value val, bool compression = true)

Synopsis

Write a value to a file using an efficient binary file format.

1.15.8. writeTextValueFile

Function

void writeTextValueFile(loc file, value val)

Synopsis

Write a value to a file using a textual file format.

2. Vis

Synopsis

Functions for creating visualisations.

Description

The Rascal visualisation libraries provide a compositional visualisation framework and consists of:

  • The library [Figure] that defines the basic visualisation infrastructure.

  • The library [$Vis/Render] that defines the rendering of figures to a screen or file.

2.1. Figure

Synopsis

Overview of the complete Figure library.

Syntax

import vis::Figure;

Description

The Figure library provides visualization functionality that can be used to synthesize information. This plays, for example, a role in the synthesis part of the EASY paradigm. It is based on the following principles:

  • Coordinate free: only intrinsic properties of figures such as their height, width or color have to be specified. Their placement and actual coordinates are computed automatically.

  • Compositional: figures can be composed in many ways.

  • Declarative: the definition of a figure does not has any side-effects like, for example, changing the current drawing location or current drawing color.

  • Scalable: the dimensions of figures can be scaled automatically.

More precisely, figures:

  • …​ are ordinary values that can be computed and manipulated, e.g., by functions.

  • …​ only describe their own properties like dimensions and color.

  • …​ are unaware of their actual coordinate position.

  • …​ can be composed with other figures. Examples are horizontal and vertical composition, placement on a grid, graph or tree.

  • …​ can be reused in different contexts.

The Figure library provides two data types:

  • FProperty describes a property of a figure such as (also see [Properties]):

    • Sizing: [$Properties/size], [hsize] (or [width]), [vsize] (or [height]).

    • _ Positioning_: [align], [gap], [textAngle].

    • Visual appearance: [lineWidth], [lineColor], [lineStyle], [fillColor], [font], [fontSize], [fontColor], [shadow], [shapeConnected], [shapeClosed], [shapeCurved].

    • Interaction: [resizable], [onClick], [onKeyDown], [onKeyUp], [onMouseEnter], [onMouseExit], [onMouseDown], [onMouseUp], [onClick], [onMouseMove].

    • Other: [id]

  • Figure describes an actual visual element such as (also see [Figures]):

    • Atomic Figures: [$Figures/text], [$Figures/outline].

    • Containers: [box], [ellipse], [space].

    • Compositions: [hcat], [vcat], [hvcat], [overlay], [pack], [grid], [$Figures/tree], [treemap], [$Figures/graph].

    • Transformations: [$Figures/scale], [rotate].

Pitfalls

One of the functions [Render-render] or [Render-renderSave] are needed to actually view a Figure.

2.1.1. Angles

Synopsis

Conventions for defining angles.

Description

Various properties use angles. Angles are measured in degrees and, using an analog clock as metaphor, 0 degrees is at 3:00 hours and degrees go clockwise:

Angles
Pitfalls

There is at the moment no support for angles expressed in radians.

2.1.2. ColorModel

Synopsis

The model used for defining colors.

Types

alias Color = int;

Description

A color is expressed in the RGB color space and consists of a red, green and blue ingredient; each can have a value in the range [0-255]. In addition, colors can have a transparency, expressed as a percentage between 0.0 (completely opaque) and 1.0 (completely transparent). One can also refer to colors by name. The full range of X11 (HTML) Colors is supported.

A color can be constructed using:

  • the integer value of the color (RGBA, 8 bits per color)

  • the [rgb] function that combines the red, green and blue ingredient into an integer representation of the color.

  • the [color] function that maps color names to color values.

  • the [gray] function that creates gray scale values. # the [arbColor] function that creates an arbitrary color.

The following properties use colors:

  • [lineColor]: sets the color of lines and borders.

  • [fillColor]: sets the color for filling the inside of a figure.

  • [fontColor]: sets the color for text.

all these properties accept a Color value or, for convenience, also a color name.

Examples
[red]##java.lang.NullPointerException##
[red]##Error: Name size is not in scope##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name box is not in scope##
rascal>render(b1);
[red]##Error: Name b1 is not in scope##
[red]##Error: Name renderSave is not in scope##

displays: image::Libraries/Vis/Figure/ColorModel/b1.png[alt="b1"]

We can also use the RGB value of MidNightBlue directly

[red]##java.lang.NullPointerException##
[red]##Error: Name size is not in scope##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name rgb is not in scope##
[red]##Error: Name box is not in scope##
rascal>render(b2);
[red]##Error: Name b2 is not in scope##
[red]##Error: Name renderSave is not in scope##

and obtain (unsurprisingly) the same result: image::Libraries/Vis/Figure/ColorModel/b2.png[alt="b2"]

arbColor
Synopsis

Creates an arbitrary color.

Function

FProperty arbColor()

Examples
[red]##java.lang.NullPointerException##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name arbColor is not in scope##
[red]##Error: Name box is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name arbColor is not in scope##
[red]##Error: Name box is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name arbColor is not in scope##
[red]##Error: Name box is not in scope##
rascal>render(hcat([box1, box2, box3], std(size(50))));
[red]##Error: Name std is not in scope##
[red]##Error: Name box1 is not in scope##
[red]##Error: Name box3 is not in scope##
[red]##Error: Name renderSave is not in scope##
[red]##Error: Name size is not in scope##
[red]##Error: Name box2 is not in scope##
[red]##Error: Name hcat is not in scope##
a1
color
Synopsis

Return a color with a given name.

Color color(str name)
Color color(str name, real alpha)
Description

Returns color with given name. All HTML/X11 Color Names are supported. When the transparency alpha is given, the color is adjusted accordingly.

The list of available color names is given by colorNames.

Examples
[red]##java.lang.NullPointerException##
[red]##Error: Name color is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name size is not in scope##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name c is not in scope##
rascal>render(b1);
[red]##Error: Name b1 is not in scope##
[red]##Error: Name renderSave is not in scope##

gives image::Libraries/Vis/Figure/ColorModel/color/b1.png[alt="b1"] and with only 50% transparency:

[red]##java.lang.NullPointerException##
[red]##Error: Name color is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name size is not in scope##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name c is not in scope##
rascal>render(b1);
[red]##Error: Name b1 is not in scope##
[red]##Error: Name renderSave is not in scope##

gives image::Libraries/Vis/Figure/ColorModel/color/b2.png[alt="b2"]

colorNames
Synopsis

Sorted list of available color names that can be used by the [color] function.

Function

list[str] colorNames()

Examples
rascal>import vis::Figure;
[red]##Error: Cannot import module vis::Figure##
rascal>colorNames();
[red]##Error: Name colorNames is not in scope##

This functions can be used to create color tables.

[red]##java.lang.NullPointerException##
[red]##Error: Name box is not in scope##
[red]##Error: Name size is not in scope##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name colorNames is not in scope##
rascal>render(hvcat(boxes, width(500), left()));
[red]##Error: Name width is not in scope##
[red]##Error: Name hvcat is not in scope##
[red]##Error: Name renderSave is not in scope##
[red]##Error: Name boxes is not in scope##
[red]##Error: Name left is not in scope##
colors

Or a color table with the color names in colored boxes:

ok
[red]##Parse error##
[red]##Parse error##
[red]##Error: Name n is not in scope##
[red]##Error: Name elms is not in scope##
[red]##Error: Name n is not in scope##
[red]##Error: Name n is not in scope##
[red]##Error: Name elms is not in scope##
[red]##Error: Name n is not in scope##
[red]##Error: Name elms is not in scope##
[red]##Error: Name elms is not in scope##
[red]##Parse error##
[red]##java.lang.NullPointerException##
[red]##Error: Name left is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name colorNames is not in scope##
[red]##Error: Name text is not in scope##
[red]##Error: Name fillColor is not in scope##
rascal>render(grid(split(boxes, 3)));
[red]##Error: Name boxes is not in scope##
[red]##Error: Name renderSave is not in scope##
[red]##Error: Name grid is not in scope##
c3
colorScale
Synopsis

Compute a color scale for range of values.

Function

Color(&T <: num) colorScale(list[&T <: num] values, Color from, Color to)

Description

Given a list of numbers values, colorScale returns a function that maps these numbers to a color scale between the colors from and to.

Examples
list[int]: [10,20,-50,13,-40,25]
[red]##java.lang.NullPointerException##
[red]##Error: Name color is not in scope##
[red]##Error: Name colorScale is not in scope##
[red]##Error: Name color is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name box is not in scope##
[red]##Error: Name cscale is not in scope##
[red]##Error: Name size is not in scope##
[red]##Error: Name text is not in scope##
[red]##Error: Name fillColor is not in scope##
rascal>render(hcat(boxes));
[red]##Error: Name boxes is not in scope##
[red]##Error: Name renderSave is not in scope##
[red]##Error: Name hcat is not in scope##

gives image::Libraries/Vis/Figure/ColorModel/colorScale/h1.png[alt="h1"]

colorSteps
Synopsis

Create a list of intermediate colors between two colors.

Function

list[Color] colorSteps(Color from, Color to, int steps)

Description

Create a list of interpolated colors between from and to in a given number of steps.

Examples
[red]##java.lang.NullPointerException##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name colorSteps is not in scope##
[red]##Error: Name color is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name size is not in scope##
[red]##Error: Name color is not in scope##
rascal>render(hcat(boxes));
[red]##Error: Name boxes is not in scope##
[red]##Error: Name renderSave is not in scope##
[red]##Error: Name hcat is not in scope##

gives:

h1
gray
Synopsis

The color gray.

Color gray(int g)
Color gray(int g, real alpha)
Color gray(real perc)
Color gray(real perc, real alpha)
Description

Create gray colors in various shades:

Create a gray color between black (0) and white (255).
Create a gray color between black (0) and white (255) with transparency alpha.
Create a gray color between black (0.0) and white (1.0).
Create a gray color between black (0.0) and white (1.0) transparency alpha.
Examples

Setting gray values with an integer in the range [0,255]:

[red]##java.lang.NullPointerException##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name gray is not in scope##
[red]##Error: Name box is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name gray is not in scope##
[red]##Error: Name box is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name gray is not in scope##
[red]##Error: Name box is not in scope##
rascal>render(hcat([b1, b2, b3], size(50)));
[red]##Error: Name size is not in scope##
[red]##Error: Name renderSave is not in scope##
[red]##Error: Name b3 is not in scope##
[red]##Error: Name b2 is not in scope##
[red]##Error: Name b1 is not in scope##
[red]##Error: Name hcat is not in scope##

gives: image::Libraries/Vis/Figure/ColorModel/gray/h1.png[alt="h1"]

Setting gray values with an a percentage in the range [0.0, 1.0]:

[red]##java.lang.NullPointerException##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name gray is not in scope##
[red]##Error: Name box is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name gray is not in scope##
[red]##Error: Name box is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name gray is not in scope##
[red]##Error: Name box is not in scope##
rascal>render(hcat([b1, b2, b3], size(50)));
[red]##Error: Name size is not in scope##
[red]##Error: Name renderSave is not in scope##
[red]##Error: Name b3 is not in scope##
[red]##Error: Name b2 is not in scope##
[red]##Error: Name b1 is not in scope##
[red]##Error: Name hcat is not in scope##

gives: image::Libraries/Vis/Figure/ColorModel/gray/h2.png[alt="h2"]

Setting transparency:

[red]##java.lang.NullPointerException##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name gray is not in scope##
[red]##Error: Name box is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name gray is not in scope##
[red]##Error: Name box is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name gray is not in scope##
[red]##Error: Name box is not in scope##
rascal>render(hcat([b1, b2, b3], size(50)));
[red]##Error: Name size is not in scope##
[red]##Error: Name renderSave is not in scope##
[red]##Error: Name b3 is not in scope##
[red]##Error: Name b2 is not in scope##
[red]##Error: Name b1 is not in scope##
[red]##Error: Name hcat is not in scope##

gives: image::Libraries/Vis/Figure/ColorModel/gray/h3.png[alt="h3"]

interpolateColor
Synopsis

Interpolate between two colors.

Function

Color interpolateColor(Color from, Color to, real percentage)

Description

Interpolate between two colors (in RGB space). The percentage indicates the distance between the from and the to color.

Examples
[red]##java.lang.NullPointerException##
[red]##Error: Name color is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name color is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name size is not in scope##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name to is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name interpolateColor is not in scope##
[red]##Error: Name from is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name size is not in scope##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name to is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name interpolateColor is not in scope##
[red]##Error: Name from is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name size is not in scope##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name to is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name interpolateColor is not in scope##
[red]##Error: Name from is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name size is not in scope##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name to is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name interpolateColor is not in scope##
[red]##Error: Name from is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name size is not in scope##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name to is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name interpolateColor is not in scope##
[red]##Error: Name from is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name size is not in scope##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name to is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name interpolateColor is not in scope##
[red]##Error: Name from is not in scope##
rascal>render(hcat([b1, b2, b3, b4, b5, b6]));
[red]##Error: Name renderSave is not in scope##
[red]##Error: Name b4 is not in scope##
[red]##Error: Name b3 is not in scope##
[red]##Error: Name b2 is not in scope##
[red]##Error: Name b1 is not in scope##
[red]##Error: Name b6 is not in scope##
[red]##Error: Name b5 is not in scope##
[red]##Error: Name hcat is not in scope##

gives: image::Libraries/Vis/Figure/ColorModel/interpolateColor/h1.png[alt="h1"]

palette
Synopsis

A standard palette of 12 colors.

Function

str palette(int n)

Description

Provides a color name from a palette of 12 good distinguishable colors.

Examples
[red]##java.lang.NullPointerException##
[red]##Error: Name palette is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name size is not in scope##
[red]##Error: Name fillColor is not in scope##
rascal>render(hcat(boxes));
[red]##Error: Name boxes is not in scope##
[red]##Error: Name renderSave is not in scope##
[red]##Error: Name hcat is not in scope##

gives:

h1
Pitfalls

Arguments outside the interval [0,11] are mapped to "black".

rgb
Synopsis

Create a color from a red, green and blue contribution.

Color rgb(int red, int green, int blue)
Color rgb(int red, int green, int blue, real alpha)
Description

Create a color from a red, green and blue contribution each in the range [0,255]. An optional transparency alpha may be given between 0.0 (completely opaque) and 1.0 (completely transparent).

Examples
[red]##java.lang.NullPointerException##
[red]##Error: Name size is not in scope##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name rgb is not in scope##
[red]##Error: Name box is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name size is not in scope##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name rgb is not in scope##
[red]##Error: Name box is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name size is not in scope##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name rgb is not in scope##
[red]##Error: Name box is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name size is not in scope##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name rgb is not in scope##
[red]##Error: Name box is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name b4 is not in scope##
[red]##Error: Name b3 is not in scope##
[red]##Error: Name b2 is not in scope##
[red]##Error: Name b1 is not in scope##
rascal>render(hcat(boxes));
[red]##Error: Name boxes is not in scope##
[red]##Error: Name renderSave is not in scope##
[red]##Error: Name hcat is not in scope##

gives: image::Libraries/Vis/Figure/ColorModel/rgb/h1.png[alt="h1"]

2.1.3. CompositionModel

Synopsis

The model for composing figures.

Description

The Figure library uses the following model for the composition of figures:

Composition Model

The ingredients are:

  • [Properties/size] determines the minimal horizontal and vertical size of a figure. Sizes can be set separately per dimension using [hsize] (synonym [width]) or [vsize] (synonym: [height]). Figures can never become smaller than their minimal size.

  • [shrink] determines how much smaller a figure is relative to its parent size. Shrink can also be set per dimension using [hshrink] or [vshrink].

  • [grow] determines how much larger a figure is relative to its child size. Grow can also be set per dimension using [hgrow] or [vgrow].

  • [align] determines the alignment of a figure relative to its parent. Alignment can also be set per dimension using [halign] or [halign].

A number of shorthands is provided for common alignment values:

Shorthand

Corresponds to

See

:------------

:-------------------

:---------------------

left()

halign(0.0)

[Properties/left]

hcenter()

halign(0.5)

[Properties/hcenter]

right()

halign(1.0)

[Properties/right]

top()

valign(0.0)

[Properties/top]

vcenter()

valign(0.5)

[Properties/vcenter]

bottom()

valign(1.0)

[Properties/bottom]

center()

align(0.5, 0.5)

[Properties/center]

The following units are used:

  • sizes are expressed in pixels, i.e., screen points.

  • align, grow and shrink are expressed as percentage of width and/or height and have a value between 0.0 and 1.0.

Pitfalls
  • Although sizes are traditionally used to determine the size of geometric figures, it is better to use relative sizes using grow, shrink and align since this makes figures resizable.

  • [resizable] can be used to control the resizing behaviour of a figure.

2.1.4. Figures

Synopsis

Overview of all figures.

Types
  • Figure

  • alias Figures = list[Figure];

Description

Figure is the primary data type that represents figures. A list of figures is represented by the type Figures. Figures can be classified as follows:

  • Atomic Figures: indivisible figures such as [$Figures/text] and [$Figures/outline].

  • Containers: most figures may act as containers for other figures. For example, a [box] and [ellipse] may contain an arbitrarily complex subfigure.

  • Compositions: serve to combine figures into new figures. Examples are horizontal ([hcat]) or vertical ([vcat]) concatenation or placement of figures in a [grid], graph or tree.

  • Transformations: perform geometric transformations on a given figure.

  • Interaction: provide interaction with the user, see [computeFigure], [fswitch], [button], [textfield], [combo], [checkbox], scaleSlider,[scrollable], [hscrollable] and [vscrollable].

Pitfalls

We are cheating a bit with the above data declaration for Figure. The current version of Rascal does not yet support data constructors with a variable number of arguments as needed for the properties. At the moment, the above constructors are provided as Rascal functions that can have variable arguments, see [Function Declaration].

LineDecoration
Synopsis

Describes the line decorations for an [$Figures/outline].

Types
public data LineDecoration =
    info(int lineNumber, str msg)
  | warning(int lineNumber, str msg)
  | error(int lineNumber, str msg)
  | highlight(int lineNumber, str msg)
  | highlight(int lineNumber, str msg, int level)
  ;
box
Synopsis

A rectangular box.

Figure box(FProperty props…​)
Figure box(Figure inner, FProperty props…​)
Description

Draw a rectangular box using the properties props. An optional nested figure inner may be placed inside the box.

Examples

Lets start with a box b0 of given (minimal) dimensions:

[red]##java.lang.NullPointerException##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name size is not in scope##
rascal>render(b0);
[red]##Error: Name renderSave is not in scope##
[red]##Error: Name b0 is not in scope##

that will display as: image::Libraries/Vis/Figure/Figures/box/box0.png[alt="box0"]

We can nest a new box b1 in box b0 as follows:

[red]##java.lang.NullPointerException##
[red]##Error: Name shrink is not in scope##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name box is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name b1 is not in scope##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name size is not in scope##
rascal>render(b0);
[red]##Error: Name renderSave is not in scope##
[red]##Error: Name b0 is not in scope##

The result is: image::Libraries/Vis/Figure/Figures/box/box1.png[alt="box1"]

Note that:

  • Box b0 contains box b1.

  • The dimensions of b1 are determined by shrinking to 80% of the dimensions of b0.

The placement of an inner figure is determined by alignment, see [align]. We can, for instance, place b1 in the top left corner of b0:

[red]##java.lang.NullPointerException##
[red]##Error: Name shrink is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name align is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name b1 is not in scope##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name size is not in scope##
rascal>render(b0);
[red]##Error: Name renderSave is not in scope##
[red]##Error: Name b0 is not in scope##

The result is: image::Libraries/Vis/Figure/Figures/box/box2.png[alt="box2"]

Placing b1 in the bottom right corner of b0:

[red]##java.lang.NullPointerException##
[red]##Error: Name shrink is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name align is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name b1 is not in scope##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name size is not in scope##
rascal>render(b0);
[red]##Error: Name renderSave is not in scope##
[red]##Error: Name b0 is not in scope##

gives: image::Libraries/Vis/Figure/Figures/box/box3.png[alt="box3"]

We can also nest box b0 in another box b2 and make b2 20% larger than b0:

[red]##java.lang.NullPointerException##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name size is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name grow is not in scope##
[red]##Error: Name b0 is not in scope##
[red]##Error: Name box is not in scope##
rascal>render(b2);
[red]##Error: Name b2 is not in scope##
[red]##Error: Name renderSave is not in scope##

The result is: image::Libraries/Vis/Figure/Figures/box/box4.png[alt="box4"]

If no sizes are given at all then the box will expand to fill the available size:

[red]##Error: Name shrink is not in scope##
[red]##Error: Name render is not in scope##
[red]##Error: Name shrink is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name shrink is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name box is not in scope##

The result is: image::Libraries/Vis/Figure/Figures/box/box5.png[alt="box5"]

button
Synopsis

An interactive push button.

Function

Figure button(str label, void () vcallback, FProperty props…​)

Description

A button with the text label. Whenever the user clicks on this button, callback vcallback is called. Typically, the callback causes a state change in the Rascal program (e.g., the value of a variable is changed) and this variable is used in another part of the figure.

Examples
[red]##Parse error##
int: 0
[red]##Parse error##
[red]##Error: Name text is not in scope##
[red]##Parse error##
[red]##Parse error##
rascal>render(inc());
[red]##Error: Name renderSave is not in scope##
[red]##Error: Name inc is not in scope##
b1

Clicking the button will increment the value of n.

Pitfalls

Unfortunately we cannot show an interactive version of the above example here. Try it out in Rascal itself.

checkbox
Synopsis

An interactive checkbox.

Function

Figure checkbox(str text, void(bool state) vcallback, FProperty props…​)

Description

A checkbox that can be selected or deselected by the user. Whenever this occurs, vcallback is called. The state argument of the callback is true when the check box is checked (= selected).

Examples
[red]##Parse error##
bool: false
[red]##Parse error##
[red]##Error: Name left is not in scope##
[red]##Error: Name text is not in scope##
[red]##Parse error##
[red]##Parse error##
rascal>render(check());
[red]##Error: Name check is not in scope##
[red]##Error: Name renderSave is not in scope##
c1

Checking the checkbox will change the variable state and this is reflected in the changed text.

Pitfalls

Unfortunately we cannot show an interactive version of the above example here. Try it out in Rascal itself.

Due to limitations in SWT this does not behave correctly when being placed over or under figures, so do not use them in [overlay] or [mouseOver].

choice
Synopsis

An interactive choice.

Function

choice(list[str] choices, void(str s) ccallback, FProperty props…​)

Description

Presents a list of named choices to the user. When the user selects one of them, callback ccallback is called with that choice as argument.

[red]##Parse error##
str: "A"
[red]##Parse error##
[red]##Error: Name left is not in scope##
[red]##Error: Name text is not in scope##
[red]##Parse error##
[red]##Parse error##
rascal>render(choiceTest());
[red]##Error: Name renderSave is not in scope##
[red]##Error: Name choiceTest is not in scope##
choice1
Pitfalls

Due to limitations in SWT this does not behave correctly when being placed over or under figures, so do not use them in [overlay] or [mouseOver].

combo
Synopsis

An interactive combo box.

Function

Figure combo(list[str] choices, void(str s) ccallback, FProperty props…​)

Description

Presents a combo box with a list of named choices to the user. When the user selects one of them, callback ccallback is called with that choice as argument.

Examples
[red]##Parse error##
str: "A"
[red]##Parse error##
[red]##Error: Name left is not in scope##
[red]##Error: Name text is not in scope##
[red]##Parse error##
[red]##Parse error##
rascal>render(comboTest());
[red]##Error: Name renderSave is not in scope##
[red]##Error: Name comboTest is not in scope##
combo1
Pitfalls

Due to limitations in SWT this does not behave correctly when being placed over or under figures, so do not use them in [overlay] or [mouseOver].

computeFigure
Synopsis

A dynamically computed figure.

Figure computeFigure(Figure () computeFig, FProperty props…​)
Figure computeFigure(bool() recomp, Figure () computeFig, FProperty props…​)
Description

Return the figure that is returned by the callback computeFig.

Subsequent calls to computeFig may return different figures and may thus change the resulting visualization. The figure is recomputed after each user interaction.

Optionally, a function recomp may be given that checks whether the figure should be recomputed.

edge
Synopsis

An edge in a graph.

Function

Edge edge(str from, str to, FProperty props…​)

Description

An edge connects nodes in graphs. The arguments from and to are node [id]s.

Applicable properties are:

  • [fromArrow]

  • [toArrow]

Examples

See graph.

ellipse
Synopsis

An ellipse.

FProperty ellipse(FProperty props…​)
FProperty ellipse(Figure inner, FProperty props)
Description

Draw an ellipse using the sizes given in properties props. An optional nested figure fig may be placed inside the ellipse.

Examples

The fragment

[red]##java.lang.NullPointerException##
[red]##Error: Name width is not in scope##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name ellipse is not in scope##
[red]##Error: Name height is not in scope##
rascal>render(e1);
[red]##Error: Name renderSave is not in scope##
[red]##Error: Name e1 is not in scope##

will display: image::Libraries/Vis/Figure/Figures/ellipse/e1.png[alt="ellipse 1"]

Nesting, for instance, a box in an ellipse

[red]##java.lang.NullPointerException##
[red]##Error: Name width is not in scope##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name height is not in scope##
[red]##Error: Name box is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name std is not in scope##
[red]##Error: Name b1 is not in scope##
[red]##Error: Name ellipse is not in scope##
[red]##Error: Name gap is not in scope##
[red]##Error: Name fillColor is not in scope##
rascal>render(e1);
[red]##Error: Name renderSave is not in scope##
[red]##Error: Name e1 is not in scope##

gives:

ellipse 2
fswitch
Synopsis

Dynamic selection from a fixed list of figures.

Function

Figure fswitch(int () choice, Figures fs, Fproprty props …​)

Description

Select one of the figures in the fixed list of figures fs. The result of the function choice determines which of the figures to select.

The minimal size of the figure is maximal minimal size of all the choices. That means that if a switch is made from choice a to b, the size required for the fswitch will not change.

graph
Synopsis

Graph layout.

Function

Figure graph(Figures nodes, list[Edge] edges, FProperty props…​)

Description

Takes a list of nodes and a list of edges and draws a graph. The nodes can be arbitrary figures that should have a name (using the [id] property). The edges determine connections between named nodes.

The following constraints apply:

  • All nodes should have an id property with a unique value.

  • All edges should refer to ids that are defined by the nodes.

The following properties are applicable to graphs:

  • [id] to define the identity of nodes and to define edges between nodes.

  • [hint] determines the layout algorithm to use. Currently, only "layered" is supported.

  • [layer] is used to define the placement of nodes in the same layer.

  • [orientation] is used to define the drawing direction.

  • [toArrow] and [fromArrow] are used to define arrows on edges.

  • [$Properties/label] defines an edge label.

Examples
[red]##Parse error##
[red]##Parse error##
[red]##Parse error##
[red]##Parse error##
[red]##Parse error##
[red]##Error: Name text is not in scope##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name id is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name size is not in scope##
[red]##Parse error##
[red]##Parse error##
[red]##Parse error##
[red]##Error: Name edge is not in scope##
[red]##Parse error##
rascal>render(graph(nodes, edges, hint("layered"), gap(100)));
[red]##Error: Name nodes is not in scope##
[red]##Error: Name renderSave is not in scope##
[red]##Error: Name hint is not in scope##
[red]##Error: Name edges is not in scope##
[red]##Error: Name graph is not in scope##
[red]##Error: Name gap is not in scope##
graph 1
[red]##Parse error##
[red]##Parse error##
[red]##Parse error##
[red]##Parse error##
[red]##Parse error##
[red]##Parse error##
[red]##Parse error##
[red]##Parse error##
[red]##Parse error##
[red]##Parse error##
[red]##Parse error##
[red]##Parse error##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name id is not in scope##
[red]##Error: Name text is not in scope##
[red]##Parse error##
[red]##Parse error##
[red]##Parse error##
[red]##Parse error##
[red]##Parse error##
[red]##Parse error##
[red]##Parse error##
rascal>render(graph(nodes, edges, hint("layered"), std(size(30)), gap(40)));
[red]##Error: Name std is not in scope##
[red]##Error: Name nodes is not in scope##
[red]##Error: Name renderSave is not in scope##
[red]##Error: Name size is not in scope##
[red]##Error: Name hint is not in scope##
[red]##Error: Name gap is not in scope##
[red]##Error: Name edges is not in scope##
[red]##Error: Name graph is not in scope##
graph 2
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name text is not in scope##
[red]##Error: Name id is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name grow is not in scope##
[red]##Error: Name color is not in scope##
[red]##Parse error##
[red]##Parse error##
[red]##Parse error##
[red]##Parse error##
[red]##Parse error##
[red]##Parse error##
[red]##Parse error##
[red]##Parse error##
rascal>render(graph(nodes, edges, hint("spring"), size(500), gap(20)));
[red]##Error: Name gap is not in scope##
[red]##Error: Name nodes is not in scope##
[red]##Error: Name renderSave is not in scope##
[red]##Error: Name size is not in scope##
[red]##Error: Name hint is not in scope##
[red]##Error: Name edges is not in scope##
[red]##Error: Name graph is not in scope##
graph 3
Pitfalls
  • The layered graph layout performs currently best when:

    • the [hgap] is set to a value equal to the average width of the nodes.

    • [orientation] is not used.

  • For spring layout the following do not yet work:

    • labels,

    • arrows.

grid
Synopsis

Place figures in a grid with cells of equal size.

Function

grid(list[list[Figure]] figs, FProperty props…​)

Description

Layout figures in a grid.

All elements that are resizable and do not specify a [shrink] will be get of the same size. For example:

[red]##Parse error##
[red]##Parse error##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name box is not in scope##
[red]##Parse error##
[red]##Parse error##
[red]##Parse error##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name text is not in scope##
[red]##Error: Name box is not in scope##
[red]##Parse error##
rascal>render(grid([row1, row2]));
[red]##Error: Name row2 is not in scope##
[red]##Error: Name renderSave is not in scope##
[red]##Error: Name grid is not in scope##
[red]##Error: Name row1 is not in scope##

gives:

grid1

If an element specifies a [hshrink] then this element will get a portion [hshrink] of the total width of the grid. Similarly, if an an element specifies a [vshrink] then this element will get a portion [vshrink] of the total height of the grid. For example:

[red]##Parse error##
[red]##Parse error##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name box is not in scope##
[red]##Parse error##
[red]##Parse error##
[red]##Parse error##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name text is not in scope##
[red]##Error: Name box is not in scope##
[red]##Parse error##
rascal>render(grid([row1, row2]));
[red]##Error: Name row2 is not in scope##
[red]##Error: Name renderSave is not in scope##
[red]##Error: Name grid is not in scope##
[red]##Error: Name row1 is not in scope##

gives:

grid2

If a row or column contains only non-resizable elements then the entire row or column will not be resized. For example:

[red]##Parse error##
[red]##Parse error##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name box is not in scope##
[red]##Parse error##
[red]##Parse error##
[red]##Parse error##
[red]##Error: Name vsize is not in scope##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name vresizable is not in scope##
[red]##Error: Name bottom is not in scope##
[red]##Error: Name box is not in scope##
[red]##Parse error##
[red]##java.lang.NullPointerException##
[red]##Error: Name row2 is not in scope##
[red]##Error: Name size is not in scope##
[red]##Error: Name row1 is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name grid is not in scope##
rascal>render(b);
[red]##Error: Name b is not in scope##
[red]##Error: Name renderSave is not in scope##

Gives

grid3

If the total [hshrink] in a row is more than 1.0 or if the total [hshrink] of a row is 1.0 but there are elements in row which do not specify a hshrink but do need space. Then we cannot meet the constraints and the grid will show a Grid over-constrained message. The same holds for [vshrink].

For example:

[red]##Parse error##
[red]##Parse error##
[red]##Error: Name text is not in scope##
[red]##Error: Name box is not in scope##
[red]##Parse error##
rascal>render(grid(<<row1>>));
[red]##Error: Name renderSave is not in scope##
[red]##Error: Name row1 is not in scope##
[red]##Error: Name grid is not in scope##

Gives

grid4

To insert white space between figures we can specify the [hgrow] and [vgrow]. For example [hgrow] indicates that the grid will be [hgrow] as wide as combined width of the elements, the extra space will be used for gaps between the rows.

[red]##Parse error##
[red]##Parse error##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name box is not in scope##
[red]##Parse error##
[red]##Parse error##
[red]##Parse error##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name text is not in scope##
[red]##Error: Name box is not in scope##
[red]##Parse error##
rascal>render(grid([row1, row2],hgrow(1.1),vgrow(1.3)));
[red]##Error: Name row2 is not in scope##
[red]##Error: Name renderSave is not in scope##
[red]##Error: Name hgrow is not in scope##
[red]##Error: Name grid is not in scope##
[red]##Error: Name row1 is not in scope##
[red]##Error: Name vgrow is not in scope##

Gives

grid5

Alternatively we can use [hgap] and [vgap] to specify the gap in pixels, instead of relative to the size of the elements.

For example:

[red]##Parse error##
[red]##Parse error##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name box is not in scope##
[red]##Parse error##
[red]##Parse error##
[red]##Parse error##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name text is not in scope##
[red]##Error: Name box is not in scope##
[red]##Parse error##
rascal>render(grid([row1, row2],hgap(10),vgap(15)));
[red]##Error: Name hgap is not in scope##
[red]##Error: Name renderSave is not in scope##
[red]##Error: Name grid is not in scope##
[red]##Error: Name row1 is not in scope##
[red]##Error: Name row2 is not in scope##
[red]##Error: Name vgap is not in scope##

Gives

grid6

If both [hgrow] and [hgap] are set then the property which gives the largest gap will be used.

If one row is shorter than the other then the missing elements of that row are considered to be empty.

[red]##Parse error##
[red]##Parse error##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name box is not in scope##
[red]##Parse error##
[red]##Parse error##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name box is not in scope##
[red]##Parse error##
[red]##java.lang.NullPointerException##
[red]##Error: Name box is not in scope##
[red]##Error: Name fillColor is not in scope##
rascal>render(grid([row1, row2, row3]));
[red]##Error: Name row2 is not in scope##
[red]##Error: Name renderSave is not in scope##
[red]##Error: Name grid is not in scope##
[red]##Error: Name row3 is not in scope##
[red]##Error: Name row1 is not in scope##

Gives

grid7

[hcat] and [vcat] are special cases of grid.

Examples

Element with a fixed size:

[red]##Parse error##
[red]##Parse error##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name box is not in scope##
[red]##Parse error##
[red]##Parse error##
[red]##Parse error##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name box is not in scope##
[red]##Parse error##
[red]##java.lang.NullPointerException##
[red]##Error: Name box is not in scope##
[red]##Error: Name fillColor is not in scope##
rascal>render(grid([row1, row2, row3]));
[red]##Error: Name row2 is not in scope##
[red]##Error: Name renderSave is not in scope##
[red]##Error: Name grid is not in scope##
[red]##Error: Name row3 is not in scope##
[red]##Error: Name row1 is not in scope##

gives:

grid2

And now changing the alignment of b2:

[red]##Parse error##
[red]##Parse error##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name box is not in scope##
[red]##Parse error##
[red]##Parse error##
[red]##Parse error##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name box is not in scope##
[red]##Parse error##
[red]##java.lang.NullPointerException##
[red]##Error: Name box is not in scope##
[red]##Error: Name fillColor is not in scope##
rascal>render(grid([row1, row2, row3]));
[red]##Error: Name row2 is not in scope##
[red]##Error: Name renderSave is not in scope##
[red]##Error: Name grid is not in scope##
[red]##Error: Name row3 is not in scope##
[red]##Error: Name row1 is not in scope##

gives:

grid3
hcat
Synopsis

Horizontal composition of a list of figures.

Function

Figure hcat(Figures figs, FProperty props…​)

Description

Horizontal composition is a special case of [grid]. It is a grid with just one row. See [grid] for more information.

See also [vcat].

Examples
[red]##java.lang.NullPointerException##
[red]##Error: Name vshrink is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name fillColor is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name vshrink is not in scope##
[red]##Error: Name box is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name vshrink is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name fillColor is not in scope##
rascal>render(hcat([b1, b2, b3]));
[red]##Error: Name renderSave is not in scope##
[red]##Error: Name b3 is not in scope##
[red]##Error: Name b2 is not in scope##
[red]##Error: Name b1 is not in scope##
[red]##Error: Name hcat is not in scope##

gives: image::Libraries/Vis/Figure/Figures/hcat/h1.png[alt="h1"]

b2 aligned at the top:

[red]##java.lang.NullPointerException##
[red]##Error: Name vshrink is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name fillColor is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name vshrink is not in scope##
[red]##Error: Name top is not in scope##
[red]##Error: Name box is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name vshrink is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name fillColor is not in scope##
rascal>render(hcat([b1, b2, b3]));
[red]##Error: Name renderSave is not in scope##
[red]##Error: Name b3 is not in scope##
[red]##Error: Name b2 is not in scope##
[red]##Error: Name b1 is not in scope##
[red]##Error: Name hcat is not in scope##

gives: image::Libraries/Vis/Figure/Figures/hcat/h2.png[alt="h2"]

b2 aligned at the bottom:

[red]##java.lang.NullPointerException##
[red]##Error: Name vshrink is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name fillColor is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name vshrink is not in scope##
[red]##Error: Name bottom is not in scope##
[red]##Error: Name box is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name vshrink is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name fillColor is not in scope##
rascal>render(hcat([b1, b2, b3]));
[red]##Error: Name renderSave is not in scope##
[red]##Error: Name b3 is not in scope##
[red]##Error: Name b2 is not in scope##
[red]##Error: Name b1 is not in scope##
[red]##Error: Name hcat is not in scope##

gives: image::Libraries/Vis/Figure/Figures/hcat/h3.png[alt="h3"]

All boxes aligned at the bottom:

[red]##java.lang.NullPointerException##
[red]##Error: Name vshrink is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name fillColor is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name vshrink is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name fillColor is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name vshrink is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name fillColor is not in scope##
rascal>render(hcat([b1, b2, b3],std(bottom())));
[red]##Error: Name b3 is not in scope##
[red]##Error: Name b2 is not in scope##
[red]##Error: Name b1 is not in scope##
[red]##Error: Name std is not in scope##
[red]##Error: Name hcat is not in scope##
[red]##Error: Name bottom is not in scope##
[red]##Error: Name renderSave is not in scope##

gives: image::Libraries/Vis/Figure/Figures/hcat/h6.png[alt="h6"]

hscreen
Synopsis

Creates a horizontal screen on which things can be projected.

Function

Figure hscreen(Figure inner,FProperty prop…​)

Description

Figures nested within the hscreen can project figures onto the screen using the [project] property. A screen must have an [id] property giving its name.

The position of the hscreen depends on the alignment of the inner figure. If the inner figure is placed at the top then the screen will be at the bottom and vice versa.

[red]##java.lang.NullPointerException##
[red]##Error: Name project is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name top is not in scope##
[red]##Error: Name hcat is not in scope##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name text is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name hscreen is not in scope##
[red]##Error: Name id is not in scope##
[red]##Error: Name i is not in scope##
rascal>render(sc);
[red]##Error: Name sc is not in scope##
[red]##Error: Name renderSave is not in scope##
hscreen1
[red]##java.lang.NullPointerException##
[red]##Error: Name project is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name bottom is not in scope##
[red]##Error: Name hcat is not in scope##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name text is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name hscreen is not in scope##
[red]##Error: Name id is not in scope##
[red]##Error: Name i is not in scope##
rascal>render(sc);
[red]##Error: Name sc is not in scope##
[red]##Error: Name renderSave is not in scope##
hscreen2

If the inner figure specifies a shrink then the remaining size is used for the screen, otherwise the minimal size is used.

[red]##java.lang.NullPointerException##
[red]##Error: Name project is not in scope##
[red]##Error: Name top is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name hcat is not in scope##
[red]##Error: Name vshrink is not in scope##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name text is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name hscreen is not in scope##
[red]##Error: Name id is not in scope##
[red]##Error: Name i is not in scope##
rascal>render(sc);
[red]##Error: Name sc is not in scope##
[red]##Error: Name renderSave is not in scope##
hscreen4

Alignment and shrinking of projected figures also works.

[red]##Parse error##
[red]##Parse error##
[red]##java.lang.NullPointerException##
[red]##Error: Name hgrow is not in scope##
[red]##Error: Name top is not in scope##
[red]##Error: Name vshrink is not in scope##
[red]##Error: Name hscreen is not in scope##
[red]##Error: Name boxes is not in scope##
[red]##Error: Name hcat is not in scope##
[red]##Error: Name id is not in scope##
rascal>render(s);
[red]##Error: Name renderSave is not in scope##
[red]##Error: Name s is not in scope##
hscreen5

Also see [vscreen].

hscrollable
Synopsis

Embed a figure in a horizontally scrollable plane.

Function

Figure hscrollable(Figure f, FProperty props …​)

Description

Embeds figure f in a scrollable plane. The full height of f will always be shown, but if the horizontal space for the hscrollable is too small to show the entire figure f then a horizontal scrollbar will appear. The minimal height of the hscrollable is the minimal height of the figure f plus the height of a horizontal scrollbar, and the minimal width is the minimal width required to show a horizontal scrollbar (unless the minimal size is specified by [Properties-size]).

Also see [scrollable] and [vscrollable].

Examples
[red]##java.lang.NullPointerException##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name hsize is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name shrink is not in scope##
[red]##Error: Name box1 is not in scope##
[red]##Error: Name hscrollable is not in scope##
rascal>render(box(sb,fillColor("red")));
[red]##Error: Name sb is not in scope##
[red]##Error: Name renderSave is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name fillColor is not in scope##
s1
Pitfalls

When rendering on-screen the figure is always displayed in a scrollable area. Thus using a scrollable as a top level figure makes little sense, as there is no observable difference between render(hscrollable(g)) and render(g). In both cases horizontal as well as vertical scrollbars may appear.

hvcat
Synopsis

Horizontal and vertical composition of a list of figures.

Function

Figure hvcat(Figures figs, FProperty props…​)

Description

Horizontal and vertical composition of a list of figures within a given width comparable to the horizontal and vertical placement of words in a paragraph of text.

Figures are placed horizontally as long as they fit within the given width. If a figure would exceed that width it is placed on the next row of figures.

Within each row, the horizontal gap controls the distance between figures and the vertical alignment of each figure controls its alignment in the row.

The distance between rows is controlled by the vertical gap.

Examples
[red]##java.lang.NullPointerException##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name size is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name size is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name size is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name size is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name size is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name size is not in scope##
rascal>render(hvcat([b1, b2, b3, b4, b5, b6], gap(5)));
[red]##Error: Name hvcat is not in scope##
[red]##Error: Name renderSave is not in scope##
[red]##Error: Name b4 is not in scope##
[red]##Error: Name b3 is not in scope##
[red]##Error: Name b2 is not in scope##
[red]##Error: Name b1 is not in scope##
[red]##Error: Name b5 is not in scope##
[red]##Error: Name b6 is not in scope##
[red]##Error: Name gap is not in scope##

displayed in a 400x50 area gives: image::Libraries/Vis/Figure/Figures/hvcat/h1.png[alt="h1"]

However, the same example

[red]##java.lang.NullPointerException##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name size is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name size is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name size is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name size is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name size is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name size is not in scope##
rascal>render(hvcat([b1, b2, b3, b4, b5, b6], gap(5)));
[red]##Error: Name hvcat is not in scope##
[red]##Error: Name renderSave is not in scope##
[red]##Error: Name b4 is not in scope##
[red]##Error: Name b3 is not in scope##
[red]##Error: Name b2 is not in scope##
[red]##Error: Name b1 is not in scope##
[red]##Error: Name b5 is not in scope##
[red]##Error: Name b6 is not in scope##
[red]##Error: Name gap is not in scope##

displayed in a 100x120 area gives: image::Libraries/Vis/Figure/Figures/hvcat/h2.png[alt="h2"]

The alignment of the rows can be set using [justify] and [ialign].

outline
Synopsis

Outline to summarize file related information.

Function

Figure outline(list[LineDecoration] lineInfo, int maxLine, FProperty props…​)

Description

An outline is a rectangle with colored horizontal lines and is primarily used to summarize information related to a source file. Colored lines indicate different findings in the file. Dimensions are determined by the [width] and [height] properties. lineInfo is a list of LineDecorations that associate information, warnings, errors or highlights with a specific line. This information is also used by source editors.

Examples
[red]##Error: Name size is not in scope##
[red]##Error: Name outline is not in scope##
[red]##Error: Name render is not in scope##
[red]##Error: Name info is not in scope##
[red]##Error: Name highlight is not in scope##
[red]##Error: Name warning is not in scope##
outline 1
Benefits

In combination with [pack] or [hvcat] information amount large amounts of files can be summarized densely.

overlay
Synopsis

Composition of figures by superposition.

Function

Figure overlay(Figures figs, FProperty props…​)

Description

Composition of a list of figures by overlaying them on top of each other. Alignment gives detailed control over the position of figures in an overlay. This can be used to create arbitrary shapes. These shapes can be further controlled by

  • connecting the figures in the overlay, see [shapeConnected].

  • make a smooth connection between figures in the overlay, see [shapeCurved].

  • connecting the first and the last figure in the shape, see [shapeClosed].

  • using [fillColor] to define the area color of the closed shape.

  • using [hconnect] or [vconnect] to determine where the figures in a shape will be connected.

Examples
[red]##java.lang.NullPointerException##
[red]##Error: Name shrink is not in scope##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name box is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name shrink is not in scope##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name box is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name shrink is not in scope##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name box is not in scope##
rascal>render(overlay([b1, b2, b3]));
[red]##Error: Name b3 is not in scope##
[red]##Error: Name b2 is not in scope##
[red]##Error: Name b1 is not in scope##
[red]##Error: Name renderSave is not in scope##
[red]##Error: Name overlay is not in scope##

gives: image::Libraries/Vis/Figure/Figures/overlay/o1.png[alt="o1"]

[red]##java.lang.NullPointerException##
[red]##Error: Name shrink is not in scope##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name box is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name right is not in scope##
[red]##Error: Name shrink is not in scope##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name top is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name shrink is not in scope##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name box is not in scope##
rascal>render(overlay([b1, b2, b3]));
[red]##Error: Name b3 is not in scope##
[red]##Error: Name b2 is not in scope##
[red]##Error: Name b1 is not in scope##
[red]##Error: Name renderSave is not in scope##
[red]##Error: Name overlay is not in scope##

gives: image::Libraries/Vis/Figure/Figures/overlay/o2.png[alt="o2"]

[red]##java.lang.NullPointerException##
[red]##Error: Name shrink is not in scope##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name box is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name shrink is not in scope##
[red]##Error: Name left is not in scope##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name bottom is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name shrink is not in scope##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name box is not in scope##
rascal>render(overlay([b1, b2, b3]));
[red]##Error: Name b3 is not in scope##
[red]##Error: Name b2 is not in scope##
[red]##Error: Name b1 is not in scope##
[red]##Error: Name renderSave is not in scope##
[red]##Error: Name overlay is not in scope##

gives: image::Libraries/Vis/Figure/Figures/overlay/o3.png[alt="o3"]

[red]##java.lang.NullPointerException##
[red]##Error: Name shrink is not in scope##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name box is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name shrink is not in scope##
[red]##Error: Name left is not in scope##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name bottom is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name right is not in scope##
[red]##Error: Name shrink is not in scope##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name box is not in scope##
rascal>render(overlay([b1, b2, b3]));
[red]##Error: Name b3 is not in scope##
[red]##Error: Name b2 is not in scope##
[red]##Error: Name b1 is not in scope##
[red]##Error: Name renderSave is not in scope##
[red]##Error: Name overlay is not in scope##

gives: image::Libraries/Vis/Figure/Figures/overlay/o4.png[alt="o4"]

Alignment gives detailed control over the position of figures in an overlay.

[red]##Error: Name shrink is not in scope##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name align is not in scope##
[red]##Error: Name ellipse is not in scope##
lrel[real,real]: [
  <0.0,0.0>,
  <0.5,0.5>,
  <0.8,0.5>,
  <1.0,0.0>
]
[red]##java.lang.NullPointerException##
[red]##Error: Name point is not in scope##
[red]##Error: Name overlay is not in scope##
rascal>render(ovl);
[red]##Error: Name renderSave is not in scope##
[red]##Error: Name ovl is not in scope##

gives:

o5

The overlaid figures can be connected by using [shapeConnected]:

[red]##Error: Name shrink is not in scope##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name align is not in scope##
[red]##Error: Name ellipse is not in scope##
lrel[real,real]: [
  <0.0,0.0>,
  <0.5,0.5>,
  <0.8,0.5>,
  <1.0,0.0>
]
[red]##java.lang.NullPointerException##
[red]##Error: Name overlay is not in scope##
[red]##Error: Name shapeConnected is not in scope##
[red]##Error: Name point is not in scope##
rascal>render(ovl);
[red]##Error: Name ovl is not in scope##
[red]##Error: Name renderSave is not in scope##

gives:

o6

The next enhancement is to close the begin and end points of the shape, using [shapeClosed]:

[red]##Error: Name shrink is not in scope##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name align is not in scope##
[red]##Error: Name ellipse is not in scope##
lrel[real,real]: [
  <0.0,0.0>,
  <0.5,0.5>,
  <0.8,0.5>,
  <1.0,0.0>
]
[red]##Parse error##
[red]##Parse error##
rascal>render(ovl);
[red]##Error: Name renderSave is not in scope##
[red]##Error: Name ovl is not in scope##

gives:

o7

Another enhancement is to use curves to connect the figures in the shape, using [shapeCurved]:

[red]##Error: Name shrink is not in scope##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name align is not in scope##
[red]##Error: Name ellipse is not in scope##
lrel[real,real]: [
  <0.0,0.0>,
  <0.5,0.5>,
  <0.8,0.5>,
  <1.0,0.0>
]
[red]##Parse error##
[red]##Parse error##
[red]##Parse error##
rascal>render(ovl);
[red]##Error: Name renderSave is not in scope##
[red]##Error: Name ovl is not in scope##

gives:

o8

A final enhancement is to set the fill color of the closed shape:

[red]##Error: Name shrink is not in scope##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name align is not in scope##
[red]##Error: Name ellipse is not in scope##
lrel[real,real]: [
  <0.0,0.0>,
  <0.5,0.5>,
  <0.8,0.5>,
  <1.0,0.0>
]
[red]##Parse error##
[red]##Parse error##
[red]##Parse error##
[red]##Parse error##
rascal>render(ovl);
[red]##Error: Name renderSave is not in scope##
[red]##Error: Name ovl is not in scope##

gives:

o9

The [hconnect] and [vconnect] properties can be used to determine where a shape will connect with a figure.

[red]##java.lang.NullPointerException##
[red]##Error: Name left is not in scope##
[red]##Error: Name hconnect is not in scope##
[red]##Error: Name vconnect is not in scope##
[red]##Error: Name shrink is not in scope##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name top is not in scope##
[red]##Error: Name box is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name resizable is not in scope##
[red]##Error: Name ellipse is not in scope##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name bottom is not in scope##
[red]##Error: Name size is not in scope##
[red]##Error: Name vconnect is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name right is not in scope##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name hconnect is not in scope##
[red]##Error: Name vconnect is not in scope##
[red]##Error: Name top is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name aspectRatio is not in scope##
[red]##Error: Name shrink is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name b2 is not in scope##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name shapeClosed is not in scope##
[red]##Error: Name shapeConnected is not in scope##
[red]##Error: Name b1 is not in scope##
[red]##Error: Name e1 is not in scope##
[red]##Error: Name overlay is not in scope##
rascal>render(ovl);
[red]##Error: Name ovl is not in scope##
[red]##Error: Name renderSave is not in scope##

gives:

o10
pack
Synopsis

Dense packing of a list of figures.

Function

Figure pack(Figures figs, FProperty props…​)

Description

Pack the given figures in arbitrary order to fill space as efficiently as possible. Our bin packing algorithm is inspired by LightMaps.

The size computation is automatic and attempts to obtain a rectangular image close to a square. The gap property is used for the distance between figures.

When the vertical size available is too small, a vertical scrollbar will appear.

Examples
[red]##java.lang.NullPointerException##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name size is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name size is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name size is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name size is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name size is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name size is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name size is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name size is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name size is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name size is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name size is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name size is not in scope##
rascal>render(pack([b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12], std(gap(10))));
[red]##Error: Name gap is not in scope##
[red]##Error: Name renderSave is not in scope##
[red]##Error: Name b4 is not in scope##
[red]##Error: Name b3 is not in scope##
[red]##Error: Name b1 is not in scope##
[red]##Error: Name b8 is not in scope##
[red]##Error: Name b7 is not in scope##
[red]##Error: Name b6 is not in scope##
[red]##Error: Name b5 is not in scope##
[red]##Error: Name std is not in scope##
[red]##Error: Name pack is not in scope##
[red]##Error: Name b12 is not in scope##
[red]##Error: Name b11 is not in scope##
[red]##Error: Name b2 is not in scope##
[red]##Error: Name b9 is not in scope##
[red]##Error: Name b10 is not in scope##

gives (when give a space of 200x200):

p1
rotate
Synopsis

Rotate a figure.

Function

Figure rotate(num angle, Figure fig)

Description

<warning> Currently doesn’t work! </warning>

Rotate figure fig angle degrees around its anchor point.

Also see Angles.

Examples

<xfigure r1.png>

image::{concept}/r1.png[alt="rotate 1"]


<xfigure r2.png>
//b1 = box(size(150,150), fillColor("Blue"));
//b2 = box(size(100,50), fillColor("Red"));
//render(hcat([b1, rotate(45, b2)]));
rotate 1
scale
Synopsis

Scale a figure.

Figure scale(num perc, Figure fig)
Figure scale(num xperc, num yperc, Figure fig)
Description

<warning> Currently doesn’t work! </warning>

Scale figure fig. When only a single percentage perc is given, this applied to the horizontal and vertical dimension.

When percentages xperc and yperc are given they are applied to the horizontal, respectively, vertical dimension.

Examples

<xfigure sc1.png>

image::{concept}/sc1.png[alt="scale 1"]


.Benefits

.Pitfalls
Other properties than dimensions are scaled as well. For instance, lineWidth
is scaled (as can be seen in the above example). When this effect is undesired,
these properties have to be scaled inversely before `scale` is applied.
Reducing `lineWidth` to 0.5 and scaling by 2 given a `lineWidth` of 1:
<xfigure sc2.png>
//b = box(size(100,50), fillColor("Blue"), lineWidth(0.5));
//render(scale(2, b));
scale 2
scaleSlider
Synopsis

Interactive slider.

Function

Figure scaleSlider(int() low, int high(), int () selection, void(int) callback)

Description

Create an interactive slider that can be used to interactively control an integer parameter. The arguments are as follows:

  • low: function to determine lowest value on the scale.

  • high function to determine highest value on the scale.

  • selection: function to determine currently selected value.

  • callback: function called when slider is changed.

Examples

We now use the scaleSlider to interactively control the size of a box. Observe that:

  • the local variable n is used to record the current size of the box.

  • the arguments of scaleSlider use or modify the value of n.

  • the last element in the vertical composition uses computeFigure to compute a new box of size n.

Here are the code and the resulting figure:

[red]##Parse error##
int: 100
[red]##Parse error##
[red]##Parse error##
[red]##Parse error##
[red]##Parse error##
[red]##Parse error##
[red]##Error: Name text is not in scope##
[red]##Parse error##
[red]##Error: Name computeFigure is not in scope##
[red]##Error: Name resizable is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name size is not in scope##
[red]##Parse error##
[red]##Parse error##
rascal>render(scaledbox());
[red]##Error: Name scaledbox is not in scope##
[red]##Error: Name renderSave is not in scope##
s1

Moving the slider will change the size of the box.

Pitfalls

Due to limitations in SWT this does not behave correctly when being placed over or under figures, so do not use them in [overlay] or [mouseOver].

Unfortunately we cannot show an interactive version of the above example here. Try it out in Rascal itself.

scrollable
Synopsis

Embed a figure in a scrollable plane.

Function

Figure scrollable(Figure f, FProperty props …​)

Description

Embeds figure f in a scrollable plane. If the space for the scrollable is too small to show the entire figure f then scrollbars will appear. The minimal size of the scrollable is the minimum size required to show the scrollbars.

Examples
[red]##java.lang.NullPointerException##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name size is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name shrink is not in scope##
[red]##Error: Name scrollable is not in scope##
[red]##Error: Name box1 is not in scope##
rascal>render(box(sb,fillColor("red")));
[red]##Error: Name sb is not in scope##
[red]##Error: Name renderSave is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name fillColor is not in scope##
s1
Pitfalls

When rendering on-screen the figure is always displayed in a scrollable area. Thus using a scrollable as a top level figure makes little sense, as there is no observable difference between render(scrollable(g)) and render(g).

space
Synopsis

An invisible space.

Function

Figure space(Figure inner, FProperty props…​)

Description

A space is an invisible placeholder and acts like an invisible box.

Examples

A space can only be observed indirectly by placing it between two visible figures:

[red]##java.lang.NullPointerException##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name size is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name size is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name space is not in scope##
[red]##Error: Name size is not in scope##
rascal>render(hcat([b1, s1, b2]));
[red]##Error: Name renderSave is not in scope##
[red]##Error: Name b2 is not in scope##
[red]##Error: Name b1 is not in scope##
[red]##Error: Name s1 is not in scope##
[red]##Error: Name hcat is not in scope##
space 1
text
Synopsis

Text.

Function

Figure text(str s, FProperty props…​)

Description

Creates a text string. The following properties are relevant for text:

  • [font]: determines the name of the font to be used. The default font is "Helvetica".

  • [fontSize]: determines the point size (in typographic points) of the font. Default is 12.

  • [fontColor]: determines the color of the font. Default is "Black",

  • [textAngle]: determines the angle (in degrees) at which text is draw (also see [Angles]). Default is 0.

Examples
[red]##Error: Name render is not in scope##
[red]##Error: Name text is not in scope##
text 1
[red]##Error: Name render is not in scope##
[red]##Error: Name fontColor is not in scope##
[red]##Error: Name fontSize is not in scope##
[red]##Error: Name text is not in scope##
text 2
[red]##Error: Name render is not in scope##
[red]##Error: Name grow is not in scope##
[red]##Error: Name fontColor is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name fontSize is not in scope##
[red]##Error: Name text is not in scope##
text 3
[red]##java.lang.NullPointerException##
[red]##Error: Name fontSize is not in scope##
[red]##Error: Name fontColor is not in scope##
[red]##Error: Name text is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name fontSize is not in scope##
[red]##Error: Name fontColor is not in scope##
[red]##Error: Name text is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name fontSize is not in scope##
[red]##Error: Name fontColor is not in scope##
[red]##Error: Name text is not in scope##
rascal>render(box(hcat([t1, t2, t3]), gap(10)));
[red]##Error: Name t3 is not in scope##
[red]##Error: Name renderSave is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name t1 is not in scope##
[red]##Error: Name gap is not in scope##
[red]##Error: Name t2 is not in scope##
[red]##Error: Name hcat is not in scope##
text 4
[red]##Error: Name render is not in scope##
[red]##Error: Name fontColor is not in scope##
[red]##Error: Name textAngle is not in scope##
[red]##Error: Name fontSize is not in scope##
[red]##Error: Name text is not in scope##
text 5
textfield
Synopsis

Interactive text entry field.

Figure textfield(str text, void (str) scallback, FProperty props…​)
Figure textfield(str text, void (str) scallback, bool (str) validate, FProperty props…​)
Description

A textfield in which the user can enter text:

The callback scallback is called whenever the user types ENTER or RETURN in the textfield.
The callback validate is called for every character that the user types. When validate yields false

a visual cue is given that the entered text is erroneous. Only when validate returns true and the user types ENTER or RETURN, scallback will be called.

Examples
[red]##Parse error##
str: ""
[red]##Parse error##
[red]##Error: Name left is not in scope##
[red]##Error: Name text is not in scope##
[red]##Parse error##
[red]##Parse error##
rascal>render(tfield());
[red]##Error: Name renderSave is not in scope##
[red]##Error: Name tfield is not in scope##
t1
Pitfalls

Unfortunately we cannot show an interactive version of the above example here. Try it out in Rascal itself.

Due to limitations in SWT this does not behave correctly when being placed over or under figures, so do not use them in [overlay] or [mouseOver].

tree
Synopsis

Tree layout.

Function

Figure tree(Figure root, Figures children, FProperty props…​)

Description

tree takes a list of nodes and a list of edges and draws a tree.

The [orientation] property can be used to set the drawing direction, [hgap] and [vgap] can be used to set the gaps.

Examples
[red]##Parse error##
[red]##Parse error##
[red]##Error: Name box is not in scope##
[red]##Error: Name fillColor is not in scope##
[red]##Parse error##
[red]##Parse error##
[red]##Parse error##
rascal>render(t1);
[red]##Error: Name t1 is not in scope##
[red]##Error: Name renderSave is not in scope##
tree 1

The standard way of drawing trees is in manhattan-style: all connection between tree nodes are horizontal or vertical. This style is controlled by the [manhattan] property:

[red]##Parse error##
[red]##Parse error##
[red]##Error: Name box is not in scope##
[red]##Error: Name fillColor is not in scope##
[red]##Parse error##
[red]##Parse error##
[red]##Parse error##
rascal>render(t2);
[red]##Error: Name t2 is not in scope##
[red]##Error: Name renderSave is not in scope##
tree 2
[red]##Parse error##
[red]##Parse error##
[red]##Parse error##
[red]##Error: Name ellipse is not in scope##
[red]##Error: Name size is not in scope##
[red]##Error: Name fillColor is not in scope##
[red]##Parse error##
[red]##Parse error##
[red]##Parse error##
[red]##Parse error##
[red]##Parse error##
[red]##Error: Name ellipse is not in scope##
[red]##Error: Name size is not in scope##
[red]##Error: Name fillColor is not in scope##
[red]##Parse error##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name size is not in scope##
[red]##Error: Name box is not in scope##
[red]##Parse error##
[red]##Parse error##
rascal>render(t3);
[red]##Error: Name renderSave is not in scope##
[red]##Error: Name t3 is not in scope##
tree 3
treemap
Synopsis

Treemap layout.

Function

Figure treemap(Figures nodes, FProperty props…​)

Description

Takes a list of nodes and and draws a treemap, see TreeMapping. The nodes can be arbitrary figures and each node should specify its area, through the [area] property. If the treemapping algorithm assigns a size to a figure that is smaller than its minimal size then a box (with the same properties) is drawn instead of the actual figure.

Examples
[red]##Parse error##
[red]##Parse error##
[red]##Parse error##
[red]##Parse error##
[red]##Parse error##
[red]##Error: Name box is not in scope##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name area is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name area is not in scope##
[red]##Error: Name treemap is not in scope##
[red]##Error: Name fillColor is not in scope##
[red]##Parse error##
[red]##Parse error##
rascal>render(t);
[red]##Error: Name renderSave is not in scope##
[red]##Error: Name t is not in scope##
treemap 1
vcat
Synopsis

Vertical composition of figures.

Function

Figure vcat(Figures figs, FProperty props…​)

Description

This is a special case of [grid]. It is a [grid] with just one column. See [grid] for more information.

See also [hcat].

Examples
[red]##java.lang.NullPointerException##
[red]##Error: Name vshrink is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name fillColor is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name box is not in scope##
rascal>render(vcat([b1, b2]));
[red]##Error: Name renderSave is not in scope##
[red]##Error: Name b1 is not in scope##
[red]##Error: Name vcat is not in scope##
[red]##Error: Name b2 is not in scope##

gives: image::Libraries/Vis/Figure/Figures/vcat/v1.png[alt="v1"]

[red]##java.lang.NullPointerException##
[red]##Error: Name box is not in scope##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name hshrink is not in scope##
[red]##Error: Name left is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name hshrink is not in scope##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name box is not in scope##
rascal>render(vcat([b1, b2]));
[red]##Error: Name renderSave is not in scope##
[red]##Error: Name b1 is not in scope##
[red]##Error: Name vcat is not in scope##
[red]##Error: Name b2 is not in scope##

gives: image::Libraries/Vis/Figure/Figures/vcat/v2.png[alt="v2"]

[red]##java.lang.NullPointerException##
[red]##Error: Name right is not in scope##
[red]##Error: Name hshrink is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name fillColor is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name hshrink is not in scope##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name box is not in scope##
rascal>render(vcat([b1, b2]));
[red]##Error: Name renderSave is not in scope##
[red]##Error: Name b1 is not in scope##
[red]##Error: Name vcat is not in scope##
[red]##Error: Name b2 is not in scope##

gives: image::Libraries/Vis/Figure/Figures/vcat/v3.png[alt="v3"]

When several child figures are involved, it is more convenient to change the standard alignment for them using [std].

[red]##java.lang.NullPointerException##
[red]##Error: Name hshrink is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name fillColor is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name hshrink is not in scope##
[red]##Error: Name vshrink is not in scope##
[red]##Error: Name box is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name hshrink is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name fillColor is not in scope##
rascal>render(vcat([b1, b2, b3], std(left()), vgrow(1.1)));
[red]##Error: Name left is not in scope##
[red]##Error: Name renderSave is not in scope##
[red]##Error: Name b3 is not in scope##
[red]##Error: Name std is not in scope##
[red]##Error: Name vcat is not in scope##
[red]##Error: Name b2 is not in scope##
[red]##Error: Name b1 is not in scope##
[red]##Error: Name vgrow is not in scope##

gives: image::Libraries/Vis/Figure/Figures/vcat/v5.png[alt="v5"]

vscreen
Synopsis

Vertical projection screen.

Function

Figure vscreen(Figure fig, FProperty props …​)

Description

Creates a vertical screen on which things can be projected. Works the same as [hscreen].

vscrollable
Synopsis

Embded a figure in a vertically scrollable plane.

Function

Figure vscrollable(Figure f, FProperty props …​)

Description

Embeds figure f in a scrollable plane. The full width of f will always be shown, but if the vertical space for the vscrollable is too small to show the entire figure f then a vertical scrollbar will appear. The minimal width of the vscrollable is the minimal width of the figure f plus the width of a vertical scrollbar and the minimal height is the minimal height required to show a vertical scrollbar (unless the minimal size is specified by [Properties-size]).

Also see [scrollable] and [hscrollable].

Examples
[red]##java.lang.NullPointerException##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name vsize is not in scope##
[red]##Error: Name box is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name shrink is not in scope##
[red]##Error: Name vscrollable is not in scope##
[red]##Error: Name box1 is not in scope##
rascal>render(box(sb,fillColor("red")));
[red]##Error: Name sb is not in scope##
[red]##Error: Name renderSave is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name fillColor is not in scope##
s1
Pitfalls

When rendering on-screen the figure is always displayed in a scrollable area. Thus using a scrollable as a top level figure makes little sense, as there is no observable difference between render(vscrollable(g)) and render(g). In both cases horizontal as well as vertical scrollbars may appear.

2.1.5. InteractionModel

Synopsis

The model used for user-interaction.

Description

The visualizations created with the Figure library can use the following generic primitives for user interaction:

  • Mouse. A figure can define its behaviour in response to mouse interaction:

    • [onMouseEnter]: what to do when the mouse enters the area occupied by the current figure.

    • [onMouseExit]: what to do when the mouse leaves the area occupied by the current figure.

    • [onMouseDown]: what to do when the mouse is pressed when the mouse is in the area occupied by the current figure.

    • [onMouseUp]: what to do when the mouse is released when the mouse is in the area occupied by the current figure.

    • [onMouseMove]: what to do when the mouse moves while it is already in the area occupied by the current figure.

    • [onClick]: what to do when the user clicks on the current figure.

  • Keyboard. A figure can define its behaviour in response to keyboard input:

    • [onKeyDown]: what to do when the user pressed a keyboard key when the mouse if over the current figure.

    • [onKeyUp]: what to do when the user releases a keyboard key when the mouse if over the current figure.

  • Interaction widget. Various interaction widgets are provided:

    • [button]: creates a button that can be pressed.

    • [textfield]: creates an area where text can be entered.

    • [combo]: creates a drop down list from which entries can be selected.

    • [checkbox]: creates an on/off check box.

    • [scaleSlider]: creates a slider to enter a numeric value.

The above interaction primitives all have one or more Rascal functions as argument; they act as callbacks when the interaction primitive is activated by the user.

The following properties further support interaction:

  • [fswitch]: replace the current figure by one from a given (static) list of figures.

  • [computeFigure]: replace the current figure by a dynamically created new figure.

  • [timer]: associate a timer with a figure.

Pitfalls
  • Interactive applications highly depend on dynamically changing property values. They frequently use the possibility to use a function, rather than a value for properties. For instance, instead of using size(10) one may use size(int(){ return n;}, where n is a variable in the scope of the function that created the figure.

  • Unfortunately we cannot show an interactive version of the above example here. Try it out in Rascal itself.

2.1.6. KeyModifier

Synopsis

The KeyModifier datatype describes key modifiers in user-interactions.

Types
data KeyModifier =
	  modCtrl()
	| modAlt()
	| modShift()
	| modCommand();
Description

Describes key modifiers, the keyboards keys Control, Alt, Shift and Command (Super/Windows/Apple key)

2.1.7. Properties

Synopsis

Overview of all visual properties that apply to figures.

Types
  • FProperty

  • alias FProperties = list[FProperty];

  • alias computedInt = int();

  • alias computedReal = real();

  • alias computedNum = num();

  • alias computedStr = str();

  • alias computedColor = Color();

Description

All figures may have an (optional) list of properties.

A property:

  • is represented by the type FProperty,

  • has a standard value, unless it is explicitly defined for a figure,

  • describes a property of the figure in which it is declared, but

  • the standard value of each property may be redefined for all figures that are contained in a figure.

Several properties have variants that act on one or two dimensions. We call them 2D properties and use the following naming scheme:

  • P(num xy) sets the value for property P in both dimensions to the same value xy.

  • P(num x, num y) sets the value for property P to distinct values x, respectively, y.

  • hP(num x) sets the horizontal value for property P to x.

  • vP(num y) sets the vertical value for property P to y.

The properties width and height are synonyms for hsize, respectively, vsize.

Most properties have typed arguments but they come in several versions:

  • A version with an argument of type int, real, num, str or Color. The values of these arguments are computed when the property is constructed, i.e., when the Figure is constructed.

  • A version with computed argument like computedInt, computedReal, computedNum, computedStr or computedColor. These are functions that return a value. These functions are called during the rendering of the figure to which this property is attached. In this way, properties can be changed.

Properties can be classified as follows:

  • Sizing: [$Properties/size], [hsize], [vsize], [grow], [hgrow], [vgrow], [shrink], [hshrink], [vshrink], [resizable], [hresizable], [vresizable], [lineWidth], [fontSize]

  • Aligning: [align], [halign], [valign], [$Properties/bottom], [$Properties/top], [$Properties/center], [hcenter], [vcenter]

  • Composing: [gap], [hgap], [vgap], [startGap], [hstartGap], [vstartGap], [endGap], [hendGap], [vendGap]

  • Styling: [lineColor], [lineStyle], [fillColor] [font], [fontColor], [shadow], [shadowColor], [shadowPos], [hshadowPos], [vshadowPos].

  • Interacting: [resizable], [onMouseDown],[onMouseUp], [onMouseEnter], [onMouseExit],[mouseOver], [onKeyDown],[onKeyUp].

Most properties use dimensions that are relative to their parent or children. The exceptions are

  • [$Properties/size], [hsize] and [vsize] set a minimal size in pixels.

  • [gap], [hgap] and [vgap] set a minimal gap size in pixels.

If the figure in which these properties occur is not [resizable], then the given absolute values are respected. Otherwise they act as minimal value and may become larger in the resized figure.

Examples

Just a few examples to show the spirit:

  • size(10, 20) sets the size property to 10 (horizontally), respectively 20 (vertically).

  • hsize(10) sets the hsize property to the value 10.

  • hsize(int(){return 10;}) sets the hsize property to the result of executing the argument function int(){return 10;} which is, indeed, not a big deal. This usage becomes more interesting when the argument function returns different values for each call.

  • fillColor("blue") sets the fill color of the current figure.

  • std(fillColor("blue")) sets the standard fill color for the current figure and for all of its children.

See the more detailed description of each property for examples.

The following table specifies which properties have an effect on which figures.

<table> <tr><td>X <td>[box] <td>[button] <td>[checkbox] <td>[combo] <td>computeFigure <td>[ellipse] <td>[fswitch] <td>graph <td>[grid] <td>[hvcat] <td>outline <td>[overlay] <td>[pack]<td>scaleSlider <td>[scrollable] <td>[space] <td>text <td>[textfield] <td>tree <tr><td>[align]2D <td> X <td> X <td> X <td> X <td> X <td> X <td> X <td> <td> X <td> X <td> X <td> X <td> X <td> X <td> X <td> X <td> X <td> X <td> X <tr><td>aspectRatio <td> X <td> X <td> X <td> X <td> X <td> X <td> X <td> <td> X <td> X <td> X <td> X <td> X <td> X <td> X <td> X <td> X <td> X <td> <tr><td>[connect]2D <td> X <td> X <td> X <td> X <td> X <td> X <td> X <td> <td> X <td> X <td> X <td> X <td> X <td> X <td> X <td> X <td> X <td> X <td> X <tr><td>endGap2D <td> <td> <td> <td> <td> <td> <td> <td> <td> X <td> <td> <td> <td> <td> <td> <td> <td> <td> <td> <tr><td>fillColor <td> X <td> X <td> X <td> X <td> <td> X <td> <td> <td> <td> <td> X <td> X <td> <td> X <td> <td> X <td> <td> X <td> <tr><td>[font] <td> <td> X <td> X <td> X <td> <td> <td> <td> <td> <td> <td> <td> <td> <td> X <td> <td> <td> X <td> X <td> <tr><td>[fontBaseline] <td> <td> <td> <td> <td> <td> <td> <td> <td> <td> <td> <td> <td> <td> <td> <td> <td> X <td> <td> <tr><td>fontColor <td> <td> X <td> X <td> X <td> <td> <td> <td> <td> <td> <td> <td> <td> <td> X <td> <td> <td> X <td> X <td> <tr><td>fontBold <td> <td> X <td> X <td> X <td> <td> <td> <td> <td> <td> <td> <td> <td> <td> X <td> <td> <td> X <td> X <td> <tr><td>[fontSize] <td> <td> X <td> X <td> X <td> <td> <td> <td> <td> <td> <td> <td> <td> <td> X <td> <td> <td> X <td> X <td> <tr><td>fontItalic <td> <td> X <td> X <td> X <td> <td> <td> <td> <td> <td> <td> <td> <td> <td> X <td> <td> <td> X <td> X <td> <tr><td>[gap]2D <td> X <td> <td> <td> <td> <td> X <td> <td> X <td> X <td> X <td> <td> <td> X <td> <td> <td> X <td> <td> <td> X <tr><td>[grow]2D <td> X <td> <td> <td> <td> <td> X <td> <td> <td> X <td> <td> <td> <td> <td> <td> <td> X <td> <td> <td> <tr><td>[hint] <td> <td> <td> <td> <td> <td> <td> <td> X <td> <td> <td> <td> <td> <td> <td> <td> <td> <td> <td> <tr><td>[ialign] <td> <td> <td> <td> <td> <td> <td> <td> <td> <td> X <td> <td> <td> <td> <td> <td> <td> X <td> <td> <tr><td>[id] <td> X <td> X <td> X <td> X <td> X <td> X <td> X <td> X <td> X <td> X <td> X <td> X <td> X <td> X <td> X <td> X <td> X <td> X <td> X <tr><td>[justify] <td> <td> <td> <td> <td> <td> <td> <td> <td> <td> X <td> <td> <td> <td> <td> <td> <td> <td> <td> <tr><td>[lineColor] <td> X <td> <td> <td> <td> <td> X <td> <td> X <td> <td> <td> X <td> X <td> <td> <td> <td> X <td> <td> <td> X <tr><td>[lineStyle] <td> X <td> <td> <td> <td> <td> X <td> <td> X <td> <td> <td> X <td> X <td> <td> <td> <td> X <td> <td> <td> X <tr><td>[lineWidth] <td> X <td> <td> <td> <td> <td> X <td> <td> X <td> <td> <td> X <td> X <td> <td> <td> <td> X <td> <td> <td> X <tr><td>[manhattan] <td> <td> <td> <td> <td> <td> <td> <td> <td> <td> <td> <td> <td> <td> <td> <td> <td> <td> <td> X <tr><td>[mouseOver] <td> X <td> <td> <td> <td> X <td> X <td> X <td> <td> X <td> X <td> X <td> X <td> X <td> <td> X <td> X <td> X <td> <td> X <tr><td>[onKeyDown] <td> X <td> <td> <td> <td> X <td> X <td> X <td> <td> X <td> X <td> X <td> X <td> X <td> <td> X <td> X <td> X <td> <td> X <tr><td>[onKeyUp] <td> X <td> <td> <td> <td> X <td> X <td> X <td> <td> X <td> X <td> X <td> X <td> X <td> <td> X <td> X <td> X <td> <td> X <tr><td>[onMouseDown] <td> X <td> <td> <td> <td> X <td> X <td> X <td> <td> X <td> X <td> X <td> X <td> X <td> <td> X <td> X <td> X <td> <td> X <tr><td>[onMouseUp] <td> X <td> <td> <td> <td> X <td> X <td> X <td> <td> X <td> X <td> X <td> X <td> X <td> <td> X <td> X <td> X <td> <td> X <tr><td>[onMouseUp] <td> X <td> <td> <td> <td> X <td> X <td> X <td> <td> X <td> X <td> X <td> X <td> X <td> <td> X <td> X <td> X <td> <td> X <tr><td>[orientation] <td> <td> <td> <td> <td> <td> <td> <td> <td> <td> <td> <td> <td> <td> <td> <td> <td> <td> <td> <tr><td>[resizable]2D <td> X <td> X <td> X <td> X <td> X <td> X <td> X <td> <td> X <td> X <td> X <td> X <td> X <td> X <td> X <td> X <td> X <td> X <td> X <tr><td>[shadow] <td> X <td> <td> <td> <td> <td> X <td> <td> <td> <td> <td> X <td> <td> <td> <td> <td> <td> X <td> <td> <tr><td>[shadowColor] <td> X <td> <td> <td> <td> <td> X <td> <td> <td> <td> <td> X <td> <td> <td> <td> <td> <td> X <td> <td> <tr><td>[shadowPos]2D <td> X <td> <td> <td> <td> <td> X <td> <td> <td> <td> <td> X <td> <td> <td> <td> <td> <td> X <td> <td> <tr><td>[shapeClosed] <td> <td> <td> <td> <td> <td> <td> <td> <td> <td> <td> <td> X <td> <td> <td> <td> <td> <td> <td> <tr><td>[shapeConnected] <td> <td> <td> <td> <td> <td> <td> <td> <td> <td> <td> <td> X <td> <td> <td> <td> <td> <td> <td> <tr><td>[shapeCurved] <td> <td> <td> <td> <td> <td> <td> <td> <td> <td> <td> <td> X <td> <td> <td> <td> <td> <td> <td> <tr><td>[shrink]2D <td> X <td> X <td> X <td> X <td> X <td> X <td> X <td> <td> X <td> X <td> X <td> X <td> X <td> X <td> X <td> X <td> X <td> X <td> X <tr><td>[Properties-size]2D <td> X <td> X <td> X <td> X <td> X <td> X <td> X <td> <td> X <td> X <td> X <td> X <td> X <td> X <td> X <td> X <td> X <td> X <td> X <tr><td>[startGap]2D <td> <td> <td> <td> <td> <td> <td> <td> <td> X <td> <td> <td> <td> <td> <td> <td> <td> <td> <td> <tr><td>[textAngle] <td> <td> <td> <td> <td> <td> <td> <td> <td> <td> <td> <td> <td> <td> <td> <td> <td> X <td> <td> </table>

Benefits
  • Values of properties are defined by an inheritance-like approach: values can be nested and more nested declarations overrule more global ones. Default values can be set locally.

Pitfalls
  • As described above, each argument of a property may be specified in various manners. To avoid clutter, we only show the simplest version, but be aware that all versions are allowed.

  • A figure may inherit an undesired value for a property; the solution is to redeclare that property locally with the desired value.

KeySym
Synopsis

Datatype describing a key on the keyboard.

Types
data KeySym =
  keyPrintable(str key)
| keyAltLeft()
| keyAltRight()
| keyArrowDown()
| keyArrowLeft()
| keyArrowRight()
| keyArrowUp()
| keyBackSpace()
| keyBreak()
| keyCapsLock()
| keyCommandLeft()
| keyCommandRight()
| keyControlLeft()
| keyControlRight()
| keyEnd()
| keyEnter()
| keyEscape()
| keyF1()
| keyF10()
| keyF11()
| keyF12()
| keyF13()
| keyF14()
| keyF15()
| keyF16()
| keyF17()
| keyF18()
| keyF19()
| keyF2()
| keyF20()
| keyF3()
| keyF4()
| keyF5()
| keyF6()
| keyF7()
| keyF8()
| keyF9()
| keyHelp()
| keyHome()
| keyInsert()
| keyKeypad0()
| keyKeypad1()
| keyKeypad2()
| keyKeypad3()
| keyKeypad4()
| keyKeypad5()
| keyKeypad6()
| keyKeypad7()
| keyKeypad8()
| keyKeypad9()
| keyKeypadAdd()
| keyKeypadCr()
| keyKeypadDecimal()
| keyKeypadDivide()
| keyKeypadEqual()
| keyKeypadMultiply()
| keyKeypadSubtract()
| keyNumLock()
| keyPageDown()
| keyPageUp()
| keyPause()
| keyPrintScreen()
| keyScrollLock()
| keyShiftLeft()
| keyShiftRight()
| keyTab()
| keyUnknown(int keyCode);
Description

A datatype describing a key on the keyboard. Any key that is printable is represented by keyPrintable(str key), for example 'a' is described by keyPrintable("a"). Unknown keys are described by keyUnkown(int keyCode) where keyCode is their key code.

align
Synopsis

Alignment of figure relative to parent.

Function

FProperty align(num h, num v)

Description

Defines the horizontal and vertical alignment of a figure relative to its parents. Alignments range from 0 (left, top) to 1 (right, bottom) as follows:

Align

Alignments can be set per dimension by [halign], respectively, [valign].

Note that:

  • align(hv) is equivalent to halign(hv), valign(hv).

  • align(h, v) is equivalent to halign(h), valign(v).

A number of shorthands is provided for common alignment values:

Shorthand

Corresponds to

See

:------------

:------------------

:---------------------

left()

halign(0.0)

[Properties/left]

hcenter()

halign(0.5)

[Properties/hcenter]

right()

halign(1.0)

[Properties/right]

top()

valign(0.0)

[Properties/top]

vcenter()

valign(0.5)

[Properties/vcenter]

bottom()

valign(1.0)

[Properties/bottom]

center()

align(0.5, 0.5)

[Properties/center]

Also see CompositionModel.

Examples
[red]##java.lang.NullPointerException##
[red]##Error: Name shrink is not in scope##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name align is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name b1 is not in scope##
[red]##Error: Name box is not in scope##
rascal>render(b2);
[red]##Error: Name b2 is not in scope##
[red]##Error: Name renderSave is not in scope##
a1
[red]##java.lang.NullPointerException##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name shrink is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name align is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name b1 is not in scope##
[red]##Error: Name box is not in scope##
rascal>render(b2);
[red]##Error: Name b2 is not in scope##
[red]##Error: Name renderSave is not in scope##
a2
area
Synopsis

The desired area for a figure inside a [treemap].

Function

FProperty area(num a)

aspectRatio
Synopsis

The fixed aspect ratio of a figure.

Function

FProperty onClick(void() handler)

Description

Defines the ratio between the horizontal and vertical size of a figure. This ratio is maintained whenever the figure is resized. An aspect ratio with value 1, turns boxes into squares and ellipses into circles.

Examples
[red]##java.lang.NullPointerException##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name ellipse is not in scope##
[red]##Error: Name shrink is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name e1 is not in scope##
[red]##Error: Name box is not in scope##
rascal>render(e1);
[red]##Error: Name renderSave is not in scope##
[red]##Error: Name e1 is not in scope##
a0
[red]##java.lang.NullPointerException##
[red]##Error: Name aspectRatio is not in scope##
[red]##Error: Name ellipse is not in scope##
[red]##Error: Name shrink is not in scope##
[red]##Error: Name fillColor is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name e1 is not in scope##
[red]##Error: Name box is not in scope##
rascal>render(e1);
[red]##Error: Name renderSave is not in scope##
[red]##Error: Name e1 is not in scope##
a1
[red]##java.lang.NullPointerException##
[red]##Error: Name aspectRatio is not in scope##
[red]##Error: Name ellipse is not in scope##
[red]##Error: Name shrink is not in scope##
[red]##Error: Name fillColor is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name e1 is not in scope##
[red]##Error: Name box is not in scope##
rascal>render(e1);
[red]##Error: Name renderSave is not in scope##
[red]##Error: Name e1 is not in scope##
a2
bottom
Synopsis

Bottom alignment.

Function

FProperty bottom()

Description

bottom defines bottom alignment. It sets the vertical alignment to 1.

Note that:

  • bottom() is equivalent to valign(1.0).

center
Synopsis

Centered alignment.

Function

FProperty center()

Description

center defines horizontal and vertical centered alignment. It sets the horizontal and vertical alignment to 0.5.

Note that:

  • center() is equivalent to anchor(0.5, 0.5).

Also see [align] and CompositionModel.

connect
Synopsis

Connection point for figure in an [overlay].

Function

FProperty connect(real h, real v)

Description

Describes where a line connects with this figure. See [hconnect], [vconnect] and [overlay].

endGap
Synopsis

End gap in composition.

Function

FProperty endGap(bool h,bool v)

Description

Specifies if a [hcat] or [grid] will end with (half) a gap. See also endGap,[vendGap] and [hendGap].

fillColor
Synopsis

Fill color.

FProperty fillColor(Color c)
FProperty fillColor(str cname)
Description

Set the color used to fill the inside of figures:

Set the fill color to c.
Set the fill color to the color with name cname.

Also see ColorModel.

Examples
[red]##java.lang.NullPointerException##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name box is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name box is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name box is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name box is not in scope##
[red]##java.lang.NullPointerException##
[red]##Error: Name b4 is not in scope##
[red]##Error: Name b3 is not in scope##
[red]##Error: Name b2 is not in scope##
[red]##Error: Name b1 is not in scope##
rascal>render(hcat(boxes));
[red]##Error: Name boxes is not in scope##
[red]##Error: Name renderSave is not in scope##
[red]##Error: Name hcat is not in scope##

gives:

h1
font
Synopsis

Define font to be used for text.

Function

FProperty font(str fname)

Description

Sets the font to be used for text. See fontNames for a list of available fonts.

Examples
[red]##java.lang.NullPointerException##
[red]##Error: Name fontColor is not in scope##
[red]##Error: Name font is not in scope##
[red]##Error: Name text is not in scope##
rascal>render(t1);
[red]##Error: Name t1 is not in scope##
[red]##Error: Name renderSave is not in scope##
font 1
[red]##java.lang.NullPointerException##
[red]##Error: Name font is not in scope##
[red]##Error: Name text is not in scope##
[red]##Error: Name fontColor is not in scope##
rascal>render(t2);
[red]##Error: Name t2 is not in scope##
[red]##Error: Name renderSave is not in scope##
font 2
fontBold
Synopsis

Define if text should be rendered bold.

Function

FProperty fontBold(bool b)

Description

See also fontItalic.

fontColor
Synopsis

Define the color to be used for text.

FProperty fontColor(Color c)
FProperty fontColor(str cname)
Description

Sets the color to be used for text:

Set font color c.
Set font color with name cname.

Also see ColorModel.

Examples
[red]##java.lang.NullPointerException##
[red]##Error: Name fontColor is not in scope##
[red]##Error: Name text is not in scope##
rascal>render(t1);
[red]##Error: Name t1 is not in scope##
[red]##Error: Name renderSave is not in scope##

gives: image::Libraries/Vis/Figure/Properties/fontColor/t1.png[alt="t1"]

[red]##java.lang.NullPointerException##
[red]##Error: Name fontColor is not in scope##
[red]##Error: Name text is not in scope##
rascal>render(t2);
[red]##Error: Name t2 is not in scope##
[red]##Error: Name renderSave is not in scope##

gives: image::Libraries/Vis/Figure/Properties/fontColor/t2.png[alt="t2"]

fontItalic
Synopsis

Defines if text should be rendered italic.

Function

FProperty fontItalic(bool b)

Description

See also fontBold.

fontNames
Synopsis

The available font names.

Function

list[str] fontNames()

Description

Gives a list of names of available fonts.

Examples
rascal>import vis::Figure;
[red]##Error: Cannot import module vis::Figure##
rascal>fontNames();
[red]##Error: Name fontNames is not in scope##

The available fonts (on the machine on which this page was generated) are <xfigure f1.png>

image::{concept}/f1.png[alt="font names"]


.Benefits

.Pitfalls
The available fonts are system and installation dependent.


:leveloffset: +1

:leveloffset: -1


[[Properties-fontSize]]
# fontSize
:concept: Libraries/Vis/Figure/Properties/fontSize

.Synopsis
Size of the font to be used for text.

.Syntax

.Types

.Function
`FProperty fontSize(int s)`

.Description
Sets the font size (in points) to be used in text.

.Examples
[source,rascal-shell]

java.lang.NullPointerException Error: Name fontSize is not in scope Error: Name text is not in scope rascal>render(t1); Error: Name t1 is not in scope Error: Name renderSave is not in scope

image::{concept}/f1.png[alt="font 1"]


[source,rascal-shell]

java.lang.NullPointerException Error: Name fontSize is not in scope Error: Name text is not in scope rascal>render(t2); Error: Name t2 is not in scope Error: Name renderSave is not in scope

image::{concept}/f2.png[alt="font 2"]


.Benefits

.Pitfalls


:leveloffset: +1

:leveloffset: -1


[[Properties-fromArrow]]
# fromArrow
:concept: Libraries/Vis/Figure/Properties/fromArrow

.Synopsis
Arrow for source of an [edge].

.Syntax

.Types

.Function
FProperty fromArrow(Figure f)

.Description
Add an arrow to the source of a <<Figures-graph>> edge.
The arrow is an arbitrary figure `f` and its upper side will be used as the
point of the arrow. The figure is appropriately rotated depending on the orientation of the edge.

An arrow to the destination of an edge is defined with <<toArrow>>.
An edge may have both a <<fromArrow>> and a <<toArrow>> property.

.Examples
[source,rascal-shell]

Parse error Parse error Parse error Parse error Error: Name fromArrow is not in scope Error: Name edge is not in scope Error: Name size is not in scope Error: Name box is not in scope Parse error rascal>render(graph(nodes, edges, gap(50), std(size(100)))); Error: Name std is not in scope Error: Name nodes is not in scope Error: Name renderSave is not in scope Error: Name size is not in scope Error: Name gap is not in scope Error: Name edges is not in scope Error: Name graph is not in scope

image::{concept}/f1.png[alt="f1"]


.Benefits

.Pitfalls


:leveloffset: +1

:leveloffset: -1


[[Properties-gap]]
# gap
:concept: Libraries/Vis/Figure/Properties/gap

.Synopsis
Define minimal gap between figures in compositions.

.Syntax

.Types

.Function
`FProperty gap(num h, num v)`

.Description
Set the minimal horizontal gap between figures to `h` and the minimal vertical gap to `v`.

Also see <<hgap>> and <<vgap>>.

Note that:

*  `gap(hv)` is equivalent to `gap(hv, hv)` and to `hgap(hv), vgap(hv)`.
*  `gap(h, v)` is equivalent to `hgap(h), vgap(v)`.

.Examples
[source,rascal-shell]

java.lang.NullPointerException Error: Name fillColor is not in scope Error: Name box is not in scope java.lang.NullPointerException Error: Name fillColor is not in scope Error: Name box is not in scope java.lang.NullPointerException Error: Name fillColor is not in scope Error: Name box is not in scope rascal>render(hcat([b1, b2, b2], gap(50))); Error: Name gap is not in scope Error: Name renderSave is not in scope Error: Name b1 is not in scope Error: Name hcat is not in scope Error: Name b2 is not in scope Error: Name b2 is not in scope

image::{concept}/g1.png[alt="g1"]

[source,rascal-shell]

java.lang.NullPointerException Error: Name fillColor is not in scope Error: Name box is not in scope java.lang.NullPointerException Error: Name b1 is not in scope Error: Name fillColor is not in scope Error: Name box is not in scope Error: Name vgap is not in scope Error: Name hgap is not in scope rascal>render(b2); Error: Name b2 is not in scope Error: Name renderSave is not in scope

image::{concept}/g2.png[alt="g2"]


[source,rascal-shell]

java.lang.NullPointerException Error: Name left is not in scope Error: Name fillColor is not in scope Error: Name top is not in scope Error: Name box is not in scope java.lang.NullPointerException Error: Name b1 is not in scope Error: Name fillColor is not in scope Error: Name box is not in scope Error: Name vgap is not in scope Error: Name hgap is not in scope rascal>render(b2); Error: Name b2 is not in scope Error: Name renderSave is not in scope

image::{concept}/g3.png[alt="g3"]


.Benefits

.Pitfalls


:leveloffset: +1

:leveloffset: -1


[[Properties-grow]]
# grow
:concept: Libraries/Vis/Figure/Properties/grow

.Synopsis
Grow (increase) the size of a figure relative to any contained figures.

.Syntax

.Types

.Function
`FProperty grow(num hg, num vg)`

.Description
Grow the current figure relative to any contained figures. Growth is expressed as a factor larger than 1.

Note that:

*  `grow(hvg)` defines the growth in both dimensions and is equivalent to `hgrow(hvg), vgrow(hvg)`.
*   `grow(hg, vg)` defines the growth in both dimensions separately and is equivalent to `hgrow(hg), vgrow(vg)`.


Also see <<hgrow>> and <<vgrow>>.

.Examples
[source,rascal-shell]

java.lang.NullPointerException Error: Name fillColor is not in scope Error: Name box is not in scope Error: Name size is not in scope java.lang.NullPointerException Error: Name fillColor is not in scope Error: Name b1 is not in scope Error: Name grow is not in scope Error: Name box is not in scope rascal>render(b2); Error: Name b2 is not in scope Error: Name renderSave is not in scope

image::{concept}/g1.png[alt="g1"]


.Benefits

.Pitfalls


:leveloffset: +1

:leveloffset: -1


[[Properties-halign]]
# halign
:concept: Libraries/Vis/Figure/Properties/halign

.Synopsis
Horizontal alignment.

.Syntax

.Types

.Function
`FProperty halign(num h)`

.Description
Set the horizontal alignment to `h`.

Also see <<align>> and <<CompositionModel>>.

.Examples
[source,rascal-shell]

java.lang.NullPointerException Error: Name resizable is not in scope Error: Name fillColor is not in scope Error: Name halign is not in scope Error: Name box is not in scope Error: Name size is not in scope java.lang.NullPointerException Error: Name b1 is not in scope Error: Name box is not in scope Error: Name size is not in scope rascal>render(b2); Error: Name b2 is not in scope Error: Name renderSave is not in scope

image::{concept}/a1.png[alt="a1"]


[source,rascal-shell]

java.lang.NullPointerException Error: Name resizable is not in scope Error: Name fillColor is not in scope Error: Name halign is not in scope Error: Name box is not in scope Error: Name size is not in scope java.lang.NullPointerException Error: Name b1 is not in scope Error: Name box is not in scope Error: Name size is not in scope rascal>render(b2); Error: Name b2 is not in scope Error: Name renderSave is not in scope

image::{concept}/a2.png[alt="a2"]


.Benefits

.Pitfalls


:leveloffset: +1

:leveloffset: -1


[[Properties-hcenter]]
# hcenter
:concept: Libraries/Vis/Figure/Properties/hcenter

.Synopsis
Horizontal, centered, alignment.

.Syntax

.Types

.Function
`FProperty hcenter()`

.Description
`hcenter` defines *horizontal centered alignment*.
It sets the horizontal alignment at 0.5.

Note that:

*  `hcenter()` is equivalent to `halign(0.5)`.


Also see <<halign>>, <<align>> and <<CompositionModel>>.

.Examples

.Benefits

.Pitfalls


:leveloffset: +1

:leveloffset: -1


[[Properties-hconnect]]
# hconnect
:concept: Libraries/Vis/Figure/Properties/hconnect

.Synopsis
Define horizontal connection point of figure in an [overlay].

.Syntax


.Types

.Function
`FProperty hconnect(num r)`

.Description
Describes where a line connects with this figure. 0.0 means on the left and 1.0 at the right. See also <<connect>> and <<vconnect>>.

.Examples

.Benefits

.Pitfalls


:leveloffset: +1

:leveloffset: -1


[[Properties-height]]
# height
:concept: Libraries/Vis/Figure/Properties/height

.Synopsis
Define the minimal vertical size.

.Syntax

.Types

.Function
`FProperty height(num h)`

.Description
`height` is a synonym for <<vsize>>.

.Examples

.Benefits

.Pitfalls


:leveloffset: +1

:leveloffset: -1


[[Properties-hendGap]]
# hendGap
:concept: Libraries/Vis/Figure/Properties/hendGap

.Synopsis
Horizontal end gap in compositions.

.Syntax

.Types

.Function
`FProperty hendGap(bool g)`

.Description
Specifies if a <<hcat>> or <<grid>> will end with (half) a horizontal gap. See also <<endGap>> and <<vendGap>>.

.Examples

.Benefits

.Pitfalls


:leveloffset: +1

:leveloffset: -1


[[Properties-hgap]]
# hgap
:concept: Libraries/Vis/Figure/Properties/hgap

.Synopsis
Define minimal horizontal gap in compositions.

.Syntax

.Types

.Function
`FProperty hgap(num h)`

.Description
Set the minimal horizontal gap between figures.
See <<gap>>.

.Examples

.Benefits

.Pitfalls


:leveloffset: +1

:leveloffset: -1


[[Properties-hgrow]]
# hgrow
:concept: Libraries/Vis/Figure/Properties/hgrow

.Synopsis
Increase (grow) the horizontal size of a figure relative to contained figures.

.Syntax

.Types

.Function
`FProperty hgrow(num hg)`

.Description
Defines the horizontal growth of a figure relative to its contained figures.
Growth is expressed as a factor larger than 1.

Also see <<grow>> and <<vgrow>>.

.Examples
[source,rascal-shell]

java.lang.NullPointerException Error: Name fillColor is not in scope Error: Name box is not in scope Error: Name size is not in scope java.lang.NullPointerException Error: Name hgrow is not in scope Error: Name b1 is not in scope Error: Name fillColor is not in scope Error: Name box is not in scope rascal>render(b2); Error: Name b2 is not in scope Error: Name renderSave is not in scope

image::{concept}/g1.png[alt="g1"]


.Benefits

.Pitfalls


:leveloffset: +1

:leveloffset: -1


[[Properties-hint]]
# hint
:concept: Libraries/Vis/Figure/Properties/hint

.Synopsis
Hint at layout algorithm to be used in graphs.

.Syntax

.Types

.Function
`hint(str name)`

.Description
Gives a hint for the layout strategy to be used. Currently implemented hints all apply to the <<Figures-graph>> layout:

*  `spring`: use force-directed spring layout (the default).
*  `layered`: draw as a layered graph.

.Examples

.Benefits

.Pitfalls


:leveloffset: +1

:leveloffset: -1


[[Properties-hresizable]]
# hresizable
:concept: Libraries/Vis/Figure/Properties/hresizable

.Synopsis
Resizable in horizontal direction.

.Syntax

.Types

.Function
`FProperty hresizable(bool hr)`

.Description
Define whether a figure can be resized in the horizontal direction.

Also see: <<resizable>>.

.Examples

.Benefits

.Pitfalls


:leveloffset: +1

:leveloffset: -1


[[Properties-hshadowPos]]
# hshadowPos
:concept: Libraries/Vis/Figure/Properties/hshadowPos

.Synopsis
Horizontal position of shadows.

.Syntax

.Types

.Function
`FProperty hshadowPos(num hs)`

.Description
Set the horizontal shadow position. See <<shadowPos>>.

.Examples

.Benefits

.Pitfalls


:leveloffset: +1

:leveloffset: -1


[[Properties-hshrink]]
# hshrink
:concept: Libraries/Vis/Figure/Properties/hshrink

.Synopsis
Decrease (shrink) the size of a figure relative to its parent.

.Syntax

.Types

.Function
`FProperty hshrink(num hs)`

.Description
Horizontally shrink the current figure relative to the figure it is contained in (its parent).
Shrink is expressed as a factor smaller than 1.

Also see <<shrink>> and <<vshrink>>.

.Examples
[source,rascal-shell]

java.lang.NullPointerException Error: Name hshrink is not in scope Error: Name box is not in scope Error: Name fillColor is not in scope java.lang.NullPointerException Error: Name fillColor is not in scope Error: Name b1 is not in scope Error: Name box is not in scope Error: Name size is not in scope rascal>render(b2); Error: Name b2 is not in scope Error: Name renderSave is not in scope

image::{concept}/s1.png[alt="s1"]


.Benefits

.Pitfalls


:leveloffset: +1

:leveloffset: -1


[[Properties-hsize]]
# hsize
:concept: Libraries/Vis/Figure/Properties/hsize

.Synopsis

Defines the minimal horizontal size.

.Syntax

.Types

.Function
`FProperty hsize(num h)`

.Description
See <<Properties-size>>. A synonym for `hsize` is <<width>>.

.Examples

.Benefits

.Pitfalls


:leveloffset: +1

:leveloffset: -1


[[Properties-hstartGap]]
# hstartGap
:concept: Libraries/Vis/Figure/Properties/hstartGap

.Synopsis
Horizontal gap at start of composition.

.Syntax


.Types

.Function
`FProperty hstartGap(bool h)`

.Description
Specifies if a <<hcat>> or <<grid>> will start with (half) a horizontal gap. See also <<startGap>> and <<vstartGap>>.

.Examples

.Benefits

.Pitfalls


:leveloffset: +1

:leveloffset: -1


[[Properties-ialign]]
# ialign
:concept: Libraries/Vis/Figure/Properties/ialign

.Synopsis
Internal align in [hvcat].

.Syntax
`FProperty ialign(num align)`

.Types

.Function

.Description
Describes the internal alignment used in a <<hvcat>>  (like in a word processor):

*  `ialign(0.0)` means left aligned,
*  `ialign(0.5)` means center aligned, and
*  `ialign(1.0)` means right aligned.


See also <<justify>>.

.Examples

.Benefits

.Pitfalls


:leveloffset: +1

:leveloffset: -1


[[Properties-id]]
# id
:concept: Libraries/Vis/Figure/Properties/id

.Synopsis
Identity.

.Syntax

.Types

.Function
`FProperty id(str name)`

.Description
Assign the identity `name` to the current figure. Identities are used in
various compositions like <<Figures-graph>> and <<treemap>>.

.Examples

.Benefits

.Pitfalls


:leveloffset: +1

:leveloffset: -1


[[Properties-justify]]
# justify
:concept: Libraries/Vis/Figure/Properties/justify

.Synopsis
Justification in [hvcat].

.Syntax


.Types

.Function
`FProperty justify(bool b)`

.Description
If set to `true` then a <<hvcat>> will be rendered "justified". That is instead of aligning the figures in each row to the left or right according to <<ialign>> the horizontal space in each row will be set so that the row fills the complete width. This is the same as the "justified" alignment mode in a word processor.

.Examples

.Benefits

.Pitfalls


:leveloffset: +1

:leveloffset: -1


[[Properties-label]]
# label
:concept: Libraries/Vis/Figure/Properties/label

.Synopsis
A label on an [edge].

.Syntax

.Types

.Function
`FProperty label(Figure f)`

.Description
Adds figure `f` as label to an <<edge>> in a <<Figures-graph>>.

.Examples
[source,rascal-shell]

Parse error Parse error Parse error Parse error Parse error Error: Name text is not in scope Error: Name fillColor is not in scope Error: Name id is not in scope Error: Name box is not in scope Error: Name size is not in scope Parse error Parse error Parse error Parse error Parse error rascal>render(graph(nodes, edges, hint("layered"), gap(100))); Error: Name nodes is not in scope Error: Name renderSave is not in scope Error: Name hint is not in scope Error: Name edges is not in scope Error: Name graph is not in scope Error: Name gap is not in scope

image::{concept}/l1.png[alt="graph 1"]


.Benefits

.Pitfalls

*  Labels are still under development and produce unexpected results (see above).


:leveloffset: +1

:leveloffset: -1


[[Properties-layer]]
# layer
:concept: Libraries/Vis/Figure/Properties/layer

.Synopsis
A layer in a [$Figures/graph].

.Syntax

.Types

.Function
`FProperty layer(str name)`

.Description
Introduces a named layer in a <<Figures-graph>>. All nodes with the same layer name are placed in the same layer.

.Examples
[source,rascal-shell]

Parse error Parse error Parse error Parse error Parse error Error: Name box is not in scope Error: Name fillColor is not in scope Error: Name text is not in scope Error: Name layer is not in scope Error: Name id is not in scope Parse error java.lang.NullPointerException Error: Name edge is not in scope Error: Name edge is not in scope rascal>render(graph(nodes, edges, gap(20), std(size(50)))); Error: Name std is not in scope Error: Name nodes is not in scope Error: Name renderSave is not in scope Error: Name size is not in scope Error: Name gap is not in scope Error: Name edges is not in scope Error: Name graph is not in scope

image::{concept}/l1.png[alt="l1"]


.Benefits

.Pitfalls


:leveloffset: +1

:leveloffset: -1


[[Properties-left]]
# left
:concept: Libraries/Vis/Figure/Properties/left

.Synopsis
Left, horizontal, alignment.

.Syntax

.Types

.Function
`FProperty left()`

.Description
`left` defines *left horizontal alignment*. It sets the horizontal alignment at 1.0.

Note that:

*  `left()` is equivalent to `halign(0.0)`.


Also see <<align>>, <<halign>> and <<CompositionModel>>.

.Examples

.Benefits

.Pitfalls


:leveloffset: +1

:leveloffset: -1


[[Properties-lineColor]]
# lineColor
:concept: Libraries/Vis/Figure/Properties/lineColor

.Synopsis
Defines the line color.

.Syntax

.Types

.Function

#  `FProperty lineColor(Color c)`
#  `FProperty lineColor(str cname)`

.Description
Sets the color of lines and figure boundaries:

#  Set color to `c`.
#  Set color to color with name `cname`.


Also see <<ColorModel>>

.Examples
[source,rascal-shell]

java.lang.NullPointerException Error: Name size is not in scope Error: Name lineColor is not in scope Error: Name box is not in scope java.lang.NullPointerException Error: Name size is not in scope Error: Name lineColor is not in scope Error: Name box is not in scope java.lang.NullPointerException Error: Name size is not in scope Error: Name lineColor is not in scope Error: Name box is not in scope java.lang.NullPointerException Error: Name size is not in scope Error: Name lineColor is not in scope Error: Name box is not in scope java.lang.NullPointerException Error: Name b4 is not in scope Error: Name b3 is not in scope Error: Name b2 is not in scope Error: Name b1 is not in scope rascal>render(hcat(boxes)); Error: Name boxes is not in scope Error: Name renderSave is not in scope Error: Name hcat is not in scope

gives:

image::{concept}/lc1.png[alt="h1"]


.Benefits

.Pitfalls


:leveloffset: +1

:leveloffset: -1


[[Properties-lineStyle]]
# lineStyle
:concept: Libraries/Vis/Figure/Properties/lineStyle

.Synopsis

Sets the style of lines and borders of figures.

.Syntax

.Types

.Function
`FProperty lineStyle(str style)`

.Description
The following line styles are available:

*  `"solid"` (default)
*  `"dash"`
*  `"dot"`
*  `"dashdot"`
*  `"dashdotdot"`

.Examples
[source,rascal-shell]

java.lang.NullPointerException Error: Name lineStyle is not in scope Error: Name box is not in scope Error: Name size is not in scope rascal>render(b1); Error: Name b1 is not in scope Error: Name renderSave is not in scope

gives
image::{concept}/box1.png[alt="box1"]


[source,rascal-shell]

java.lang.NullPointerException Error: Name lineStyle is not in scope Error: Name box is not in scope Error: Name size is not in scope rascal>render(b2); Error: Name b2 is not in scope Error: Name renderSave is not in scope

gives
image::{concept}/box2.png[alt="box2"]


[source,rascal-shell]

java.lang.NullPointerException Error: Name lineStyle is not in scope Error: Name box is not in scope Error: Name size is not in scope rascal>render(b3); Error: Name b3 is not in scope Error: Name renderSave is not in scope

gives
image::{concept}/box3.png[alt="box3"]


[source,rascal-shell]

java.lang.NullPointerException Error: Name lineStyle is not in scope Error: Name box is not in scope Error: Name size is not in scope rascal>render(b4); Error: Name b4 is not in scope Error: Name renderSave is not in scope

gives
image::{concept}/box4.png[alt="box4"]


.Benefits

.Pitfalls


:leveloffset: +1

:leveloffset: -1


[[Properties-lineWidth]]
# lineWidth
:concept: Libraries/Vis/Figure/Properties/lineWidth

.Synopsis
Defines the width of lines.

.Syntax

.Types

.Function
`FProperty lineWidth(num w)`

.Description
Set the width of lines and borders of figures to `w`.

.Examples
[source,rascal-shell]

java.lang.NullPointerException Error: Name lineWidth is not in scope Error: Name box is not in scope java.lang.NullPointerException Error: Name lineWidth is not in scope Error: Name box is not in scope java.lang.NullPointerException Error: Name lineWidth is not in scope Error: Name box is not in scope java.lang.NullPointerException Error: Name lineWidth is not in scope Error: Name box is not in scope java.lang.NullPointerException Error: Name b4 is not in scope Error: Name b3 is not in scope Error: Name b2 is not in scope Error: Name b1 is not in scope rascal>render(hcat(boxes,hgrow(1.2))); Error: Name boxes is not in scope Error: Name renderSave is not in scope Error: Name hgrow is not in scope Error: Name hcat is not in scope

gives:

image::{concept}/lw1.png[alt="h1"]


.Benefits

.Pitfalls


:leveloffset: +1

:leveloffset: -1


[[Properties-manhattan]]
# manhattan
:concept: Libraries/Vis/Figure/Properties/manhattan

.Synopsis
Define the drawing style of [$Figures/tree]s.

.Syntax

.Types

.Function
`FProperty manhattan(bool b)`

.Description
Determine drawing style for <<Figures-tree>>s:

*  When true, all connections are drawn horizontally and vertically.
*  When false, all connections are drawn diagonally.

.Examples
[source,rascal-shell]

Parse error Parse error Error: Name box is not in scope Error: Name fillColor is not in scope Parse error Parse error Parse error rascal>render(t1); Error: Name t1 is not in scope Error: Name renderSave is not in scope

image::{concept}/t1.png[alt="tree 1"]



[source,rascal-shell]

Parse error Parse error Error: Name box is not in scope Error: Name fillColor is not in scope Parse error Parse error Parse error rascal>render(t2); Error: Name t2 is not in scope Error: Name renderSave is not in scope

image::{concept}/t2.png[alt="tree 2"]


.Benefits

.Pitfalls


:leveloffset: +1

:leveloffset: -1


[[Properties-mouseOver]]
# mouseOver
:concept: Libraries/Vis/Figure/Properties/mouseOver

.Synopsis
Define interactive mouse over behaviour.

.Syntax

.Types

.Function
`FProperty mouseOver(Figure fig)`

.Description
Show figure `fig` when the mouse hovers over the current figure.

.Examples
[source,rascal-shell]

Parse error java.lang.NullPointerException Error: Name nr is not in scope Error: Name stairs is not in scope Error: Name nr is not in scope Error: Name mouseOver is not in scope Parse error Parse error Parse error Parse error rascal>render(box(stairs(10),grow(1.2),bottom(),center())); Error: Name renderSave is not in scope Error: Name box is not in scope Error: Name center is not in scope Error: Name bottom is not in scope Error: Name stairs is not in scope Error: Name grow is not in scope

image::{concept}/onkeydown.png[alt="onkeydown"]


.Benefits

.Pitfalls
Unfortunately we cannot show an interactive version here. Try it out in Rascal yourself.


:leveloffset: +1

:leveloffset: -1


[[Properties-onClick]]
# onClick
:concept: Libraries/Vis/Figure/Properties/onClick

.Synopsis
Old name for [onMouseDown]. (__deprecated__)

.Syntax

.Types

.Function

.Description

.Examples

.Benefits

.Pitfalls


:leveloffset: +1

:leveloffset: -1


[[Properties-onKeyDown]]
# onKeyDown
:concept: Libraries/Vis/Figure/Properties/onKeyDown

.Synopsis

Define interactive behaviour when a key is pressed.

.Syntax

.Types

.Function
FProperty onKeyDown (bool (KeySym key, map[KeyModifier,bool] modifiers) cb)

.Description
This property allows you to install a handler for key presses. When the mouse is over the figure (i.e. the figure has focus) and a key is pressed then the callback `cb` will be called. This callback takes two arguments

*  `KeySym key` the key that is pressed, described by a [KeySym].
*  `map[KeyModifier,bool]` a map that indicates which modifier keys (Control, Alt, Super) are currently held down. Modifier keys are described by [KeyModifier].

The callback returns a `bool` which indicates if the event is captured. Keyhandlers are executed deepest-figure first, if the key press is captured then the key press is not propagated further so figures below (less deep) than this figure will not receive a key press.

.Examples
[source,rascal-shell]

Error: Cannot import module vis::KeySym str: "" str: "" Parse error Parse error Parse error Error: Name key is not in scope bool: true Parse error Parse error Parse error Parse error Parse error Parse error Error: Name key is not in scope bool: true Parse error rascal>render(b2); Error: Name renderSave is not in scope Error: Name b2 is not in scope

image::{concept}/onkeydown.png[alt="onkeydown"]


.Benefits

.Pitfalls
Unfortunately we cannot show an interactive version here, try it out in Rascal yourself.


:leveloffset: +1

:leveloffset: -1


[[Properties-onKeyUp]]
# onKeyUp
:concept: Libraries/Vis/Figure/Properties/onKeyUp

.Synopsis
Define interactive behaviour when key is released.

.Syntax


.Types

.Function
`onKeyUp (bool (KeySym, map[KeyModifier,bool]))`

.Description
Execute callback when key is released. Works the same as <<onKeyDown>>.

.Examples

.Benefits

.Pitfalls


:leveloffset: +1

:leveloffset: -1


[[Properties-onMouseDown]]
# onMouseDown
:concept: Libraries/Vis/Figure/Properties/onMouseDown

.Synopsis

Define interactive behaviour when mouse is pressed while mouse is over figure.

.Syntax

.Types

.Function
`FProperty onMouseDown(bool (int, map[KeyModifier,bool]) cb)`

.Description
`onMouseDown` has a single argument: a callback `cb` that gets two arguments:

*  an `int` indicating the mouse button, 1 indicates left mouse button, 2 the middle and 3 the right. Higher numbers are used for mice with more buttons.
* an `map[KeyModifier,bool]` indicating which keyboard modifiers are currently pressed. See [KeyModifier].


The callback returns a `bool` which indicates if the event is captured. Mouse handlers are executed deepest-figure first, if the mouse press is captured then the mouse press is not propagated further so figures below (less deep than) this figure will not receive a mouse press.

.Examples
[source,rascal-shell]

Error: Cannot import module vis::KeySym str: "" str: "" Parse error Parse error Parse error Error: Name butnr is not in scope bool: true Parse error Parse error Parse error Parse error Parse error Parse error Error: Name butnr is not in scope bool: true Parse error rascal>render(b2); Error: Name renderSave is not in scope Error: Name b2 is not in scope

image::{concept}/onmousedown.png[alt="onmousedown"]


.Benefits

.Pitfalls


:leveloffset: +1

:leveloffset: -1


[[Properties-onMouseEnter]]
# onMouseEnter
:concept: Libraries/Vis/Figure/Properties/onMouseEnter

.Synopsis

Define interactive behaviour when the mouse pointer enters the figure.

.Syntax

.Types

.Function
`FProperty onMouseEnter(void () cb)`

.Description
Execute callback `cb` when the mouse pointer enters the figure. See also <<onMouseExit>>.

.Examples
[source,rascal-shell]

bool: false Parse error Parse error Parse error rascal>render(b); Error: Name b is not in scope Error: Name renderSave is not in scope

image::{concept}/mouseenter.png[alt="mouseenter"]


.Benefits

.Pitfalls
Unfortunately we cannot show an interactive version here, try it out in Rascal yourself.


:leveloffset: +1

:leveloffset: -1


[[Properties-onMouseExit]]
# onMouseExit
:concept: Libraries/Vis/Figure/Properties/onMouseExit

.Synopsis
Define interactive behaviour when the mouse pointer leaves the figure.

.Syntax

.Types

.Function
`FProperty onMouseExit(void () cb)`

.Description
Execute callback `cb` when the mouse pointer exits the figure. See also <<onMouseEnter>>.

.Examples

.Benefits

.Pitfalls


:leveloffset: +1

:leveloffset: -1


[[Properties-onMouseMove]]
# onMouseMove
:concept: Libraries/Vis/Figure/Properties/onMouseMove

.Synopsis
Define interactive behaviour when the mouse moves over this figure.

.Syntax

.Types

.Function
`FProperty onMouseMove(void (bool) handler)`

.Description
Execute `handler` when the mouse moves over the current figure.

.Examples

.Benefits

.Pitfalls


:leveloffset: +1

:leveloffset: -1


[[Properties-onMouseUp]]
# onMouseUp
:concept: Libraries/Vis/Figure/Properties/onMouseUp

.Synopsis
Define interactive behaviour when the mouse button is released.

.Syntax

.Types

.Function
`FProperty onMouseUp  (bool (int,map[KeyModifier,bool]) cb )

.Description
Execute callback `cb` when a mouse button is released. Works the same as <<onMouseDown>>.

.Examples

.Benefits

.Pitfalls


:leveloffset: +1

:leveloffset: -1


[[Properties-orientation]]
# orientation
:concept: Libraries/Vis/Figure/Properties/orientation

.Synopsis
Define the orientation of a [$Figures/tree] or [$Figures/graph].

.Syntax

.Types

[source,rascal]

data Orientation = leftRight() | rightLeft() | topDown() | downTop();

.Function
`FProperty orientation(Orientation o)`

.Description
Describes the orientation of a <<Figures-graph>> or a <<Figures-tree>>. Possible values are described by
the datatype `orientation`.

.Examples

.Benefits

.Pitfalls


:leveloffset: +1

:leveloffset: -1


[[Properties-project]]
# project
:concept: Libraries/Vis/Figure/Properties/project

.Synopsis
Project figure on a [hscreen] or [vscreen].

.Syntax

.Types

.Function
`FProperty project (Figure f0, str p0)`

.Description
Project figure `f0` from this figure onto the screen with <<id>> `p0`. See <<hscreen>> and <<vscreen>>

.Examples

.Benefits

.Pitfalls


:leveloffset: +1

:leveloffset: -1


[[Properties-resizable]]
# resizable
:concept: Libraries/Vis/Figure/Properties/resizable

.Synopsis
Define whether figure can be resized.

.Syntax

.Types

.Function
`FProperty resizable(bool hr, bool vr)`

.Description
Determine whether a figure can be resized in the horizontal or the vertical dimension, or in both directions.
Figures can have a minimal size beyond which they cannot be further reduced in size.
By default, figures are resizable and will occupy all available space.

Noet that:

*  `resizable(r)` is equivalent to `hresizable(r), vresizable(r)`.
*  `resizable(hr, vr)` is equivalent to `hresizable(hr), vresizable(vr)`.

.Examples

.Benefits

.Pitfalls


:leveloffset: +1

:leveloffset: -1


[[Properties-right]]
# right
:concept: Libraries/Vis/Figure/Properties/right

.Synopsis
Right, horizontal, alignment.

.Syntax

.Types

.Function
`FProperty right()`

.Description
`right` defines *right horizontal alignment*.
It sets horizontal alignment to 1.0.

Note that

*  `right()` is equivalent to `halign(1.0)`.


Also see <<align>>, <<halign>> and <<CompositionModel>>.

.Examples

.Benefits

.Pitfalls


:leveloffset: +1

:leveloffset: -1


[[Properties-shadow]]
# shadow
:concept: Libraries/Vis/Figure/Properties/shadow

.Synopsis
Add a shadow to the current figure.

.Syntax

.Types

.Function
`Fproperty shadow(bool b)`

.Description
Defines whether a figure will have a shadow or not.
The color of the shadow is determined by <<shadowColor>>.
The position of the shadow is determined by <<shadowPos>>.

.Examples
[source,rascal-shell]

java.lang.NullPointerException Error: Name shadow is not in scope Error: Name box is not in scope Error: Name size is not in scope Error: Name resizable is not in scope rascal>render(box1); Error: Name renderSave is not in scope Error: Name box1 is not in scope

image::{concept}/s1.png[alt="s1"]


.Benefits

.Pitfalls


:leveloffset: +1

:leveloffset: -1


[[Properties-shadowColor]]
# shadowColor
:concept: Libraries/Vis/Figure/Properties/shadowColor

.Synopsis
Define the color of a [shadow].

.Syntax

.Types

.Function

*  `FProperty shadowColor(Color c)`
*  `FProperty shadowColor(str colorName)`

.Description
Defines the color of shadows. Also see <<shadow>> and <<shadowPos>>.

.Examples
[source,rascal-shell]

java.lang.NullPointerException Error: Name resizable is not in scope Error: Name shadow is not in scope Error: Name box is not in scope Error: Name size is not in scope Error: Name shadowColor is not in scope rascal>render(box1); Error: Name renderSave is not in scope Error: Name box1 is not in scope

image::{concept}/s1.png[alt="s1"]


.Benefits

.Pitfalls


:leveloffset: +1

:leveloffset: -1


[[Properties-shadowPos]]
# shadowPos
:concept: Libraries/Vis/Figure/Properties/shadowPos

.Synopsis
Define the position of a [shadow].

.Syntax

.Types

.Function

.Description
Determines the positions of shadows. The shadow position can also be set for separate dimensions by hshadowPos and vshadowPos.

Note that:

*  `shadowPos(n)` is equivalent to `shadowPos(n, n)`.
*  `shadowPos(hs, vs)` is equivalent to `hshadowPos(hs), vshadowPos(vs)`.


Also see <<shadow>> and <<shadowColor>>.

.Examples
[source,rascal-shell]

java.lang.NullPointerException Error: Name shadowPos is not in scope Error: Name shrink is not in scope Error: Name box is not in scope Error: Name shadow is not in scope rascal>render(space(box1)); Error: Name box1 is not in scope Error: Name space is not in scope Error: Name renderSave is not in scope

image::{concept}/s1.png[alt="s1"]


.Benefits

.Pitfalls
Shadow is not taken into account for size computation


:leveloffset: +1

:leveloffset: -1


[[Properties-shapeClosed]]
# shapeClosed
:concept: Libraries/Vis/Figure/Properties/shapeClosed

.Synopsis
Connect first and last point of a shape in an [overlay].

.Syntax

.Types

.Function
`FProperty shapeClosed(bool b)`

.Description
When `b` is true, connect the first and the last figure in a shape created by <<shapeConnected>>.
Also see <<overlay>> and <<shapeCurved>>.

.Examples
See <<overlay>> for examples.

.Benefits

.Pitfalls


:leveloffset: +1

:leveloffset: -1


[[Properties-shapeConnected]]
# shapeConnected
:concept: Libraries/Vis/Figure/Properties/shapeConnected

.Synopsis
Connect the figures in a shape by lines.

.Syntax

.Types

.Function
`FProperty shapeConnected(bool b)`

.Description
When `b` is true, connect the figures in an <<overlay>> to create a shape.
Also see <<shapeClosed>> and <<shapeCurved>>.

.Examples
See <<overlay>> for examples.

.Benefits

.Pitfalls


:leveloffset: +1

:leveloffset: -1


[[Properties-shapeCurved]]
# shapeCurved
:concept: Libraries/Vis/Figure/Properties/shapeCurved

.Synopsis
Connect the figures in a shape by curves.

.Syntax

.Types

.Function
`FProperty shapeCurved(bool b)`

.Description
When `b` is true, connect the figures in shape by a curve rather than by a straight line.
A shape is created by connecting the figures in an <<overlay>> by <<shapeConnected>>.

.Examples
See <<overlay>> for examples.

.Benefits

.Pitfalls


:leveloffset: +1

:leveloffset: -1


[[Properties-shrink]]
# shrink
:concept: Libraries/Vis/Figure/Properties/shrink

.Synopsis
Decrease (shrink) the size of a figure relative to its parent.

.Syntax

.Types

.Function
`FProperty shrink(num hg, num vg)`

.Description
Shrink the current figure relative to the figure it is contained in (its parent).
Shrink is expressed as a factor smaller than 1.

Note that:

*  `shrink(hvs)` defines the shrink in both dimensions and is equivalent to `hshrink(hvs), vshrink(hvs)`.
*  `shrink(hs, vs)` defines the shrink in both dimensions separately and is equivalent to `hshrink(hs), vshrink(vs)`.


Also see <<hshrink>> and <<vshrink>>.

.Examples
[source,rascal-shell]

java.lang.NullPointerException Error: Name shrink is not in scope Error: Name fillColor is not in scope Error: Name box is not in scope java.lang.NullPointerException Error: Name fillColor is not in scope Error: Name b1 is not in scope Error: Name box is not in scope Error: Name size is not in scope rascal>render(b2); Error: Name b2 is not in scope Error: Name renderSave is not in scope

image::{concept}/s1.png[alt="s1"]


.Benefits

.Pitfalls


:leveloffset: +1

:leveloffset: -1


[[Properties-size]]
# size
:concept: Libraries/Vis/Figure/Properties/size

.Synopsis
Define the minimal size of a figure.

.Syntax

.Types

.Function
`Fproperty size(num h, num v)`

.Description
Define the *minimal* size of a figure by
setting <<hsize>> to `h` and <<vsize>> to `v`.

Note that:

*  `size(hv)` is equivalent to `hsize(hv), vsize(hv)`.
*  `size(h, v)` is equivalent to `hsize(h), vsize(v)`.
*  [width] is a synonym for [hsize].
*  [height] is a synonym for [vsize].

.Examples
By default, the following box
[source,rascal-shell]

java.lang.NullPointerException Error: Name fillColor is not in scope Error: Name box is not in scope Error: Name size is not in scope rascal>render(b1); Error: Name b1 is not in scope Error: Name renderSave is not in scope

will be displayed with the given minimal sizes:

image::{concept}/box1.png[alt="box1"]



By default all figures are resizable and will occupy all _available_ space as determined by

*  the size of the parent figure.
*  the size of the window in which the figure is displayed.


If we enlarge the window in which `b1` is displayed to, say, 400, 200, we get:
[source,rascal-shell]

java.lang.NullPointerException Error: Name fillColor is not in scope Error: Name box is not in scope Error: Name size is not in scope rascal>render(b1); Error: Name b1 is not in scope Error: Name renderSave is not in scope

image::{concept}/box2.png[alt="box2"]


Resizing can be turned off by setting <<resizable>> to false.

.Benefits

.Pitfalls


:leveloffset: +1

:leveloffset: -1


[[Properties-startGap]]
# startGap
:concept: Libraries/Vis/Figure/Properties/startGap

.Synopsis
Define the gap at the start of a composition.

.Syntax

.Types

.Function
`FProperty startGap(bool h, bool v)`

.Description
Specifies if a <<hcat>>,<<vcat>> or <<grid>> will start with (half) a gap. See also <<hstartGap>> and <<vstartGap>>.

.Examples

.Benefits

.Pitfalls


:leveloffset: +1

:leveloffset: -1


[[Properties-std]]
# std
:concept: Libraries/Vis/Figure/Properties/std

.Synopsis
Define a standard property value for all contained figures.

.Syntax

.Types

.Function
`FProperty std(FProperty prop)`

.Description
Set `prop` as the standard property for all figures contained in the current figure (including the figure itself).

.Examples
In the following, each box controls its own `size` and `lineColor`, but the properties `fillColor`, `lineWidth` and `resizable` are
controlled by a standard setting in `hcat`:

[source,rascal-shell]

Parse error Parse error Error: Name box is not in scope Error: Name lineColor is not in scope Parse error rascal>render(box(hcat(boxes,shrink(0.9)),std(lineColor("blue")), std(fillColor("grey")), std(lineWidth(3)))); Error: Name shrink is not in scope Error: Name fillColor is not in scope Error: Name boxes is not in scope Error: Name renderSave is not in scope Error: Name box is not in scope Error: Name lineColor is not in scope Error: Name lineWidth is not in scope Error: Name hcat is not in scope Error: Name std is not in scope Error: Name std is not in scope Error: Name std is not in scope

image::{concept}/s1.png[alt="s1"]


If a figure does not specify a certain property, then the standard will be used.

.Benefits

.Pitfalls


:leveloffset: +1

:leveloffset: -1


[[Properties-textAngle]]
# textAngle
:concept: Libraries/Vis/Figure/Properties/textAngle

.Synopsis
Define the angle at which text is drawn.

.Syntax

.Types

.Function
`FProperty textAngle(num a)`

.Description
Place text at `a` degrees. The value of the angle may also be computed by a callback `ca`.
Also see <<Angles>>.

.Examples
[source,rascal-shell]

Error: Name textAngle is not in scope Error: Name render is not in scope Error: Name fontSize is not in scope Error: Name text is not in scope

image::{concept}/ta1.png[alt="ta1"]


.Benefits

.Pitfalls


:leveloffset: +1

:leveloffset: -1


[[Properties-timer]]
# timer
:concept: Libraries/Vis/Figure/Properties/timer

.Synopsis

Define interactive, time-dependent, behaviour.

.Syntax

.Types

.Function
`FProperty timer (TimerAction (TimerInfo) ti, void () cbb)`

.Description
This property allows you to execute a callback `cbb` after a specified time, and also allows you to delay, cancel and restart the timer.

At the start and after each event (i.e. other callback) the callback `ti` will be called. This callback should have type `TimerAction (TimerInfo)`. The callback is given a `TimerInfo` structure:
[source,rascal-shell]

rascal>data TimerInfo = stopped(int timeSinceLast) >>>>>>> | running(int timeLeft); ok

This indicates if the timer has stopped and the time since the last execution of the timer (in milliseconds, initially 0) or if the timer is running and the time that is still left till the callback `cbb` will be executed.

The callback `ti` must then return a `TimerAction` which indicates what action it want to undertake:

[source,rascal-shell]

rascal>data TimerAction = restart(int delay) >>>>>>> | stop() >>>>>>> | noChange(); ok

*  `restart(int delay)` indicates that the timer is restarted and that the callback `cbb` will be executed `delay` milliseconds from now. This can also be used to delay the timer.
*  `stop()` indicates that the timer is cancelled.
*  `noChange()` indicates that timer no change to the timer.

.Examples
[source,rascal-shell]

bool: false Parse error bool: true Parse error Parse error Parse error Error: Name restart is not in scope Parse error Error: Name noChange is not in scope Parse error Parse error Parse error Error: Name color is not in scope Error: Name color is not in scope Parse error java.lang.NullPointerException Error: Name getColor is not in scope Error: Name fillColor is not in scope Error: Name ellipse is not in scope Error: Name shrink is not in scope Error: Name timeAction is not in scope Error: Name executeTimer is not in scope Error: Name timer is not in scope rascal>render(e); Error: Name e is not in scope Error: Name renderSave is not in scope

image::{concept}/timer.png[alt="timer"]


.Benefits

.Pitfalls
Unfortunately we cannot show an animated version of the figure above, try it out in rascal yourself.


:leveloffset: +1

:leveloffset: -1


[[Properties-toArrow]]
# toArrow
:concept: Libraries/Vis/Figure/Properties/toArrow

.Synopsis
Add an error to the destination of an [edge].

.Syntax

.Types

.Function
FProperty toArrow(Figure f)

.Description
Add an arrow to the destination of a <<Figures-graph>> edge.
The arrow is an arbitrary figure `f` and its upper side will be used as the
point of the arrow. The figure is appropriately rotated depending on the orientation of the edge.

An arrow to the source of an edge is defined with <<fromArrow>>.
An edge may have both a <<fromArrow>> and a <<toArrow>> property.

.Examples
[source,rascal-shell]

Parse error Parse error Parse error Parse error Error: Name edge is not in scope Error: Name toArrow is not in scope Error: Name size is not in scope Error: Name box is not in scope Parse error rascal>render(graph(nodes, edges, gap(50), std(size(100)))); Error: Name std is not in scope Error: Name nodes is not in scope Error: Name renderSave is not in scope Error: Name size is not in scope Error: Name gap is not in scope Error: Name edges is not in scope Error: Name graph is not in scope

image::{concept}/t1.png[alt="f1"]


.Benefits

.Pitfalls


:leveloffset: +1

:leveloffset: -1


[[Properties-top]]
# top
:concept: Libraries/Vis/Figure/Properties/top

.Synopsis
Top, vertical, alignment.

.Syntax

.Types

.Function
`FProperty top()`

.Description
`top` defines *top vertical alignment*.
It sets the vertical alignment to 0.

Note that

*  `top()` is equivalent to `valign(0.0)`.


Also see <<align>>, <<valign>> and <<CompositionModel>>.

.Examples

.Benefits

.Pitfalls


:leveloffset: +1

:leveloffset: -1


[[Properties-valign]]
# valign
:concept: Libraries/Vis/Figure/Properties/valign

.Synopsis
Vertical alignment.

.Syntax

.Types

.Function
`FProperty valign(num v)`

.Description
Set the vertical alignment to `v`.

Also see <<align>> and <<CompositionModel>>.

.Examples
[source,rascal-shell]

java.lang.NullPointerException Error: Name resizable is not in scope Error: Name fillColor is not in scope Error: Name valign is not in scope Error: Name box is not in scope Error: Name size is not in scope java.lang.NullPointerException Error: Name b1 is not in scope Error: Name box is not in scope Error: Name size is not in scope rascal>render(b2); Error: Name b2 is not in scope Error: Name renderSave is not in scope

image::{concept}/a1.png[alt="a1"]


[source,rascal-shell]

java.lang.NullPointerException Error: Name resizable is not in scope Error: Name fillColor is not in scope Error: Name valign is not in scope Error: Name box is not in scope Error: Name size is not in scope java.lang.NullPointerException Error: Name b1 is not in scope Error: Name box is not in scope Error: Name size is not in scope rascal>render(b2); Error: Name b2 is not in scope Error: Name renderSave is not in scope

image::{concept}/a2.png[alt="a2"]


.Benefits

.Pitfalls


:leveloffset: +1

:leveloffset: -1


[[Properties-vcenter]]
# vcenter
:concept: Libraries/Vis/Figure/Properties/vcenter

.Synopsis
Vertical, centered, alignment.

.Syntax

.Types

.Function
`FProperty vcenter()`

.Description
`vcenter` defines *vertical centered alignment*.
It sets the vertical alignment to 0.5,

Note that:

*  `vcenter()` is equivalent to `valign(0.5)`.


Also see <<valign>>, <<align>> and <<CompositionModel>>.

.Examples

.Benefits

.Pitfalls


:leveloffset: +1

:leveloffset: -1


[[Properties-vconnect]]
# vconnect
:concept: Libraries/Vis/Figure/Properties/vconnect

.Synopsis
Vertical connection point of a figure in an [overlay].

.Syntax


.Types

.Function
`FProperty vconnect(num r)`

.Description
Describes where a line connects with this figure. 0.0 means on the top and 1.0 at the bottom. See also <<connect>> and <<vconnect>>.

.Examples

.Benefits

.Pitfalls


:leveloffset: +1

:leveloffset: -1


[[Properties-vendGap]]
# vendGap
:concept: Libraries/Vis/Figure/Properties/vendGap

.Synopsis
Vertical gap at end of composition.

.Syntax

.Types

.Function
`FProperty vendGap(bool b)`

.Description
Specifies if a <<vcat>> or <<grid>> will start with (half) a vertical gap. See also <<endGap>> and <<hendGap>>.

.Examples

.Benefits

.Pitfalls


:leveloffset: +1

:leveloffset: -1


[[Properties-vgap]]
# vgap
:concept: Libraries/Vis/Figure/Properties/vgap

.Synopsis
Define minimal vertical gap in compositions.

.Syntax

.Types

.Function
`FProperty vgap(num v)`

.Description
Set the minimal vertical gap between figures.
See <<gap>>.

.Examples

.Benefits

.Pitfalls


:leveloffset: +1

:leveloffset: -1


[[Properties-vgrow]]
# vgrow
:concept: Libraries/Vis/Figure/Properties/vgrow

.Synopsis
Increase (grow) the vertical size of a figure relative to its contained figures.

.Syntax

.Types

.Function
`FProperty vgrow(num hg)`

.Description
Defines the vertical growth of a figure relative to its contained figures.
Growth is expressed as a factor larger than 1.

Also see <<grow>> and <<hgrow>>.

.Examples
[source,rascal-shell]

java.lang.NullPointerException Error: Name fillColor is not in scope Error: Name box is not in scope Error: Name size is not in scope java.lang.NullPointerException Error: Name b1 is not in scope Error: Name fillColor is not in scope Error: Name box is not in scope Error: Name vgrow is not in scope rascal>render(b2); Error: Name b2 is not in scope Error: Name renderSave is not in scope

image::{concept}/g1.png[alt="g1"]


.Benefits

.Pitfalls


:leveloffset: +1

:leveloffset: -1


[[Properties-vresizable]]
# vresizable
:concept: Libraries/Vis/Figure/Properties/vresizable

.Synopsis
Define whether figure is resizable in the vertical direction.

.Syntax

.Types

.Function
`FProperty vresizable(bool vr)`

.Description
Define whether a figure can be resized in the vertical direction.

Also see: <<resizable>>.

.Examples

.Benefits

.Pitfalls


:leveloffset: +1

:leveloffset: -1


[[Properties-vshadowPos]]
# vshadowPos
:concept: Libraries/Vis/Figure/Properties/vshadowPos

.Synopsis
Vertical position of [shadow].

.Syntax

.Types

.Function
`FProperty vshadowPos(num vs)`

.Description
Set the vertical position of shadows. See <<shadowPos>>.

.Examples

.Benefits

.Pitfalls


:leveloffset: +1

:leveloffset: -1


[[Properties-vshrink]]
# vshrink
:concept: Libraries/Vis/Figure/Properties/vshrink

.Synopsis
Decrease (shrink) vertical size of figure relative to its parent.

.Syntax

.Types

.Function
`FProperty vshrink(num vs)`

.Description
Vertically shrink the current figure relative to the figure it is contained in (its parent).
Shrink is expressed as a factor smaller than 1.

Also see <<shrink>> and <<hshrink>>.

.Examples
[source,rascal-shell]

java.lang.NullPointerException Error: Name vshrink is not in scope Error: Name box is not in scope Error: Name fillColor is not in scope java.lang.NullPointerException Error: Name b1 is not in scope Error: Name fillColor is not in scope Error: Name box is not in scope rascal>render(b2); Error: Name b2 is not in scope Error: Name renderSave is not in scope

image::{concept}/s1.png[alt="s1"]


.Benefits

.Pitfalls


:leveloffset: +1

:leveloffset: -1


[[Properties-vsize]]
# vsize
:concept: Libraries/Vis/Figure/Properties/vsize

.Synopsis

Define the minimal vertical size.

.Syntax

.Types

.Function
`FProperty vsize(num v)`

.Description
See <<Properties-size>>. A synonym for `vsize` is <<height>>.

.Examples

.Benefits

.Pitfalls


:leveloffset: +1

:leveloffset: -1


[[Properties-vstartGap]]
# vstartGap
:concept: Libraries/Vis/Figure/Properties/vstartGap

.Synopsis
Vertical gap at start of composition.

.Syntax


.Types

.Function
`FProperty vstartGap(bool gap)`

.Description
Specifies if a <<vcat>> or <<grid>> will start with (half) a vertical gap. See also <<startGap>> and <<hstartGap>>.

.Examples

.Benefits

.Pitfalls


:leveloffset: +1

:leveloffset: -1


[[Properties-width]]
# width
:concept: Libraries/Vis/Figure/Properties/width

.Synopsis
Defines the minimal horizontal size.

.Syntax

.Types

.Function
`FProperty width(num w)`

.Description
`width` is a synonym for <<hsize>>.

.Examples

.Benefits

.Pitfalls


:leveloffset: +1

:leveloffset: -1


:leveloffset: -1


:leveloffset: -1


[[Vis-Render]]
# Render
:concept: Libraries/Vis/Render

.Synopsis
Render a figure on screen or save it to a file.


.Syntax
`import vis::Render;`

.Types

.Function

.Description

.Examples

.Benefits

.Pitfalls


:leveloffset: +1

[[Render-render]]
# render
:concept: Libraries/Vis/Render/render

.Synopsis
Render a figure on screen.

.Syntax

.Types

.Function

#  `void render(Figure fig)`
#  `void render(str name, Figure fig)`

.Description
Renders figure `fig` on a canvas. Inside Eclipse a new tabbed pane is created.

When `name` is given, it is shown on the tab of the pane and in the window title.
If a figure tab with `name` already exists, it will be reused.

.Examples

.Benefits

.Pitfalls
Only works inside Eclipse.


:leveloffset: +1

:leveloffset: -1


[[Render-renderSave]]
# renderSave
:concept: Libraries/Vis/Render/renderSave

.Synopsis
Render and save a figure to a file.

.Syntax

.Types

.Function

# `void renderSave(Figure fig, loc file)`
# `void renderSave(Figure fig, int width, int height, loc file)`

.Description
Render figure `fig` and write it to the location `file`.
Currently we only support writing files in png (.png) format.

If no width and height are given the size of the resulting image will be the minimal size required to view the figure.

If a width and height is given then the image will be at least that size. More precisely if the minimum size of the figure is smaller than the given size then the figure will be resized to fit in the given size. If the minimum size of the figure is greater than the given size then the image will be the minimum size required to view the figure.

.Examples

.Benefits

.Pitfalls

*  Only works inside Eclipse.
*  Some figures have a minimal size of 0, for example: `box(ellipse())`. No part of the figure has an inherent minimal size greater than zero.  When using `renderSave` without specifying a size on such figures a image of size 0x0 (the minimal size) will be rendered. The solution is then to specify a width and height.

Figures that do not have minimal size 0 are figures where a part of the figure has an inherent minimal size, such as a text element (the minimal size of the text element is the minimal size required to show it in the given fontSize). For example `box(box(text("jada"),grow(1.2)),grow(1.2))`


:leveloffset: +1

:leveloffset: -1


:leveloffset: -1


[[Vis-TestVis]]
# TestVis
:concept: Libraries/Vis/TestVis

.Synopsis
List of visualization tests (for developers only).

.Syntax

.Types

.Function

.Description


.Examples
[source,rascal-shell]

Error: Name render is not in scope Error: Name box is not in scope

image::{concept}/test1.png[alt="test"]


[source,rascal-shell]

Error: Name render is not in scope Error: Name box is not in scope Error: Name shrink is not in scope

image::{concept}/test2.png[alt="test"]


[source,rascal-shell]

Error: Name box is not in scope Error: Name render is not in scope Error: Name fillColor is not in scope

image::{concept}/test3.png[alt="test"]


[source,rascal-shell]

Error: Name render is not in scope Error: Name lineColor is not in scope Error: Name box is not in scope Error: Name vshrink is not in scope Error: Name hshrink is not in scope Error: Name fillColor is not in scope

image::{concept}/test4.png[alt="test"]


[source,rascal-shell]

Error: Name fillColor is not in scope Error: Name grow is not in scope Error: Name fillColor is not in scope Error: Name render is not in scope Error: Name box is not in scope Error: Name box is not in scope

image::{concept}/test5.png[alt="test"]


/Unsized blue outer box with black inner text
[source,rascal-shell]

Error: Name grow is not in scope Error: Name render is not in scope Error: Name box is not in scope Error: Name fillColor is not in scope Error: Name text is not in scope

image::{concept}/test6.png[alt="test"]


Unsized blue outer box with white inner text

[source,rascal-shell]

Error: Name fontColor is not in scope Error: Name render is not in scope Error: Name box is not in scope Error: Name fillColor is not in scope Error: Name text is not in scope Error: Name grow is not in scope

image::{concept}/test7.png[alt="test"]


[source,rascal-shell]

Error: Name shrink is not in scope Error: Name fillColor is not in scope Error: Name render is not in scope Error: Name grow is not in scope Error: Name box is not in scope Error: Name text is not in scope

image::{concept}/test8.png[alt="test"]


[source,rascal-shell]

Error: Name fillColor is not in scope Error: Name render is not in scope Error: Name lineColor is not in scope Error: Name grow is not in scope Error: Name box is not in scope Error: Name box is not in scope

image::{concept}/test9.png[alt="test"]


[source,rascal-shell]

Error: Name fillColor is not in scope Error: Name render is not in scope Error: Name left is not in scope Error: Name lineColor is not in scope Error: Name grow is not in scope Error: Name box is not in scope Error: Name box is not in scope

image::{concept}/test10.png[alt="test"]


[source,rascal-shell]

Error: Name lineColor is not in scope Error: Name render is not in scope Error: Name left is not in scope Error: Name fillColor is not in scope Error: Name top is not in scope Error: Name resizable is not in scope Error: Name text is not in scope Error: Name box is not in scope Error: Name box is not in scope Error: Name grow is not in scope Error: Name grow is not in scope

image::{concept}/test11.png[alt="test"]


[source,rascal-shell]

Error: Name lineColor is not in scope Error: Name render is not in scope Error: Name left is not in scope Error: Name fillColor is not in scope Error: Name text is not in scope Error: Name box is not in scope Error: Name box is not in scope Error: Name resizable is not in scope Error: Name bottom is not in scope Error: Name grow is not in scope Error: Name grow is not in scope

image::{concept}/test12.png[alt="test"]


[source,rascal-shell]

Error: Name lineColor is not in scope Error: Name right is not in scope Error: Name render is not in scope Error: Name left is not in scope Error: Name fillColor is not in scope Error: Name grow is not in scope Error: Name grow is not in scope Error: Name box is not in scope Error: Name box is not in scope Error: Name text is not in scope Error: Name vresizable is not in scope

image::{concept}/test13.png[alt="test"]



[source,rascal-shell]

Error: Name lineColor is not in scope Error: Name right is not in scope Error: Name render is not in scope Error: Name left is not in scope Error: Name fillColor is not in scope Error: Name top is not in scope Error: Name text is not in scope Error: Name box is not in scope Error: Name box is not in scope Error: Name grow is not in scope Error: Name grow is not in scope

image::{concept}/test14.png[alt="test"]


[source,rascal-shell]

Error: Name lineColor is not in scope Error: Name hresizable is not in scope Error: Name right is not in scope Error: Name render is not in scope Error: Name left is not in scope Error: Name fillColor is not in scope Error: Name width is not in scope Error: Name height is not in scope Error: Name text is not in scope Error: Name grow is not in scope Error: Name grow is not in scope Error: Name box is not in scope Error: Name box is not in scope

image::{concept}/test15.png[alt="test"]


[source,rascal-shell]

Error: Name resizable is not in scope Error: Name lineColor is not in scope Error: Name right is not in scope Error: Name render is not in scope Error: Name left is not in scope Error: Name fillColor is not in scope Error: Name width is not in scope Error: Name height is not in scope Error: Name text is not in scope Error: Name grow is not in scope Error: Name grow is not in scope Error: Name box is not in scope Error: Name box is not in scope

image::{concept}/test16.png[alt="test"]


[source,rascal-shell]

Error: Name resizable is not in scope Error: Name right is not in scope Error: Name size is not in scope Error: Name lineColor is not in scope Error: Name fillColor is not in scope Error: Name render is not in scope Error: Name box is not in scope Error: Name box is not in scope Error: Name grow is not in scope Error: Name bottom is not in scope

image::{concept}/test17.png[alt="test"]


[source,rascal-shell]

java.lang.NullPointerException Error: Name color is not in scope Error: Name fillColor is not in scope Error: Name rgb is not in scope Error: Name box is not in scope Error: Name hcat is not in scope Error: Name lineWidth is not in scope Error: Name rgb is not in scope Error: Name std is not in scope Error: Name box is not in scope Error: Name box is not in scope Error: Name box is not in scope Error: Name fillColor is not in scope Error: Name fillColor is not in scope Error: Name fillColor is not in scope rascal>render(h); Error: Name h is not in scope Error: Name renderSave is not in scope

image::{concept}/test18.png[alt="test"]


[source,rascal-shell]

Parse error Parse error Parse error Parse error Parse error Parse error Error: Name fillColor is not in scope Error: Name box is not in scope Error: Name color is not in scope Parse error rascal>render(h); Error: Name h is not in scope Error: Name renderSave is not in scope

image::{concept}/test19.png[alt="test"]

[source,rascal-shell]

Parse error Parse error Parse error Parse error Parse error Parse error Error: Name box is not in scope Error: Name fillColor is not in scope Error: Name gray is not in scope Parse error rascal>render(h); Error: Name h is not in scope Error: Name renderSave is not in scope

image::{concept}/testabc.png[alt="test"]

[source,rascal-shell]

Parse error Parse error Error: Name shrink is not in scope Error: Name fillColor is not in scope Error: Name top is not in scope Error: Name box is not in scope Parse error Parse error rascal>render(h ); Error: Name h is not in scope Error: Name renderSave is not in scope

image::{concept}/testdef.png[alt="test"]

[source,rascal-shell]

Parse error Parse error Error: Name shrink is not in scope Error: Name fillColor is not in scope Error: Name bottom is not in scope Error: Name box is not in scope Parse error Parse error rascal>render(h); Error: Name h is not in scope Error: Name renderSave is not in scope

image::{concept}/test21.png[alt="test"]


[source,rascal-shell]

Parse error Parse error Error: Name shrink is not in scope Error: Name fillColor is not in scope Error: Name vcenter is not in scope Error: Name box is not in scope Parse error Parse error rascal>render(h); Error: Name h is not in scope Error: Name renderSave is not in scope

image::{concept}/test22.png[alt="test"]

[source,rascal-shell]

Parse error Parse error Parse error Error: Name fillColor is not in scope Error: Name box is not in scope Error: Name size is not in scope Parse error Parse error Parse error Parse error rascal>render(h); Error: Name h is not in scope Error: Name renderSave is not in scope

image::{concept}/test23.png[alt="test"]

[source,rascal-shell]

Parse error Parse error Parse error Error: Name fillColor is not in scope Error: Name box is not in scope Error: Name size is not in scope Parse error Parse error Parse error Parse error Parse error rascal>render(h); Error: Name h is not in scope Error: Name renderSave is not in scope

image::{concept}/test24.png[alt="test"]


[source,rascal-shell]

Parse error Parse error Parse error Error: Name box is not in scope Error: Name size is not in scope Error: Name align is not in scope Error: Name fillColor is not in scope Parse error Parse error Parse error rascal>render(h); Error: Name h is not in scope Error: Name renderSave is not in scope

image::{concept}/test25.png[alt="test"]



[source,rascal-shell]

Parse error Parse error Error: Name fillColor is not in scope Error: Name size is not in scope Error: Name box is not in scope Parse error Parse error Parse error rascal>render(h); Error: Name h is not in scope Error: Name renderSave is not in scope

image::{concept}/test26.png[alt="test"]



[source,rascal-shell]

Parse error Parse error Parse error Error: Name box is not in scope Error: Name size is not in scope Parse error Parse error Error: Name fillColor is not in scope Error: Name size is not in scope Error: Name box is not in scope Parse error Parse error Parse error rascal>render(h); Error: Name h is not in scope Error: Name renderSave is not in scope

image::{concept}/test27.png[alt="test"]



[source,rascal-shell]

Parse error Parse error Error: Name fillColor is not in scope Error: Name size is not in scope Error: Name box is not in scope Parse error Parse error Error: Name fillColor is not in scope Error: Name size is not in scope Error: Name box is not in scope Parse error Parse error Error: Name fillColor is not in scope Error: Name box is not in scope Error: Name size is not in scope Parse error Parse error rascal>render(h); Error: Name h is not in scope Error: Name renderSave is not in scope

image::{concept}/test28.png[alt="test"]




[source,rascal-shell]

Parse error Error: Name shrink is not in scope Error: Name fillColor is not in scope Error: Name box is not in scope Parse error Parse error rascal>render(h); Error: Name h is not in scope Error: Name renderSave is not in scope

image::{concept}/test30.png[alt="test"]


[source,rascal-shell]

Parse error Parse error Parse error Error: Name box is not in scope Error: Name size is not in scope Parse error Parse error Error: Name fillColor is not in scope Error: Name box is not in scope Error: Name size is not in scope Parse error Parse error rascal>render(h); Error: Name h is not in scope Error: Name renderSave is not in scope

image::{concept}/test31.png[alt="test"]


[source,rascal-shell]

Error: Name ellipse is not in scope Error: Name fontColor is not in scope Error: Name render is not in scope Error: Name fillColor is not in scope Error: Name text is not in scope Error: Name grow is not in scope

image::{concept}/test32.png[alt="test"]


.Benefits

.Pitfalls


:leveloffset: +1

:leveloffset: -1


:leveloffset: -1


[[Libraries-analysis]]
# analysis
:concept: Libraries/analysis

.Synopsis
Library functions for analysis tasks.

.Syntax

.Types

.Function

.Usage

.Description


** <<analysis-formalconcepts,FCA>>: Library for Formal Concept Analysis.
** <<analysis-graphs,graphs>>: Analyzing unlabeled and labelled graphs.
*** <<graphs-Graph,Graph>>: A `Graph` datatype with associated functions.
*** <<graphs-LabeledGraph,LabeledGraph>>: Return the bottom nodes of a LGraph.
** <<analysis-m3,m3>>: a language independent meta model for facts about source code, which is extensible to include language specific modeling elements.
** <<analysis-statistics,statistics>>: Statistical functions.
*** <<statistics-Correlation,Correlation>>: Correlation between data values.
*** <<statistics-Descriptive,Descriptive>>: Descriptive Statistics.
*** <<statistics-Frequency,Frequency>>: Frequency distributions.
*** <<statistics-Inference,Inference>>: Statistical inference methods.
*** <<statistics-SimpleRegression,SimpleRegression>>: Statistical methods for simple regression.

.Examples

.Benefits

.Pitfalls


:leveloffset: +1


[[analysis-FCA]]

[[analysis-formalconcepts]]
# FCA
:concept: Libraries/analysis/formalconcepts
.Usage
`import analysis::formalconcepts::FCA;`


.Synopsis
Library for Formal Concept Analysis

.Description

Formal Concept Analysis is a somewhat ubiquitous tool in software analysis projects.
It can be used to find latent groups of objects that share the same attributes in a dataset.
Typically, we apply `FCA` to a relation `rel[&O objects, &A attributes]`, which represents
extracted source code artifacts and their attributes.

[[FCA-FormalContext[&Object, &Attribute]]]
## FormalContext[&Object, &Attribute]
.Types
`rel[&Object, &Attribute]`



[[FCA-Concept[&Object, &Attribute]]]
## Concept[&Object, &Attribute]
.Types
`tuple[set[&Object] objects, set[&Attribute] attributes]`



[[FCA-ConceptLattice[&Object, &Attribute]]]
## ConceptLattice[&Object, &Attribute]
.Types
`rel[Concept[&Object, &Attribute], Concept[&Object, &Attribute]]`



[[FCA-Object2Attributes[&Object, &Attribute]]]
## Object2Attributes[&Object, &Attribute]
.Types
`map[&Object, set[&Attribute]]`



[[FCA-Attribute2Objects[&Attribute, &Object]]]
## Attribute2Objects[&Attribute, &Object]
.Types
`map[&Attribute, set[&Object]]`



[[FCA-fca]]
## fca

.Function
`ConceptLattice[&Object, &Attribute] fca (FormalContext[&Object, &Attribute] fc)`

.Synopsis
Computes Concept Lattice given the Object Attribute Relation.

[[FCA-toDot]]
## toDot

.Function
* `DotGraph toDot(ConceptLattice[&Object, &Attribute] cl)`
* `DotGraph toDot(ConceptLattice[&Object, &Attribute] cl, bool lab)`


.Synopsis
Computes Dot Graph from Concept Lattice.

[[FCA-toDotline]]
## toDotline

.Function
`Dotline toDotline(ConceptLattice[&Object, &Attribute] cl)`



[[FCA-toOutline]]
## toOutline

.Function
`Outline toOutline(ConceptLattice[&Object, &Attribute] cl)`



[[FCA-toFormalContext]]
## toFormalContext

.Function
* `FormalContext[&Object, &Attribute] toFormalContext(Object2Attributes[&Object, &Attribute] objects)`
* `FormalContext[&Object, &Attribute] toFormalContext(Attribute2Objects[&Object, &Attribute] attributes)`




[[FCA-intersection]]
## intersection

.Function
`set[&T] intersection(set[set[&T]] st)`



[[FCA-union]]
## union

.Function
`set[&T] union(set[set[&T]] st)`



[[FCA-isSubset]]
## isSubset

.Function
`bool isSubset(set[set[&T]] candidate, set[&T] s )`



[[FCA-sigma]]
## sigma

.Function
`set[&Attribute] sigma(FormalContext[&Object, &Attribute] fc, set[&Object] objects)`



[[FCA-tau]]
## tau

.Function
`set[&Object] tau(FormalContext[&Object, &Attribute] fc, set[&Attributes] attributes)`



[[FCA-maxincl]]
## maxincl

.Function
`set[set[&T]] maxincl(set[set[&T]] c)`



[[FCA-createAttributeLattice]]
## createAttributeLattice

.Function
`rel[set[&Attribute], set[&Attribute]] createAttributeLattice(FormalContext[&Object, &Attribute] fc)`



[[FCA-makeNodes]]
## makeNodes

.Function
`map[Concept[&Object, &Attribute], int] makeNodes(ConceptLattice[&Object, &Attribute] q)`



[[FCA-newAdded1]]
## newAdded1

.Function
`set[&Attribute] newAdded1(ConceptLattice[&Object, &Attribute] q,  Concept[&Object, &Attribute] c)`



[[FCA-newAdded0]]
## newAdded0

.Function
`set[&Concept] newAdded0(ConceptLattice[&Object, &Attribute] q, Concept[&Object, &Attribute] c)`



[[FCA-compose]]
## compose

.Function
`Stm compose(Concept[&Object, &Attribute] c, map[Concept[&Object, &Attribute], int] z, bool lab)`



[[FCA-toDotString]]
## toDotString

.Function
`str toDotString(ConceptLattice[&Object, &Attribute]  q)`

.Synopsis
Write relation in `.dot` format.

:leveloffset: +1

:leveloffset: -1


[[analysis-graphs]]
# graphs
:concept: Libraries/analysis/graphs

.Synopsis
Analyzing unlabeled and labelled graphs.

.Syntax

.Types

.Function

.Usage

.Description

Graphs are represented as relations. So in general the idea is to use the `Relation` module to manipulate graphs.
At the same time there are algorithms and analyses which make particular sense when we view a relation as a graph, hence the
existence of the `Graph` and `LabeledGraph` libraries.


*** <<graphs-Graph,Graph>>: A `Graph` datatype with associated functions.
*** <<graphs-LabeledGraph,LabeledGraph>>: Return the bottom nodes of a LGraph.

.Examples

.Benefits

.Pitfalls


:leveloffset: +1


[[graphs-Graph]]

[[graphs-Graph]]
# Graph
:concept: Libraries/analysis/graphs/Graph
.Usage
`import analysis::graphs::Graph;`


.Synopsis
A `Graph` datatype with associated functions.

.Types
`alias Graph[&T] = rel[&T from, &T to];`

.Description
The Graph data type is a binary relation and all operators and functions defined
on link:/Rascal#Values-Relation[relations] are also defined on Graphs.

The `Graph` library provides the following functions:

* <<Libraries/analysis/graphs/Graph-Graph[&T],Graph[&T]>>:
* <<Libraries/analysis/graphs/Graph-order,order>>: Compute topological order of the nodes in a graph.
* <<Libraries/analysis/graphs/Graph-bottom,bottom>>: Determine the bottom nodes (leaves) of a graph.
* <<Libraries/analysis/graphs/Graph-predecessors,predecessors>>: Determine the direct predecessors of a graph node.
* <<Libraries/analysis/graphs/Graph-reach,reach>>: Determine the graph nodes reachable from a set of nodes.
* <<Libraries/analysis/graphs/Graph-reachR,reachR>>: Determine the graph nodes reachable from a set of nodes using a restricted set of intermediate nodes.
* <<Libraries/analysis/graphs/Graph-reachX,reachX>>: Determine the graph nodes reachable from a set of nodes excluding certain intermediate nodes.
* <<Libraries/analysis/graphs/Graph-shortestPathPair,shortestPathPair>>: Determine the shortest path between two graph nodes.
* <<Libraries/analysis/graphs/Graph-successors,successors>>: Determine the direct successors of a graph node.
* <<Libraries/analysis/graphs/Graph-top,top>>: Determine the set of top nodes (roots) of a graph.
* <<Libraries/analysis/graphs/Graph-connectedComponents,connectedComponents>>: Determine the connected components of a graph.


[[Graph-Graph[&T]]]
## Graph[&T]
.Types
`rel[&T from, &T to]`



[[Graph-order]]
## order

.Function
`list[&T] order(Graph[&T] g)`

.Synopsis
Compute topological order of the nodes in a graph.

.Examples
[source,rascal-shell]

rascal>import analysis::graphs::Graph; ok rascal>order({<3,4>, <1,2>, <2,4>, <1,3>}); list[int]: [1,3,2,4]

[[Graph-bottom]]
## bottom

.Function
`set[&T] bottom(Graph[&T] G)`

.Synopsis
Determine the bottom nodes (leaves) of a graph.

.Description
Returns the bottom nodes of Graph `G`, i.e., the leaf nodes that don't have any descendants.

.Examples
[source,rascal-shell]

rascal>import analysis::graphs::Graph; ok rascal>bottom({<1,2>, <1,3>, <2,4>, <3,4>}); set[int]: {4}

[[Graph-predecessors]]
## predecessors

.Function
`set[&T] predecessors(Graph[&T] G, &T From)`

.Synopsis
Determine the direct predecessors of a graph node.

.Description
Returns the direct predecessors of node `From` in Graph `G`.

.Examples
[source,rascal-shell]

rascal>import analysis::graphs::Graph; ok rascal>predecessors({<1,2>, <1,3>, <2,4>, <3,4>}, 4); set[int]: {3,2}

[[Graph-reach]]
## reach

.Function
`set[&T] reach(Graph[&T] G, set[&T] Start)`

.Synopsis
Determine the graph nodes reachable from a set of nodes.

.Description
Returns the set of nodes in Graph `G` that are reachable from any of the nodes
in the set `Start`.

[[Graph-reachR]]
## reachR

.Function
`set[&T] reachR(Graph[&T] G, set[&T] Start, set[&T] Restr)`

.Synopsis
Determine the graph nodes reachable from a set of nodes using a restricted set of intermediate nodes.

.Description
Returns the set of nodes in Graph `G` that are reachable from any of the nodes
in set `Start` using path that only use nodes in the set `Restr`.

.Examples
[source,rascal-shell]

rascal>import analysis::graphs::Graph; ok rascal>reachR({<1,2>, <1,3>, <2,4>, <3,4>}, {1}, {1, 2, 3}); set[int]: {3,2}

[[Graph-reachX]]
## reachX

.Function
`set[&T] reachX(Graph[&T] G, set[&T] Start, set[&T] Excl)`

.Synopsis
Determine the graph nodes reachable from a set of nodes excluding certain intermediate nodes.

.Description
Returns set of nodes in Graph `G` that are reachable from any of the nodes
in `Start` via path that exclude nodes in `Excl`.

.Examples
[source,rascal-shell]

rascal>import analysis::graphs::Graph; ok rascal>reachX({<1,2>, <1,3>, <2,4>, <3,4>}, {1}, {2}); set[int]: {3,4}

[[Graph-shortestPathPair]]
## shortestPathPair

.Function
`list[&T] shortestPathPair(Graph[&T] G, &T From, &T To)`

.Synopsis
Determine the shortest path between two graph nodes.

.Description
Returns the shortest path between nodes `From` and `To` in Graph `G`.

[[Graph-successors]]
## successors

.Function
`set[&T] successors(Graph[&T] G, &T From)`

.Synopsis
Determine the direct successors of a graph node.

.Description
Returns the direct successors of node `From` in Graph `G`.

.Examples
[source,rascal-shell]

rascal>import analysis::graphs::Graph; ok rascal>successors({<1,2>, <1,3>, <2,4>, <3,4>}, 1); set[int]: {3,2}

[[Graph-top]]
## top

.Function
`set[&T] top(Graph[&T] G)`

.Synopsis
Determine the set of top nodes (roots) of a graph.

.Description
Returns the top nodes of Graph `G`, i.e., the root nodes that do not have any predecessors.

.Examples
[source,rascal-shell]

rascal>import analysis::graphs::Graph; ok rascal>top({<1,2>, <1,3>, <2,4>, <3,4>}); set[int]: {1}

[[Graph-connectedComponents]]
## connectedComponents

.Function
`set[set[&T]] connectedComponents(Graph[&T] G)`

.Synopsis
Determine the connected components of a graph.

.Description
Returns the http://en.wikipedia.org/wiki/Connected_component_(graph_theory)[connected components] of Graph `G`, as sets of nodes. All nodes within one component are all reachable from one another, there are no paths between two nodes from different components. The graph is assumed to be undirected.

.Examples
[source,rascal-shell]

rascal>import analysis::graphs::Graph; ok rascal>connectedComponents({<1,2>, <1,3>, <4,5>, <5,6>}); set[set[int]]: { {5,4,6}, {1,3,2} }

:leveloffset: +1

:leveloffset: -1



[[graphs-LabeledGraph]]

[[graphs-LabeledGraph]]
# LabeledGraph
:concept: Libraries/analysis/graphs/LabeledGraph
.Usage
`import analysis::graphs::LabeledGraph;`




[[LabeledGraph-LGraph[&T,&L]]]
## LGraph[&T,&L]
.Types
`rel[&T from, &L label, &T to]`



[[LabeledGraph-bottom]]
## bottom

.Function
`set[&T] bottom(LGraph[&T,&L] G)`

.Synopsis
Return the bottom nodes of a LGraph.

[[LabeledGraph-predecessors]]
## predecessors

.Function
`set[&T] predecessors(LGraph[&T,&L] G, &T From)`

.Synopsis
The predecessors of a single node in a LGraph.

[[LabeledGraph-reach]]
## reach

.Function
`set[&T] reach(LGraph[&T,&L] G, set[&T] Start)`

.Synopsis
Reachability from a given start set of nodes.

[[LabeledGraph-reachR]]
## reachR

.Function
`set[&T] reachR(LGraph[&T,&L] G, set[&T] Start, set[&T] Restr)`

.Synopsis
Reachability from given start set of nodes with restrictions.

[[LabeledGraph-reachX]]
## reachX

.Function
`set[&T] reachX(LGraph[&T,&L] G, set[&T] Start, set[&T] Excl)`

.Synopsis
Reachability from given start set of nodes with exclusions.

[[LabeledGraph-successors]]
## successors

.Function
`set[&T] successors(LGraph[&T, &L] G, &T From)`

.Synopsis
The successors of a single node in a LGraph.

[[LabeledGraph-top]]
## top

.Function
`set[&T] top(LGraph[&T,&L] G)`

.Synopsis
Return the top nodes of a LGraph.

:leveloffset: +1

:leveloffset: -1


:leveloffset: -1


[[analysis-m3]]
# m3
:concept: Libraries/analysis/m3

.Synopsis
a language independent meta model for facts about source code, which is extensible to include language specific modeling elements

.Syntax

.Types

.Function

.Usage

.Description

WARNING: this documentation awaits adaptation of m3 with the Rascal compiler

This is the core language independent model:


**** <<Core-M3,M3>>: the m3 constructor is identified by the name of a project encoded as a [$Expressions/Values/Location] and has annotations for each kind of fact extracted from a project.

For language-specific support, please go here:

*  [lang/java/m3]


To get started with m3 immediately, please have a look at:

*  [$lang/java/jdt/m3/Core/createM3FromEclipseProject]

.Examples

*  See [$Recipes:Metrics/MeasuringJava] for a step-by-step by-example recipe for how to use M3 for measuring things about Java:

.Benefits

.Pitfalls


:leveloffset: +1

:leveloffset: -1


[[analysis-statistics]]
# statistics
:concept: Libraries/analysis/statistics

.Synopsis
Statistical functions.

.Description

A collection of statistical functions based on the
http://commons.apache.org/math/api-3.6/index.html[Apache statistics library].

We do not provide a course on (or even an introduction to) statistics. Useful background information can be found here:

* http://en.wikipedia.org/wiki/Statistics[Statistics] on Wikipedia.

* http://www.artofproblemsolving.com/LaTeX/Examples/statistics_firstfive.pdf[An Introduction to Statistics] by Keone Hon.

* http://www.greenteapress.com/thinkstats/thinkstats.pdf[Think Stats]: Probability and Statistics for Programmers]
  by Allan B. Downey gives a very readable overview of statistic techniques.

* http://www.scatterchart.com/statistical_calculator/[Statistics Calculator] allows entering data and get an overview of the values of various statistical indicators.

* http://easycalculation.com/statistics/statistics.php[Online Calculation on STATISTICS] gives calculators for individual measures.


The following functionality is offered:


*** <<statistics-Correlation,Correlation>>: Correlation between data values.
*** <<statistics-Descriptive,Descriptive>>: Descriptive Statistics.
*** <<statistics-Frequency,Frequency>>: Frequency distributions.
*** <<statistics-Inference,Inference>>: Statistical inference methods.
*** <<statistics-SimpleRegression,SimpleRegression>>: Statistical methods for simple regression.

.Pitfalls

*  Be aware that in creating data for statistical analysis, repeated values may occur. This implies that you should avoid creating sets of observations. This also explains why the functions provided here take lists (with elements of various types) as argument.

*  The validity of several of the statistics depend on the assumption that the observations included in the model are drawn from a
http://en.wikipedia.org/wiki/Bivariate_normal_distribution[Bivariate Normal Distribution].
This is explicitly stated for functions this is the case.

WARNING: The statistics library is still highly experimental.
     Interfaces may change and functions maybe added or deleted without notice.

:leveloffset: +1


[[statistics-Correlation]]

[[statistics-Correlation]]
# Correlation
:concept: Libraries/analysis/statistics/Correlation
.Usage
`import analysis::statistics::Correlation;`


.Synopsis
Correlation between data values.

.Description
Compute the http://en.wikipedia.org/wiki/Correlation[correlation] between pairs of data values.
Correlation measures the statistical relationship between two sets of data.

The following functions are provided:

* <<Libraries/analysis/statistics/Correlation-PearsonsCorrelation,PearsonsCorrelation>>: Pearson product-moment correlation coefficient.
* <<Libraries/analysis/statistics/Correlation-PearsonsCorrelationStandardErrors,PearsonsCorrelationStandardErrors>>: Standard errors associated with Pearson correlation
* <<Libraries/analysis/statistics/Correlation-PearsonsCorrelationPValues,PearsonsCorrelationPValues>>: P-values (significance) associated with Pearson correlation
* <<Libraries/analysis/statistics/Correlation-SpearmansCorrelation,SpearmansCorrelation>>: Spearman's rank correlation coefficient.
* <<Libraries/analysis/statistics/Correlation-covariance,covariance>>: Covariance of data values.


[[Correlation-PearsonsCorrelation]]
## PearsonsCorrelation

.Function
`num PearsonsCorrelation(lrel[num x,num y] values)`

.Synopsis
Pearson product-moment correlation coefficient.

.Description

Compute the http://en.wikipedia.org/wiki/Pearson_product-moment_correlation_coefficient[Pearson product-moment correlation coefficient].
It is a measure of the strength of the linear dependence between two variables.

.Pitfalls
Use <<SpearmansCorrelation>> when there is a *monotonous dependence* between the two variables.

[[Correlation-PearsonsCorrelationStandardErrors]]
## PearsonsCorrelationStandardErrors

.Function
`list[real] PearsonsCorrelationStandardErrors(lrel[num x,num y] values)`

.Synopsis
Standard errors associated with Pearson correlation.

[[Correlation-PearsonsCorrelationPValues]]
## PearsonsCorrelationPValues

.Function
`list[real] PearsonsCorrelationPValues(lrel[num x,num y] values)`

.Synopsis
P-values (significance) associated with Pearson correlation.

[[Correlation-SpearmansCorrelation]]
## SpearmansCorrelation

.Function
`num SpearmansCorrelation(lrel[num x,num y] values)`

.Synopsis
Spearman's rank correlation coefficient.

.Description

Compute http://en.wikipedia.org/wiki/Spearman's_rank_correlation_coefficient[Spearman's rank correlation coefficient].
The correlation between the data values is computed by first performing a rank transformation
on the data values using a natural ranking and then computing <<PearsonsCorrelation>>.

.Pitfalls
Use <<PearsonsCorrelation>> when there is a *linear dependence* between the variables.

[[Correlation-covariance]]
## covariance

.Function
`num covariance(lrel[num x,num y] values)`

.Synopsis
Covariance of data values.

.Description

Computes the http://en.wikipedia.org/wiki/Covariance[covariance] between the `x` and `y` values.

.Examples
[source,rascal-shell]

rascal>import analysis::statistics::Correlation; ok rascal>covariance([<1,12>,<3,12>,<3,11>,<5,7>]); real: -2.5

:leveloffset: +1

:leveloffset: -1



[[statistics-Descriptive]]

[[statistics-Descriptive]]
# Descriptive
:concept: Libraries/analysis/statistics/Descriptive
.Usage
`import analysis::statistics::Descriptive;`


.Synopsis
Descriptive Statistics.

.Description
Provides the following univariate (single variable) statistics functions:


* <<Libraries/analysis/statistics/Descriptive-geometricMean,geometricMean>>:
* <<Libraries/analysis/statistics/Descriptive-geometricMean,geometricMean>>: Geometric mean of data values.
* <<Libraries/analysis/statistics/Descriptive-kurtosis,kurtosis>>: Kurtosis of data values.
* <<Libraries/analysis/statistics/Descriptive-kurtosisExcess,kurtosisExcess>>: Kurtosis excess of data values.
* <<Libraries/analysis/statistics/Descriptive-max,max>>: Largest data value
* <<Libraries/analysis/statistics/Descriptive-mean,mean>>:
* <<Libraries/analysis/statistics/Descriptive-mean,mean>>: Arithmetic mean of data values.
* <<Libraries/analysis/statistics/Descriptive-median,median>>:
* <<Libraries/analysis/statistics/Descriptive-median,median>>: Median of data values.
* <<Libraries/analysis/statistics/Descriptive-middle,middle>>:
* <<Libraries/analysis/statistics/Descriptive-min,min>>: Smallest data value
* <<Libraries/analysis/statistics/Descriptive-percentile,percentile>>: Percentile of data values.
* <<Libraries/analysis/statistics/Descriptive-variance,variance>>:
* <<Libraries/analysis/statistics/Descriptive-variance,variance>>: Variance of data values.
* <<Libraries/analysis/statistics/Descriptive-skewness,skewness>>:
* <<Libraries/analysis/statistics/Descriptive-skewness,skewness>>: Skewness of data values.
* <<Libraries/analysis/statistics/Descriptive-standardDeviation,standardDeviation>>: Standard deviation of data values.
* <<Libraries/analysis/statistics/Descriptive-sum,sum>>:
* <<Libraries/analysis/statistics/Descriptive-sum,sum>>: Sum of data values
* <<Libraries/analysis/statistics/Descriptive-sumsq,sumsq>>: Sum of the squares of data values
* <<Libraries/analysis/statistics/Descriptive-centralMoment,centralMoment>>: Calculate the k-th central momen
* <<Libraries/analysis/statistics/Descriptive-moment,moment>>: Calculate the k-th momen
* <<Libraries/analysis/statistics/Descriptive-size,size>>:
* <<Libraries/analysis/statistics/Descriptive-tail,tail>>:
* <<Libraries/analysis/statistics/Descriptive-head,head>>:
* <<Libraries/analysis/statistics/Descriptive-sort,sort>>:
* <<Libraries/analysis/statistics/Descriptive-sort,sort>>:


.Examples

[source,rascal-shell]

rascal>import analysis::statistics::Descriptive; ok rascal>D = [67, 88, 55, 92.5, 102, 51]; list[num]: [67,88,55,92.5,102,51] rascal>mn = min(D); int: 51 rascal>mx = max(D); int: 102 rascal>range = mx - mn; int: 51 rascal>midrange = mn + range/2; int: 76 rascal>sum(D); real: 455.5 rascal>mean(D); real: 75.91666667 rascal>geometricMean(D); real: 73.3734107237 rascal>standardDeviation(D); real: 21.1622698845 rascal>variance(D); real: 447.841666666666666666666666666 rascal>percentile(D,25); int: 55 rascal>percentile(D,50); int: 67 rascal>percentile(D,75); real: 92.5

[[Descriptive-geometricMean]]
## geometricMean

.Function
* `real geometricMean(list[num] l:[])`
* `default real geometricMean([num hd, *num tl])`




[[Descriptive-kurtosis]]
## kurtosis

.Function
`real kurtosis(list[num] values)`

.Synopsis
Kurtosis of data values.

.Description

Computes the http://en.wikipedia.org/wiki/Kurtosis[kurtosis] of the given data values.
Kurtosis is a measure of the "peakedness" of a distribution.

[[Descriptive-kurtosisExcess]]
## kurtosisExcess

.Function
`real kurtosisExcess(list[num] values)`

.Synopsis
Kurtosis excess of data values.

.Description

Computes the http://en.wikipedia.org/wiki/Kurtosis[kurtosis excess] of the given data values.
Kurtosis excess is a measure of the "peakedness" of a distribution corrected such that a normal distribution will be 0.

[[Descriptive-max]]
## max

.Function
`(&T <: num) max(list[&T <: num] nums) throws EmptyList`

.Synopsis
Largest data value.

[[Descriptive-mean]]
## mean

.Function
* `real mean(list[&T<:num] l:[])`
* `default real mean(list[num] nums)`




[[Descriptive-median]]
## median

.Function
* `real median(list[num] l:[])`
* `default real median(list[num] nums)`




[[Descriptive-middle]]
## middle

.Function
`list[&T] middle(list[&T] nums)`



[[Descriptive-min]]
## min

.Function
`(&T <: num) min(list[&T <: num] nums) throws EmptyList`

.Synopsis
Smallest data value.

[[Descriptive-percentile]]
## percentile

.Function
`&T <: num percentile(list[&T <: num] nums, num p)`

.Synopsis
Percentile of data values.

.Description

Returns the `p`th http://en.wikipedia.org/wiki/Percentile[percentile] of the data values.
 0 < `p` <= 100 should hold.

[[Descriptive-variance]]
## variance

.Function
* `num variance(list[num] l:[])`
* `num variance([num hd, *num tl])`




[[Descriptive-skewness]]
## skewness

.Function
* `real skewness(list[num] l:[])`
* `default real skewness(list[num] values)`




[[Descriptive-standardDeviation]]
## standardDeviation

.Function
`real standardDeviation(list[num] values)`

.Synopsis
Standard deviation of data values.

.Description
Computes the http://en.wikipedia.org/wiki/Standard_deviation[standard deviation]
of the data values. It shows how much variation exists from the average (mean, or expected value).

[[Descriptive-sum]]
## sum

.Function
* `(&T <:num) sum(list[(&T <:num)] _:[])`
* `default (&T <:num) sum([(&T <: num) hd, *(&T <: num) tl])`




[[Descriptive-sumsq]]
## sumsq

.Function
`(&T <:num) sumsq(list[&T <:num] values)`

.Synopsis
Sum of the squares of data values.

[[Descriptive-centralMoment]]
## centralMoment

.Function
`real centralMoment(list[num] nums, int order = 1)`

Calculate the k-th central moment

[[Descriptive-moment]]
## moment

.Function
`real moment(list[num] nums, int order = 1)`

Calculate the k-th moment

[[Descriptive-size]]
## size

.Function
`int size(list[&T] lst)`



[[Descriptive-tail]]
## tail

.Function
`list[&T] tail(list[&T] lst) throws EmptyList`



[[Descriptive-head]]
## head

.Function
`&T head(list[&T] lst) throws EmptyList`



[[Descriptive-sort]]
## sort

.Function
* `list[&T] sort(list[&T] lst)`
* `list[&T] sort(list[&T] l, bool (&T a, &T b) less)`




:leveloffset: +1

:leveloffset: -1



[[statistics-Frequency]]

[[statistics-Frequency]]
# Frequency
:concept: Libraries/analysis/statistics/Frequency
.Usage
`import analysis::statistics::Frequency;`


.Synopsis
Frequency distributions.

.Description

The following functions are provided:

* <<Libraries/analysis/statistics/Frequency-distribution,distribution>>: Compute a distribution: count how many times events are mapped to which bucket.
* <<Libraries/analysis/statistics/Frequency-distribution,distribution>>:
* <<Libraries/analysis/statistics/Frequency-distribution,distribution>>:
* <<Libraries/analysis/statistics/Frequency-distribution,distribution>>:
* <<Libraries/analysis/statistics/Frequency-cumFreq,cumFreq>>: Cumulative frequency of values less than or equal to a given value.
* <<Libraries/analysis/statistics/Frequency-cumFreq,cumFreq>>:
* <<Libraries/analysis/statistics/Frequency-cumPct,cumPct>>: Cumulative percentage of values less than or equal to a given value.
* <<Libraries/analysis/statistics/Frequency-cumPct,cumPct>>:
* <<Libraries/analysis/statistics/Frequency-pct,pct>>: Percentage of values that are equal to a given value.
* <<Libraries/analysis/statistics/Frequency-pct,pct>>:


[[Frequency-distribution]]
## distribution

.Function
* `map[&T, int] distribution(rel[&U event, &T bucket] input)`
* `map[&T <: num, int] distribution(rel[&U event, &T <: num bucket] input, &T <: num bucketSize)`
* `map[&T, int] distribution(map[&U event, &T bucket] input)`
* `map[&T <: num, int] distribution(map[&U event, &T <: num bucket] input, &T <: num bucketSize)`


.Synopsis
Compute a distribution: count how many times events are mapped to which bucket.

.Examples
[source,rascal-shell]

rascal>import analysis::statistics::Frequency; ok rascal>distribution({<"chicken","animal">,<"bear","animal">,<"oak","plant">,<"tulip","plant">}); map[str, int]: ("plant":2,"animal":2) rascal>distribution({<"alice",2>,<"bob",3>,<"claire",5>},5); map[int, int]: (5:2,0:1)

[[Frequency-cumFreq]]
## cumFreq

.Function
* `int cumFreq(list[value] values, num n)`
* `int cumFreq(list[value] values, str s)`


.Synopsis
Cumulative frequency of values less than or equal to a given value.

.Description

Returns the cumulative frequency of values less than or equal to a given numeric or string value.
Returns 0 if the value is not comparable to the values set.

.Examples

[source,rascal-shell]

rascal>import analysis::statistics::Frequency; ok rascal> >>>>>>>D = [1, 2, 1, 1, 3, 5]; list[int]: [1,2,1,1,3,5] rascal>cumFreq(D, 1); int: 3 rascal>cumFreq(D, 2); int: 4 rascal>cumFreq(D, 10); int: 6

[[Frequency-cumPct]]
## cumPct

.Function
* `num cumPct(list[value] values, num n)`
* `num cumPct(list[value] values, str s)`


.Synopsis
Cumulative percentage of values less than or equal to a given value.

.Description
Returns the cumulative percentage of values less than or equal to v (as a proportion between 0 and 1).

[source,rascal-shell]

rascal>import analysis::statistics::Frequency; ok rascal>D = [1, 2, 1, 1, 3, 5]; list[int]: [1,2,1,1,3,5] rascal>cumPct(D, 1); real: 0.5 rascal>cumPct(D, 2); real: 0.6666666666666666 rascal>cumPct(D, 10); real: 1.0

[[Frequency-pct]]
## pct

.Function
* `num pct(list[value] values, num n)`
* `num pct(list[value] values, str s)`


.Synopsis
Percentage of values that are equal to a given value.

.Description
Returns the percentage of values that are equal to v (as a proportion between 0 and 1).
.Examples
[source,rascal-shell]

rascal>import analysis::statistics::Frequency; ok rascal>D = [1, 2, 1, 1, 3, 5]; list[int]: [1,2,1,1,3,5] rascal>pct(D, 1); real: 0.5 rascal>pct(D, 2); real: 0.16666666666666666 rascal>pct(D, 10); real: 0.0

:leveloffset: +1

:leveloffset: -1



[[statistics-Inference]]

[[statistics-Inference]]
# Inference
:concept: Libraries/analysis/statistics/Inference
.Usage
`import analysis::statistics::Inference;`


.Synopsis
Statistical inference methods.

.Description

The following functions are provided:

* <<Libraries/analysis/statistics/Inference-chiSquare,chiSquare>>: Chi-square coefficient of data values.
* <<Libraries/analysis/statistics/Inference-chiSquareTest,chiSquareTest>>: Chi-square test on data values.
* <<Libraries/analysis/statistics/Inference-chiSquareTest,chiSquareTest>>:
* <<Libraries/analysis/statistics/Inference-tTest,tTest>>: T-test on sample data.
* <<Libraries/analysis/statistics/Inference-tTest,tTest>>:
* <<Libraries/analysis/statistics/Inference-tTest,tTest>>:
* <<Libraries/analysis/statistics/Inference-anovaFValue,anovaFValue>>: Analysis of Variance (ANOVA) f-value.
* <<Libraries/analysis/statistics/Inference-anovaPValue,anovaPValue>>: Analysis of Variance (ANOVA) p-value.
* <<Libraries/analysis/statistics/Inference-anovaTest,anovaTest>>: Analysis of Variance (ANOVA) test.
* <<Libraries/analysis/statistics/Inference-gini,gini>>: Gini coefficient.


[[Inference-chiSquare]]
## chiSquare

.Function
`num chiSquare(lrel[num expected, int observed] values)`

.Synopsis
Chi-square coefficient of data values.

.Description

Compute the http://en.wikipedia.org/wiki/Chi-square_statistic[ChiSquare statistic] comparing observed and expected frequency counts.

.Examples

Consider an example from the web page mentioned above.
To test the hypothesis that a random sample of 100 people has been drawn from a population in which men and women are equal in frequency, the observed number of men and women would be compared to the theoretical frequencies of 50 men and 50 women. If there were 44 men in the sample and 56 women, then we have the following:

[source,rascal-shell]

rascal>import analysis::statistics::Inference; ok rascal>chiSquare([<50, 44>, <50, 56>]) real: 1.44

[[Inference-chiSquareTest]]
## chiSquareTest

.Function
* `num chiSquareTest(lrel[num expected, int observed] values)`
* `bool chiSquareTest(lrel[num expected, int observed] values, real alpha)`


.Synopsis
Chi-square test on data values.

.Description

Perform a http://en.wikipedia.org/wiki/Pearson%27s_chi-squared_test[Chi-square test] comparing
expected and observed frequency counts. There are two forms of this test:

*  Returns the _observed significance level_, or p-value, associated with a Chi-square goodness of fit test
comparing observed frequency counts to expected counts.

*   Performs a Chi-square goodness of fit test evaluating the null hypothesis that the observed counts conform to the frequency distribution described by the expected counts, with significance level `alpha` (0 < `alpha` < 0.5). Returns true iff the null hypothesis
can be rejected with confidence 1 - `alpha`.

[[Inference-tTest]]
## tTest

.Function
* `num tTest(list[num] sample1, list[num] sample2)`
* `bool tTest(list[num] sample1, list[num] sample2, num alpha)`
* `bool tTest(num mu, list[num] sample, num alpha)`


.Synopsis
T-test on sample data.

.Description

Perform http://en.wikipedia.org/wiki/Student's_t-test[student's t-test].
The test is provided in three variants:

*  Returns the _observed significance level_, or _p-value_, associated with a two-sample, two-tailed t-test comparing the means of the input samples. The number returned is the smallest significance level at which one can reject the null hypothesis that the two means are equal in favor of the two-sided alternative that they are different. For a one-sided test, divide the returned value by 2.

The t-statistic used is `t = (m1 - m2) / sqrt(var1/n1 + var2/n2)`
where

**  `n1` is the size of the first sample
**  `n2` is the size of the second sample;
**  `m1` is the mean of the first sample;
**  `m2` is the mean of the second sample;
**  `var1` is the variance of the first sample;
**  `var2` is the variance of the second sample.

*  Performs a two-sided t-test evaluating the null hypothesis that `sample1` and `sample2` are drawn from populations with the same mean, with significance level `alpha`. This test does not assume that the subpopulation variances are equal.
Returns true iff the null hypothesis that the means are equal can be rejected with confidence 1 - `alpha`. To perform a 1-sided test, use `alpha` / 2.

*  Performs a two-sided t-test evaluating the null hypothesis that the mean of the population from which sample is drawn equals `mu`.
Returns true iff the null hypothesis can be rejected with confidence 1 - `alpha`. To perform a 1-sided test, use `alpha` * 2.

.Examples
We use the data from the following http://web.mst.edu/~psyworld/texample.htm#1[example] to illustrate the t-test.
First, we compute the t-statistic using the formula given above.
[source,rascal-shell]

rascal>import util::Math; ok rascal>import analysis::statistics::Descriptive; ok rascal>import List; ok rascal>s1 = [5,7,5,3,5,3,3,9]; list[int]: [5,7,5,3,5,3,3,9] rascal>s2 = [8,1,4,6,6,4,1,2]; list[int]: [8,1,4,6,6,4,1,2] rascal>(mean(s1) - mean(s2))/sqrt(variance(s1)/size(s1) + variance(s2)/size(s2)); real: 0.84731854581

This is the same result as obtained in the cited example.
We can also compute it directly using the `tTest` functions:
[source,rascal-shell]

rascal>import analysis::statistics::Inference; ok rascal>tTest(s1, s2); real: 0.4115203997374087

Observe that this is a smaller value than comes out directly of the formula.
Recall that: _The number returned is the smallest significance level at which one can reject the null hypothesis that the two means are equal in favor of the two-sided alternative that they are different._
Finally, we perform the test around the significance level we just obtained:
[source,rascal-shell]

rascal>tTest(s1,s2,0.40); bool: false rascal>tTest(s1,s2,0.50); bool: true

[[Inference-anovaFValue]]
## anovaFValue

.Function
`num anovaFValue(list[list[num]] categoryData)`

.Synopsis
Analysis of Variance (ANOVA) f-value.

.Description

Perform http://en.wikipedia.org/wiki/Analysis_of_variance[Analysis of Variance test]
also described http://www.statsoft.com/textbook/anova-manova/[here].

Compute the F statistic -- also known as http://en.wikipedia.org/wiki/F-test[F-test] -- using the definitional formula
   `F = msbg/mswg`
where

*  `msbg` = between group mean square.
*  `mswg` = within group mean square.


are as defined http://faculty.vassar.edu/lowry/ch13pt1.html[here].

[[Inference-anovaPValue]]
## anovaPValue

.Function
`num anovaPValue(list[list[num]] categoryData)`

.Synopsis
Analysis of Variance (ANOVA) p-value.

.Description

Perform http://en.wikipedia.org/wiki/Analysis_of_variance[Analysis of Variance test]
also described http://www.statsoft.com/textbook/anova-manova/[here].

Computes the exact p-value using the formula `p = 1 - cumulativeProbability(F)`
where `F` is the <<anovaFValue>>.

[[Inference-anovaTest]]
## anovaTest

.Function
`bool anovaTest(list[list[num]] categoryData, num alpha)`

.Synopsis
Analysis of Variance (ANOVA) test.

.Description

Perform http://en.wikipedia.org/wiki/Analysis_of_variance[Analysis of Variance test]
also described http://www.statsoft.com/textbook/anova-manova/[here].

Returns true iff the estimated p-value is less than `alpha` (0 < `alpha` <= 0.5).

The exact p-value is computed using the formula `p = 1 - cumulativeProbability(F)`
where `F` is the <<anovaFValue>>.

[[Inference-gini]]
## gini

.Function
`real gini(lrel[num observation,int frequency] values)`

.Synopsis
Gini coefficient.

.Description

Computes the http://en.wikipedia.org/wiki/Gini_coefficient[Gini coefficient]
that measures the inequality among values in a frequency distribution.

The Gini coefficient is computed using Deaton's formula and returns a
value between 0 (completely equal distribution) and
1 (completely unequal distribution).

.Examples
[source,rascal-shell]

rascal>import analysis::statistics::Inference; ok

A completely equal distribution:
[source,rascal-shell]

rascal>gini([<10000, 1>, <10000, 1>, <10000, 1>]); real: 0.0

A rather unequal distribution:
[source,rascal-shell]

rascal>gini([<998000, 1>, <20000, 3>, <117500, 1>, <70000, 2>, <23500, 5>, <45200,1>]); real: 0.8530758129256304

:leveloffset: +1

:leveloffset: -1



[[statistics-SimpleRegression]]

[[statistics-SimpleRegression]]
# SimpleRegression
:concept: Libraries/analysis/statistics/SimpleRegression
.Usage
`import analysis::statistics::SimpleRegression;`


.Synopsis
Statistical methods for simple regression.

.Description

The following functions are provided:

* <<Libraries/analysis/statistics/SimpleRegression-intercept,intercept>>: Intercept of regression line.
* <<Libraries/analysis/statistics/SimpleRegression-interceptStdErr,interceptStdErr>>: Standard error of intercept estimate.
* <<Libraries/analysis/statistics/SimpleRegression-meanSquareError,meanSquareError>>: Sum of squared errors divided by the degrees of freedom.
* <<Libraries/analysis/statistics/SimpleRegression-R,R>>: Pearson's product-moment correlation coefficient.
* <<Libraries/analysis/statistics/SimpleRegression-regressionSumSquares,regressionSumSquares>>: Sum of squared deviations of the predicted y values about their mean.
* <<Libraries/analysis/statistics/SimpleRegression-RSquare,RSquare>>: Coefficient of determination.
* <<Libraries/analysis/statistics/SimpleRegression-significance,significance>>: Significance of the slope correlation.
* <<Libraries/analysis/statistics/SimpleRegression-slope,slope>>: Slope of regression line.
* <<Libraries/analysis/statistics/SimpleRegression-slopeConfidenceInterval,slopeConfidenceInterval>>: The 95% slope confidence interval.
* <<Libraries/analysis/statistics/SimpleRegression-slopeStdErr,slopeStdErr>>: Standard error of slope estimate.
* <<Libraries/analysis/statistics/SimpleRegression-sumOfCrossProducts,sumOfCrossProducts>>: Sum of cross products of observations.
* <<Libraries/analysis/statistics/SimpleRegression-sumSquaredErrors,sumSquaredErrors>>: Sum of squared errors.
* <<Libraries/analysis/statistics/SimpleRegression-totalSumSquares,totalSumSquares>>: Sum of squared deviations.
* <<Libraries/analysis/statistics/SimpleRegression-XSumSquares,XSumSquares>>: Sum of squared deviations of x values about their mean.
* <<Libraries/analysis/statistics/SimpleRegression-predict,predict>>: Predict a value.


[[SimpleRegression-intercept]]
## intercept

.Function
`num intercept(lrel[num,num] values) throws IllegalArgument(value v, str message)`

.Synopsis
Intercept of regression line.
.Description

Returns the http://en.wikipedia.org/wiki/Root_of_a_function[intercept] of the estimated regression line.
The least squares estimate of the intercept is computed using these http://www.xycoon.com/estimation4.htm[normal equations].

[[SimpleRegression-interceptStdErr]]
## interceptStdErr

.Function
`num interceptStdErr(lrel[num,num] values) throws IllegalArgument(value v, str message)`

.Synopsis
Standard error of intercept estimate.
.Description
Returns the http://www.xycoon.com/standarderrorb0.htm[standard error of the intercept estimate], usually denoted s(b0).

[[SimpleRegression-meanSquareError]]
## meanSquareError

.Function
`num meanSquareError(lrel[num,num] values) throws IllegalArgument(value v, str message)`

.Synopsis
Sum of squared errors divided by the degrees of freedom.

.Description

Returns the sum of squared errors divided by the degrees of freedom, usually abbreviated MSE.

[[SimpleRegression-R]]
## R

.Function
`num R(lrel[num,num] values) throws IllegalArgument(value v, str message)`

.Synopsis
Pearson's product-moment correlation coefficient.

.Description
Computes Pearson's product-moment correlation coefficient.
More functions related to this coefficient can be found in <<Correlation>>.

[[SimpleRegression-regressionSumSquares]]
## regressionSumSquares

.Function
`num regressionSumSquares(list[tuple[num,num]] values) throws IllegalArgument(value v, str message)`

.Synopsis
Sum of squared deviations of the predicted y values about their mean.

.Description

Returns the sum of squared deviations of the predicted y values about their mean (which equals the mean of y).
This is usually abbreviated SSR or http://www.xycoon.com/SumOfSquares.htm[SSM].

[[SimpleRegression-RSquare]]
## RSquare

.Function
`num RSquare(lrel[num,num] values) throws IllegalArgument(value v, str message)`

.Synopsis
Coefficient of determination.
.Description

Returns the http://en.wikipedia.org/wiki/Coefficient_of_determination[coefficient of determination] usually denoted r__^2^.
It provides a measure of how well future outcomes are likely to be predicted by the regression model.

[[SimpleRegression-significance]]
## significance

.Function
`num significance(lrel[num,num] values) throws IllegalArgument(value v, str message)`

.Synopsis
Significance of the slope correlation.
.Description

Returns the significance level of the slope (equiv) correlation.
Specifically, the returned value is the smallest alpha such that the slope confidence interval with significance level equal to alpha does not include 0. On regression output, this is often denoted Prob(|t| > 0)

.Pitfalls
The validity of this statistic depends on the assumption that the observations included in the model are drawn from a
http://en.wikipedia.org/wiki/Bivariate_normal_distribution[Bivariate Normal Distribution].

[[SimpleRegression-slope]]
## slope

.Function
`num slope(lrel[num,num] values) throws IllegalArgument(value v, str message)`

.Synopsis
Slope of regression line.
.Description
Returns the slope of the estimated regression line.
The least squares estimate of the slope is computed using the http://www.xycoon.com/estimation4.htm[normal equations].
The slope is sometimes denoted b1.

[[SimpleRegression-slopeConfidenceInterval]]
## slopeConfidenceInterval

.Function
`num slopeConfidenceInterval(lrel[num,num] values) throws IllegalArgument(value v, str message)`

.Synopsis
The 95% slope confidence interval.

.Description

Returns the half-width of a 95% confidence interval for the slope estimate.
The 95% confidence interval is

(slope - slopeConfidenceInterval, slope + slopeConfidenceInterval)


.Pitfalls
The validity of this statistic depends on the assumption that the observations included in the model are drawn from a
http://en.wikipedia.org/wiki/Bivariate_normal_distribution[Bivariate Normal Distribution].

[[SimpleRegression-slopeStdErr]]
## slopeStdErr

.Function
`num slopeStdErr(lrel[num,num] values) throws IllegalArgument(value v, str message)`

.Synopsis
Standard error of slope estimate.
.Description

Returns the http://www.xycoon.com/standarderrorb0.htm[standard error of the slope estimate], usually denoted s(b1).

[[SimpleRegression-sumOfCrossProducts]]
## sumOfCrossProducts

.Function
`num sumOfCrossProducts(lrel[num,num] values) throws IllegalArgument(value v, str message)`

.Synopsis
Sum of cross products of observations.
.Description

Returns the sum of crossproducts, x__~i~*y__~i~.

[[SimpleRegression-sumSquaredErrors]]
## sumSquaredErrors

.Function
`num sumSquaredErrors(lrel[num,num] values) throws IllegalArgument(value v, str message)`

.Synopsis
Sum of squared errors.
.Description

Returns the sum of squared errors (SSE) associated with the regression model.
The sum is computed using the computational formula

SSE = SYY - (SXY * SXY / SXX)

where SYY is the sum of the squared deviations of the y values about their mean, SXX is similarly defined and SXY is the sum of the products of x and y mean deviations.

The return value is constrained to be non-negative, i.e., if due to rounding errors the computational formula returns a negative result, 0 is returned.

[[SimpleRegression-totalSumSquares]]
## totalSumSquares

.Function
`num totalSumSquares(lrel[num,num] values) throws IllegalArgument(value v, str message)`

.Synopsis
Sum of squared deviations.
.Description

Returns the sum of squared deviations of the y values about their mean.
This is defined as http://www.xycoon.com/SumOfSquares.htm[SSTO].

[[SimpleRegression-XSumSquares]]
## XSumSquares

.Function
`num XSumSquares(lrel[num,num] values) throws IllegalArgument(value v, str message)`

.Synopsis
Sum of squared deviations of x values about their mean.

.Description

Returns the sum of squared deviations of the x values about their mean.

[[SimpleRegression-predict]]
## predict

.Function
`num predict(lrel[num,num] values, num x) throws IllegalArgument(value v, str message)`

.Synopsis
Predict a value.
.Description

Returns the "predicted" `y` value associated with the supplied `x` value, based on regression model derived from the provided data values:

`predict(x) = intercept + slope * x`

:leveloffset: +1

:leveloffset: -1


:leveloffset: -1


:leveloffset: -1


[[Libraries-lang]]
# lang
:concept: Libraries/lang

.Synopsis
Definitions and tools for various languages.

.Description


** <<lang-RSF,RSF>>: Functions for reading/writing the Rigi Standard Format (RSF).
*** <<RSF-readRSF,readRSF>>: Read a file in Rigi Standard Format (RSF).
** <<lang-csv,csv>>: Comma-Separated Values (CSV).
** <<lang-java,java>>: Definitions and tools related to the Java language.
*** <<java-jdt,jdt>>: tools for Java provided via reusing the Eclipse JDT.
*** <<java-m3,m3>>: Java-specific version of the M3 model.
** <<lang-xml,xml>>: XML utilities.

:leveloffset: +1

[[lang-RSF]]
# RSF
:concept: Libraries/lang/RSF

.Synopsis
Functions for reading/writing the Rigi Standard Format (RSF).


.Usage
`import lang::RSF::IO;`

.Types

.Function

.Description
Rigi Standard Format (RSF) is a textual format to represent binary relations and is
used to exchange relational facts between different tools.

An RSF file consists of triples of the form
[source,rascal]

$RelName$ $Elem_1$ $Elem_2$

where _RelName_ is the name of a relation and _Elem_~1~ and _Elem_~2~ are element values.

Provides the following function:

*** <<RSF-readRSF,readRSF>>: Read a file in Rigi Standard Format (RSF).

.Examples
[source,rascal]

call main printf call main listcreate data main FILE data listcreate List

defines two relations named `call` and `data`.

.Benefits

.Pitfalls


:leveloffset: +1

[[RSF-readRSF]]
# readRSF
:concept: Libraries/lang/RSF/readRSF

.Synopsis
Read a file in Rigi Standard Format (RSF).

.Usage

.Types

.Function
`map[str, rel[str,str]] readRSF(str nameRSFFile) throws IO(str msg)`

.Description
Since an RSF file may define more than one relation,
a mapping from relation name to relation value is returned.

.Examples
For the RSF file:
[source,rascal]

call main printf call main listcreate data main FILE data listcreate List

`readRSF` will create the following map:
[source,rascal]

("call" : {<"main", "printf">, <"main", "listcreate">}, "data" : {<"main", "FILE">, <"listcreate", "List">})

.Benefits

.Pitfalls


:leveloffset: +1

:leveloffset: -1


:leveloffset: -1


[[lang-csv]]
# csv
:concept: Libraries/lang/csv
.Synopsis
Comma-Separated Values (CSV).

.Description

The http://tools.ietf.org/html/rfc4180[CSV format] was originally intended for exchanging
information between spreadsheets and databases but is today used as an exchange format in many other application domains as well.
A CSV file has the following structure:

*  An optional header line consisting of field names separated by comma's.
*  One or more lines consisting of values separated by comma's.


Some adaptation is possible and includes:

*  Including or excluding the header line (use `"header" : "true"` in the option map for the various functions).
*  Using another separator than a comma (use `"separator" : ";"` in the option map for the various functions, where `";"` can be any single character string).


The following functions are provided in the <<Rascal-Libraries-lang-csv-IO>> library:


.Examples
Here is an example CSV file using the default separator (","):
[source,rascal]

field_name1,field_name2,field_name3 aaa,bbb,ccc zzz,yyy,xxx

Here is an example CSV file using a non-default separator (";"):
[source,rascal]

position;artist;title;year 1;Eagles;Hotel California;1977 2;Queen;Bohemian rhapsody;1975 3;Boudewijn de Groot;Avond;1997

:leveloffset: +1

:leveloffset: -1


[[lang-java]]
# java
:concept: Libraries/lang/java

.Synopsis
Definitions and tools related to the Java language.

:leveloffset: +1

[[java-jdt]]
# jdt
:concept: Libraries/lang/java/jdt

.Synopsis
tools for Java provided via reusing the Eclipse JDT

:leveloffset: +1

[[jdt-m3]]
# m3
:concept: Libraries/lang/java/jdt/m3

.Synopsis
functions for generating M3 models starting from Eclipse projects

:leveloffset: +1

:leveloffset: -1


:leveloffset: -1


[[java-m3]]
# m3
:concept: Libraries/lang/java/m3

.Synopsis
Java-specific version of the M3 model

.Syntax

.Types

.Function

.Usage

.Description

This API extends <<analysis-m3>> with Java specific functionality:


**** <<m3-AST,AST>>: defines AST node types for Java.
**** <<m3-Core,Core>>: extends the M3 [$analysis/m3/Core] with Java specific concepts such as inheritance and overriding.
***** <<Core-typeDependency,typeDependency>>:
**** <<m3-TypeHierarchy,TypeHierarchy>>:
**** <<m3-TypeSymbol,TypeSymbol>>:

Use this API to extract Java m3 models starting from Eclipse Java projects:


**** <<m3-AST,AST>>: defines AST node types for Java.
**** <<m3-Core,Core>>: extends the M3 [$analysis/m3/Core] with Java specific concepts such as inheritance and overriding.
***** <<Core-typeDependency,typeDependency>>:
**** <<m3-TypeHierarchy,TypeHierarchy>>:
**** <<m3-TypeSymbol,TypeSymbol>>:

.Examples

.Benefits

.Pitfalls


:leveloffset: +1


[[m3-AST]]

[[m3-AST]]
# AST
:concept: Libraries/lang/java/m3/AST
.Usage
`import lang::java::m3::AST;`


.Synopsis
defines AST node types for Java

[[AST-Declaration]]
## Declaration
.Types
[source,rascal]

data Declaration = \compilationUnit(list[Declaration] imports, list[Declaration] types) | \compilationUnit(Declaration package, list[Declaration] imports, list[Declaration] types) | \enum(str name, list[Type] implements, list[Declaration] constants, list[Declaration] body) | \enumConstant(str name, list[Expression] arguments, Declaration class) | \enumConstant(str name, list[Expression] arguments) | \class(str name, list[Type] extends, list[Type] implements, list[Declaration] body) | \class(list[Declaration] body) | \interface(str name, list[Type] extends, list[Type] implements, list[Declaration] body) | \field(Type \type, list[Expression] fragments) | \initializer(Statement initializerBody) | \method(Type \return, str name, list[Declaration] parameters, list[Expression] exceptions, Statement impl) | \method(Type \return, str name, list[Declaration] parameters, list[Expression] exceptions) | \constructor(str name, list[Declaration] parameters, list[Expression] exceptions, Statement impl) | \import(str name) | \package(str name) | \package(Declaration parentPackage, str name) | \variables(Type \type, list[Expression] \fragments) | \typeParameter(str name, list[Type] extendsList) | \annotationType(str name, list[Declaration] body) | \annotationTypeMember(Type \type, str name) | \annotationTypeMember(Type \type, str name, Expression defaultBlock) | \parameter(Type \type, str name, int extraDimensions) | \vararg(Type \type, str name) ;

[[AST-Expression]]
## Expression
.Types
[source,rascal]

data Expression = \arrayAccess(Expression array, Expression index) | \newArray(Type \type, list[Expression] dimensions, Expression init) | \newArray(Type \type, list[Expression] dimensions) | \arrayInitializer(list[Expression] elements) | \assignment(Expression lhs, str operator, Expression rhs) | \cast(Type \type, Expression expression) | \characterLiteral(str charValue) | \newObject(Expression expr, Type \type, list[Expression] args, Declaration class) | \newObject(Expression expr, Type \type, list[Expression] args) | \newObject(Type \type, list[Expression] args, Declaration class) | \newObject(Type \type, list[Expression] args) | \qualifiedName(Expression qualifier, Expression expression) | \conditional(Expression expression, Expression thenBranch, Expression elseBranch) | \fieldAccess(bool isSuper, Expression expression, str name) | \fieldAccess(bool isSuper, str name) | \instanceof(Expression leftSide, Type rightSide) | \methodCall(bool isSuper, str name, list[Expression] arguments) | \methodCall(bool isSuper, Expression receiver, str name, list[Expression] arguments) | \null() | \number(str numberValue) | \booleanLiteral(bool boolValue) | \stringLiteral(str stringValue) | \type(Type \type) | \variable(str name, int extraDimensions) | \variable(str name, int extraDimensions, Expression \initializer) | \bracket(Expression expression) | \this() | \this(Expression thisExpression) | \super() | \declarationExpression(Declaration declaration) | \infix(Expression lhs, str operator, Expression rhs) | \postfix(Expression operand, str operator) | \prefix(str operator, Expression operand) | \simpleName(str name) | \markerAnnotation(str typeName) | \normalAnnotation(str typeName, list[Expression] memberValuePairs) | \memberValuePair(str name, Expression \value) | \singleMemberAnnotation(str typeName, Expression \value) ;

[[AST-Statement]]
## Statement
.Types
[source,rascal]

data Statement = \assert(Expression expression) | \assert(Expression expression, Expression message) | \block(list[Statement] statements) | \break() | \break(str label) | \continue() | \continue(str label) | \do(Statement body, Expression condition) | \empty() | \foreach(Declaration parameter, Expression collection, Statement body) | \for(list[Expression] initializers, Expression condition, list[Expression] updaters, Statement body) | \for(list[Expression] initializers, list[Expression] updaters, Statement body) | \if(Expression condition, Statement thenBranch) | \if(Expression condition, Statement thenBranch, Statement elseBranch) | \label(str name, Statement body) | \return(Expression expression) | \return() | \switch(Expression expression, list[Statement] statements) | \case(Expression expression) | \defaultCase() | \synchronizedStatement(Expression lock, Statement body) | \throw(Expression expression) | \try(Statement body, list[Statement] catchClauses) | \try(Statement body, list[Statement] catchClauses, Statement \finally) | \catch(Declaration exception, Statement body) | \declarationStatement(Declaration declaration) | \while(Expression condition, Statement body) | \expressionStatement(Expression stmt) | \constructorCall(bool isSuper, Expression expr, list[Expression] arguments) | \constructorCall(bool isSuper, list[Expression] arguments) ;

[[AST-Type]]
## Type
.Types
[source,rascal]

data Type = arrayType(Type \type) | parameterizedType(Type \type) | qualifiedType(Type qualifier, Expression simpleName) | simpleType(Expression typeName) | unionType(list[Type] types) | wildcard() | upperbound(Type \type) | lowerbound(Type \type) | \int() | short() | long() | float() | double() | char() | string() | byte() | \void() | \boolean() ;

[[AST-Modifier]]
## Modifier
.Types
[source,rascal]

data Modifier = \private() | \public() | \protected() | \friendly() | \static() | \final() | \synchronized() | \transient() | \abstract() | \native() | \volatile() | \strictfp() | \annotation(Expression \anno) | \onDemand() | \default() ;

[[AST-getPaths]]
## getPaths

.Function
`set[loc] getPaths(loc dir, str suffix)`



[[AST-findRoots]]
## findRoots

.Function
`set[loc] findRoots(set[loc] folders)`



[[AST-createAstFromFile]]
## createAstFromFile

.Function
`Declaration createAstFromFile(loc file, bool collectBindings, bool errorRecovery = false, list[loc] sourcePath = [], list[loc] classPath = [], str javaVersion = "1.7")`

.Synopsis
Creates AST from a file

.Description

[[AST-createAstsFromFiles]]
## createAstsFromFiles

.Function
`set[Declaration] createAstsFromFiles(set[loc] file, bool collectBindings, bool errorRecovery = false, list[loc] sourcePath = [], list[loc] classPath = [], str javaVersion = "1.7")`

.Synopsis
Creates AST from a file

.Description

[[AST-createAstFromString]]
## createAstFromString

.Function
`Declaration createAstFromString(loc fileName, str source, bool collectBinding, bool errorRecovery = false, list[loc] sourcePath = [], list[loc] classPath = [], str javaVersion = "1.7")`

Creates ASTs from an input string

[[AST-createAstsFromDirectory]]
## createAstsFromDirectory

.Function
`set[Declaration] createAstsFromDirectory(loc project, bool collectBindings, bool errorRecovery = false, str javaVersion = "1.7" )`

Creates ASTs from a project

:leveloffset: +1

:leveloffset: -1



[[m3-Core]]

[[m3-Core]]
# Core
:concept: Libraries/lang/java/m3/Core
.Usage
`import lang::java::m3::Core;`


.Synopsis
extends the M3 [$analysis/m3/Core] with Java specific concepts such as inheritance and overriding.

.Description

For a quick start, go find <<createM3FromEclipseProject>>.

[[Core-M3]]
## M3
.Types
[source,rascal]

data M3 ( rel[loc from, loc to] extends = {}, // classes extending classes and interfaces extending interfaces rel[loc from, loc to] implements = {}, // classes implementing interfaces rel[loc from, loc to] methodInvocation = {}, // methods calling each other (including constructors) rel[loc from, loc to] fieldAccess = {}, // code using data (like fields) rel[loc from, loc to] typeDependency = {}, // using a type literal in some code (types of variables, annotations) rel[loc from, loc to] methodOverrides = {}, // which method override which other methods rel[loc declaration, loc annotation] annotations = {} )

[[Core-Language]]
## Language
.Types
[source,rascal]

data Language (str version="") = java() ;

[[Core-composeJavaM3]]
## composeJavaM3

.Function
`M3 composeJavaM3(loc id, set[M3] models)`



[[Core-link]]
## link

.Function
`M3 link(M3 projectModel, set[M3] libraryModels)`



[[Core-createM3FromFile]]
## createM3FromFile

.Function
`M3 createM3FromFile(loc file, bool errorRecovery = false, list[loc] sourcePath = [], list[loc] classPath = [], str javaVersion = "1.7")`



[[Core-createM3sFromFiles]]
## createM3sFromFiles

.Function
`set[M3] createM3sFromFiles(set[loc] files, bool errorRecovery = false, list[loc] sourcePath = [], list[loc] classPath = [], str javaVersion = "1.7")`



[[Core-createM3FromFiles]]
## createM3FromFiles

.Function
`M3 createM3FromFiles(loc projectName, set[loc] files, bool errorRecovery = false, list[loc] sourcePath = [], list[loc] classPath = [], str javaVersion = "1.7")`



[[Core-createM3sAndAstsFromFiles]]
## createM3sAndAstsFromFiles

.Function
`tuple[set[M3], set[Declaration]] createM3sAndAstsFromFiles(set[loc] files, bool errorRecovery = false, list[loc] sourcePath = [], list[loc] classPath = [], str javaVersion = "1.7")`



[[Core-createM3FromString]]
## createM3FromString

.Function
`M3 createM3FromString(loc fileName, str contents, bool errorRecovery = false, list[loc] sourcePath = [], list[loc] classPath = [], str javaVersion = "1.7")`



[[Core-createM3FromJarClass]]
## createM3FromJarClass

.Function
`M3 createM3FromJarClass(loc jarClass)`



[[Core-createM3FromDirectory]]
## createM3FromDirectory

.Function
`M3 createM3FromDirectory(loc project, bool errorRecovery = false, str javaVersion = "1.7")`

.Synopsis
globs for jars, class files and java files in a directory and tries to compile all source files into an [$analysis/m3] model

[[Core-createM3FromJar]]
## createM3FromJar

.Function
`M3 createM3FromJar(loc jarFile)`



[[Core-classPathToStr]]
## classPathToStr

.Function
`str classPathToStr(loc jarClass)`



[[Core-isCompilationUnit]]
## isCompilationUnit

.Function
`bool isCompilationUnit(loc entity)`



[[Core-isPackage]]
## isPackage

.Function
`bool isPackage(loc entity)`



[[Core-isClass]]
## isClass

.Function
`bool isClass(loc entity)`



[[Core-isConstructor]]
## isConstructor

.Function
`bool isConstructor(loc entity)`



[[Core-isMethod]]
## isMethod

.Function
`bool isMethod(loc entity)`



[[Core-isParameter]]
## isParameter

.Function
`bool isParameter(loc entity)`



[[Core-isVariable]]
## isVariable

.Function
`bool isVariable(loc entity)`



[[Core-isField]]
## isField

.Function
`bool isField(loc entity)`



[[Core-isInterface]]
## isInterface

.Function
`bool isInterface(loc entity)`



[[Core-isEnum]]
## isEnum

.Function
`bool isEnum(loc entity)`



[[Core-files]]
## files

.Function
`set[loc] files(rel[loc, loc] containment)`



[[Core-declaredMethods]]
## declaredMethods

.Function
`rel[loc, loc] declaredMethods(M3 m, set[Modifier] checkModifiers = {})`



[[Core-declaredFields]]
## declaredFields

.Function
`rel[loc, loc] declaredFields(M3 m, set[Modifier] checkModifiers = {})`



[[Core-declaredFieldsX]]
## declaredFieldsX

.Function
`rel[loc, loc] declaredFieldsX(M3 m, set[Modifier] checkModifiers = {})`



[[Core-declaredTopTypes]]
## declaredTopTypes

.Function
`rel[loc, loc] declaredTopTypes(M3 m)`



[[Core-declaredSubTypes]]
## declaredSubTypes

.Function
`rel[loc, loc] declaredSubTypes(M3 m)`



[[Core-classes]]
## classes

.Function
`set[loc] classes(M3 m)`



[[Core-interfaces]]
## interfaces

.Function
`set[loc] interfaces(M3 m)`



[[Core-packages]]
## packages

.Function
`set[loc] packages(M3 m)`



[[Core-variables]]
## variables

.Function
`set[loc] variables(M3 m)`



[[Core-parameters]]
## parameters

.Function
`set[loc] parameters(M3 m)`



[[Core-fields]]
## fields

.Function
`set[loc] fields(M3 m)`



[[Core-methods]]
## methods

.Function
`set[loc] methods(M3 m)`



[[Core-constructors]]
## constructors

.Function
`set[loc] constructors(M3 m)`



[[Core-enums]]
## enums

.Function
`set[loc] enums(M3 m)`



[[Core-elements]]
## elements

.Function
`set[loc] elements(M3 m, loc parent)`



[[Core-fields]]
## fields

.Function
`set[loc] fields(M3 m, loc class)`



[[Core-methods]]
## methods

.Function
`set[loc] methods(M3 m, loc class)`



[[Core-constructors]]
## constructors

.Function
`set[loc] constructors(M3 m, loc class)`



[[Core-nestedClasses]]
## nestedClasses

.Function
`set[loc] nestedClasses(M3 m, loc class)`



:leveloffset: +1
<AUTOINSERTED>

[[Core-typeDependency]]
# typeDependency
:concept: Libraries/lang/java/m3/Core/typeDependency
.Types
[source,rascal]

anno rel[loc from, loc to] M3@typeDependency;

.Usage
</AUTOINSERTED>

:leveloffset: +1

:leveloffset: -1


:leveloffset: -1



[[m3-TypeHierarchy]]

[[m3-TypeHierarchy]]
# TypeHierarchy
:concept: Libraries/lang/java/m3/TypeHierarchy
.Usage
`import lang::java::m3::TypeHierarchy;`




[[TypeHierarchy-getDeclaredTypeHierarchy]]
## getDeclaredTypeHierarchy

.Function
`rel[loc from, loc to] getDeclaredTypeHierarchy(M3 model)`



:leveloffset: +1

:leveloffset: -1



[[m3-TypeSymbol]]

[[m3-TypeSymbol]]
# TypeSymbol
:concept: Libraries/lang/java/m3/TypeSymbol
.Usage
`import lang::java::m3::TypeSymbol;`




[[TypeSymbol-Bound]]
## Bound
.Types
[source,rascal]

data Bound = \super(list[TypeSymbol] bound) | \extends(list[TypeSymbol] bound) | \unbounded() ;

[[TypeSymbol-TypeSymbol]]
## TypeSymbol
.Types
[source,rascal]

data TypeSymbol = \class(loc decl, list[TypeSymbol] typeParameters) | \interface(loc decl, list[TypeSymbol] typeParameters) | \enum(loc decl) | \method(loc decl, list[TypeSymbol] typeParameters, TypeSymbol returnType, list[TypeSymbol] parameters) | \constructor(loc decl, list[TypeSymbol] parameters) | \typeParameter(loc decl, Bound upperbound) | \typeArgument(loc decl) | \wildcard(Bound bound) | \capture(Bound bound, TypeSymbol wildcard) | \intersection(list[TypeSymbol] types) | \union(list[TypeSymbol] types) | \object() | \int() | \float() | \double() | \short() | \boolean() | \char() | \byte() | \long() | \void() | \null() | \array(TypeSymbol component, int dimension) | \typeVariable(loc decl) | \unresolved() ;

[[TypeSymbol-subtype]]
## subtype

.Function
`default bool subtype(TypeSymbol s, TypeSymbol t)`



[[TypeSymbol-lub]]
## lub

.Function
`default TypeSymbol lub(TypeSymbol s, TypeSymbol t)`



:leveloffset: +1

:leveloffset: -1


:leveloffset: -1


:leveloffset: -1


[[lang-xml]]
# xml
:concept: Libraries/lang/xml
.Synopsis
XML utilities

.Description
http://en.wikipedia.org/wiki/XML[XML] is a widely used markup language for encoding and exchanging documents.

The following functions and datatypes are provided, all based on the Document Object Model (DOM):




:leveloffset: +1

:leveloffset: -1


:leveloffset: -1


[[Libraries-util]]
# util
:concept: Libraries/util

.Synopsis
Utilities: functions, data types and interfaces with external libraries.

.Description


** <<util-Benchmark,Benchmark>>: Functions for time measurement and benchmarking.
** <<util-Clipboard,Clipboard>>:
** <<util-ContentCompletion,ContentCompletion>>:
** <<util-Editors,Editors>>:
** <<util-Eval,Eval>>: Evaluate a (list of) Rascal commands and return the value of the last command.
** <<util-IDE,IDE>>:
** <<util-Math,Math>>: Mathematical functions.
** <<util-Monitor,Monitor>>: Monitor the progress of a task/job.
** <<util-ParseTreeUI,ParseTreeUI>>:
** <<util-PriorityQueue,PriorityQueue>>: A `PriorityQueue` datatype and associated functions.
** <<util-Prompt,Prompt>>:
** <<util-ResourceMarkers,ResourceMarkers>>:

:leveloffset: +1


[[util-Benchmark]]

[[util-Benchmark]]
# Benchmark
:concept: Libraries/util/Benchmark
.Usage
`import util::Benchmark;`


.Synopsis
Functions for time measurement and benchmarking.

.Description

The `Benchmark` library provides the following functions:

* <<Libraries/util/Benchmark-cpuTime,cpuTime>>: CPU time in nanoseconds (10^-9^ sec).
* <<Libraries/util/Benchmark-cpuTime,cpuTime>>:
* <<Libraries/util/Benchmark-systemTime,systemTime>>: System time in nanoseconds (10^-9^ sec).
* <<Libraries/util/Benchmark-systemTime,systemTime>>:
* <<Libraries/util/Benchmark-userTime,userTime>>: User time in nanoseconds (10^-9^ sec).
* <<Libraries/util/Benchmark-userTime,userTime>>:
* <<Libraries/util/Benchmark-realTime,realTime>>: Current time in milliseconds (10^-3^ sec).
* <<Libraries/util/Benchmark-realTime,realTime>>:
* <<Libraries/util/Benchmark-benchmark,benchmark>>: Measure and report the execution time of name:void-closure pairs
* <<Libraries/util/Benchmark-benchmark,benchmark>>:
* <<Libraries/util/Benchmark-getNanoTime,getNanoTime>>: Current time in nanoseconds (10^-9^ sec) since January 1, 1970 GMT.
* <<Libraries/util/Benchmark-getMilliTime,getMilliTime>>: Current time in milliseconds (10^-3^ sec) since January 1, 1970 GMT.
* <<Libraries/util/Benchmark-gc,gc>>: Force a garbage collection.


[[Benchmark-cpuTime]]
## cpuTime

.Function
* `int cpuTime()`
* `int cpuTime(void () block)`


.Synopsis
CPU time in nanoseconds (10^-9^ sec).

.Description

*  Current cpu time in __nanoseconds__ (10^-9^ sec) since the start of the thread that runs the code that calls this function.
*  The cpu time in nanoseconds used by the execution of the code `block`.

.Examples

We use the `fac` function described in link:/Recipes#Basic-Factorial[Factorial] as example:
[source,rascal-shell]

rascal>import util::Benchmark; ok rascal>import demo::basic::Factorial; ok

Here we measure time by using separate calls to `cpuTime` before and after a call to `fac`.
[source,rascal-shell]

rascal>before = cpuTime(); int: 147213715199 rascal>fac(50); int: 30414093201713378043612608166064768844377641568960512000000000000 rascal>cpuTime() - before; int: 88910750

The code to be measured can also be passed as a function parameter to `cpuTime`:
[source,rascal-shell]

rascal>cpuTime( void() { fac(50); } ); int: 349560

These two timings for the same task may differ significantly due to the way these statements are executed here in the tutor.

[[Benchmark-systemTime]]
## systemTime

.Function
* `int systemTime()`
* `int systemTime(void () block)`


.Synopsis
System time in nanoseconds (10^-9^ sec).

.Description

*  Current system time in nanoseconds (10^-9^ sec) since the start of the thread that runs the code that calls this function.
*  System time in nanoseconds needed to execute the code `block`.

.Examples
We use the `fac` function described in link:/Recipes#Basic-Factorial[Factorial] as example:
[source,rascal-shell]

rascal>import util::Benchmark; ok rascal>import demo::basic::Factorial; ok

Here we measure time by using separate calls to `sytemTime` before and after a call to `fac`.
[source,rascal-shell]

rascal>before = systemTime(); int: 1824395900 rascal>fac(50); int: 30414093201713378043612608166064768844377641568960512000000000000 rascal>systemTime() - before; int: 8412951

The code to be measured can also be passed as a function parameter to `systemTime`:
[source,rascal-shell]

rascal>systemTime( void() { fac(50); } ); int: 298343

[[Benchmark-userTime]]
## userTime

.Function
* `int userTime()`
* `int userTime(void () block)`


.Synopsis
User time in nanoseconds (10^-9^ sec).

.Description

*  Current time in __nanoseconds__ (10^-9^ sec) since the start of the thread that runs the code that calls this function.
*  User time in nanoseconds needed to execute the code `block`.

.Examples

We use the `fac` function described in link:/Recipes#Basic-Factorial[Factorial] as example:
[source,rascal-shell]

rascal>import util::Benchmark; ok rascal>import demo::basic::Factorial; ok

Here we measure time by using separate calls to `userTime` before and after a call to `fac`.
[source,rascal-shell]

rascal>before = userTime(); int: 145880000000 rascal>fac(50); int: 30414093201713378043612608166064768844377641568960512000000000000 rascal>userTime() - before; int: 90000000

The code to be measured can also be passed as a function parameter to `userTime`:
[source,rascal-shell]

rascal>userTime( void() { fac(50); } ); int: 0

[[Benchmark-realTime]]
## realTime

.Function
* `int realTime()`
* `int realTime(void () block)`


.Synopsis
Current time in milliseconds (10^-3^ sec).

.Description

*  Current system time in __milliseconds__ (10^-3^ sec) since January 1, 1970 GMT.
*  Real time in milliseconds needed to execute the code `block`.

.Pitfalls
This function is a competitor for the <<DateTime-now>> function that provides a
link:/Rascal#Values-Datetime[datetime] value for the current time.

[[Benchmark-benchmark]]
## benchmark

.Function
* `map[str,num] benchmark(map[str, void()] Cases)`
* `map[str,num] benchmark(map[str, void()] Cases, int (void ()) duration)`


.Synopsis
Measure and report the execution time of name:void-closure pairs

.Description

Given is a map that maps strings (used as label to identify each case) to void-closures that execute the code to be benchmarked.
An optional `duration` argument can be used to specify the function to perform the actual measurement. By default the function <<realTime>> is used. A map of labels and durations is returned.

.Examples
We use the `fac` function described in link:/Recipes#Basic-Factorial[Factorial] as example:
[source,rascal-shell]

rascal>import util::Benchmark; ok rascal>import demo::basic::Factorial; ok

We measure two calls to the factorial function with arguments `100`, respectively, `200`
(using by default <<realTime>> that returns milliseconds):
[source,rascal-shell]

rascal>benchmark( ("fac100" : void() {fac(100);}, "fac200" : void() {fac(200);}) ); map[str, int]: ("fac100":1498123965299,"fac200":1498123965299)

We can do the same using <<userTime>> that returns nanoseconds:
[source,rascal-shell]

rascal>benchmark( ("fac100" : void() {fac(100);}, "fac200" : void() {fac(200);}), userTime ); map[str, int]: ("fac100":146170000000,"fac200":146170000000)

[[Benchmark-getNanoTime]]
## getNanoTime

.Function
`int getNanoTime()`

.Synopsis
Current time in nanoseconds (10^-9^ sec) since January 1, 1970 GMT.
.Description

[[Benchmark-getMilliTime]]
## getMilliTime

.Function
`int getMilliTime()`

.Synopsis
Current time in milliseconds (10^-3^ sec) since January 1, 1970 GMT.

.Description
This function is a synonym for <<realTime>> and gives the wall clock time in milliseconds.

[[Benchmark-gc]]
## gc

.Function
`int gc()`

.Synopsis
Force a garbage collection.

.Description
This function forces a garbage collection and can, for instance, be used before running a benchmark.

:leveloffset: +1

:leveloffset: -1


[[util-Clipboard]]
# Clipboard
:concept: Libraries/util/Clipboard

WARNING: documentation awaits Eclipse integration

:leveloffset: +1

:leveloffset: -1


[[util-ContentCompletion]]
# ContentCompletion
:concept: Libraries/util/ContentCompletion

WARNING: documentation awaits Eclipse integration

:leveloffset: +1

:leveloffset: -1


[[util-Editors]]
# Editors
:concept: Libraries/util/Editors

WARNING: documentation awaits Eclipse integration

:leveloffset: +1

:leveloffset: -1



[[util-Eval]]

[[util-Eval]]
# Eval
:concept: Libraries/util/Eval
.Usage
`import util::Eval;`




[[Eval-Result]]
## Result
.Types
[source,rascal]

data Result[&T] = ok() | result(&T val) ;

[[Eval-Exception]]
## Exception
.Types
[source,rascal]

data Exception = StaticError(str message, loc location) ;

[[Eval-eval]]
## eval

.Function
* `Result[&T] eval(type[&T] typ, str command) throws Timeout, StaticError, ParseError`
* `Result[value] eval(str command)`
* `Result[&T] eval(type[&T] typ, list[str] commands) throws Timeout, StaticError, ParseError`
* `Result[value] eval(list[str] commands)`
* `Result[&T] eval(type[&T] typ, str command, int duration) throws Timeout, StaticError, ParseError`
* `Result[value] eval(str command, int duration)`
* `Result[&T] eval(type[&T] typ, list[str] commands, int duration) throws Timeout, StaticError, ParseError`
* `Result[value] eval(list[str] commands, int duration)`


.Synopsis
Evaluate a (list of) Rascal commands and return the value of the last command.

.Description
Evaluate a command or a list of commands and return the value of the last command that is executed.

Note that a command can be one of:

*  Statement
*  Declaration
*  Import
*  Extend
*  SyntaxDefinition


The notable exclusion are <<Expressions>>. An Expression is not allowed as a command to the eval function. You can easily make
a Statement from an Expression by adding a semi-colon.

An optional `duration` argument may be present to limit the time
(in milliseconds) the execution may take. By default, the duration is set to 1000 ms.

.Examples

[source,rascal-shell]

rascal>import util::Eval; ok rascal>eval("2 * 3;"); java.lang.NullPointerException at org.rascalmpl.library.util.Eval.getSharedEvaluator(Eval.java:79) at org.rascalmpl.library.util.Eval.eval(Eval.java:101) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RVMCore.callJavaMethod(RVMCore.java:1179) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RVMonJVM.insnCALLJAVA(RVMonJVM.java:407) at .ConsoleInput$Compiled.util::Eval\eval(reified(parameter("T",value())(@boundGiven=false)):str():)#23(Unknown Source) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RVMonJVM.jvmOCALL(RVMonJVM.java:794) at .ConsoleInput$Compiled.util::Eval\eval(str():)#61(Unknown Source) at .ConsoleInput$Compiled.ConsoleInput\main()#0(Unknown Source) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RVMonJVM.dynRun(RVMonJVM.java:543) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RVMonJVM.executeRVMProgram(RVMonJVM.java:239) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RVMJVM.executeRVMProgram(RVMJVM.java:137) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.ExecutionTools.executeProgram(ExecutionTools.java:142) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.ExecutionTools.executeProgram(ExecutionTools.java:101) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.repl.CommandExecutor.executeModule(CommandExecutor.java:387) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.repl.CommandExecutor.evalStatement(CommandExecutor.java:520) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.repl.CommandExecutor.eval(CommandExecutor.java:441) at org.rascalmpl.library.experiments.tutor3.TutorCommandExecutor.evalPrint(TutorCommandExecutor.java:75) at org.rascalmpl.library.experiments.tutor3.Concept.preprocess(Concept.java:264) at org.rascalmpl.library.experiments.tutor3.Onthology.<init>(Onthology.java:131) at org.rascalmpl.library.experiments.tutor3.CourseCompiler.compileCourse(CourseCompiler.java:92) at org.rascalmpl.library.experiments.tutor3.CourseCompiler.main(CourseCompiler.java:258) An unexpected internal error occurred: java.lang.RuntimeException: java.lang.RuntimeException: org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.InternalCompilerError: Exception in CALLJAVA: org.rascalmpl.library.util.Eval.eval; message: nullnull at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RVMonJVM.dynRun(RVMonJVM.java:548) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RVMonJVM.executeRVMProgram(RVMonJVM.java:239) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RVMJVM.executeRVMProgram(RVMJVM.java:137) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.ExecutionTools.executeProgram(ExecutionTools.java:142) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.ExecutionTools.executeProgram(ExecutionTools.java:101) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.repl.CommandExecutor.executeModule(CommandExecutor.java:387) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.repl.CommandExecutor.evalStatement(CommandExecutor.java:520) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.repl.CommandExecutor.eval(CommandExecutor.java:441) at org.rascalmpl.library.experiments.tutor3.TutorCommandExecutor.evalPrint(TutorCommandExecutor.java:75) at org.rascalmpl.library.experiments.tutor3.Concept.preprocess(Concept.java:264) at org.rascalmpl.library.experiments.tutor3.Onthology.<init>(Onthology.java:131) at org.rascalmpl.library.experiments.tutor3.CourseCompiler.compileCourse(CourseCompiler.java:92) at org.rascalmpl.library.experiments.tutor3.CourseCompiler.main(CourseCompiler.java:258) Caused by: java.lang.RuntimeException: org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.InternalCompilerError: Exception in CALLJAVA: org.rascalmpl.library.util.Eval.eval; message: nullnull at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RVMonJVM.jvmOCALL(RVMonJVM.java:802) at .ConsoleInput$Compiled.util::Eval\eval(str():)#61(Unknown Source) at .ConsoleInput$Compiled.ConsoleInput\main()#0(Unknown Source) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RVMonJVM.dynRun(RVMonJVM.java:543) …​ 12 more Caused by: org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.InternalCompilerError: Exception in CALLJAVA: org.rascalmpl.library.util.Eval.eval; message: nullnull at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RVMonJVM.insnCALLJAVA(RVMonJVM.java:422) at .ConsoleInput$Compiled.util::Eval\eval(reified(parameter("T",value())(@boundGiven=false)):str():)#23(Unknown Source) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RVMonJVM.jvmOCALL(RVMonJVM.java:794) …​ 15 more Caused by: java.lang.NullPointerException at org.rascalmpl.library.util.Eval.getSharedEvaluator(Eval.java:79) at org.rascalmpl.library.util.Eval.eval(Eval.java:101) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RVMCore.callJavaMethod(RVMCore.java:1179) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RVMonJVM.insnCALLJAVA(RVMonJVM.java:407) …​ 17 more rascal>eval(["X = 2 * 3;", "X + 5;"]); java.lang.NullPointerException at org.rascalmpl.library.util.Eval.getSharedEvaluator(Eval.java:79) at org.rascalmpl.library.util.Eval.eval(Eval.java:119) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RVMCore.callJavaMethod(RVMCore.java:1179) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RVMonJVM.insnCALLJAVA(RVMonJVM.java:407) at .ConsoleInput$Compiled.util::Eval\eval(reified(parameter("T",value())(@boundGiven=false)):list(str()):)#64(Unknown Source) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RVMonJVM.jvmOCALL(RVMonJVM.java:794) at .ConsoleInput$Compiled.util::Eval\eval(list(str()):)#67(Unknown Source) at .ConsoleInput$Compiled.ConsoleInput\main()#0(Unknown Source) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RVMonJVM.dynRun(RVMonJVM.java:543) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RVMonJVM.executeRVMProgram(RVMonJVM.java:239) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RVMJVM.executeRVMProgram(RVMJVM.java:137) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.ExecutionTools.executeProgram(ExecutionTools.java:142) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.ExecutionTools.executeProgram(ExecutionTools.java:101) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.repl.CommandExecutor.executeModule(CommandExecutor.java:387) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.repl.CommandExecutor.evalStatement(CommandExecutor.java:520) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.repl.CommandExecutor.eval(CommandExecutor.java:441) at org.rascalmpl.library.experiments.tutor3.TutorCommandExecutor.evalPrint(TutorCommandExecutor.java:75) at org.rascalmpl.library.experiments.tutor3.Concept.preprocess(Concept.java:264) at org.rascalmpl.library.experiments.tutor3.Onthology.<init>(Onthology.java:131) at org.rascalmpl.library.experiments.tutor3.CourseCompiler.compileCourse(CourseCompiler.java:92) at org.rascalmpl.library.experiments.tutor3.CourseCompiler.main(CourseCompiler.java:258) An unexpected internal error occurred: java.lang.RuntimeException: java.lang.RuntimeException: org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.InternalCompilerError: Exception in CALLJAVA: org.rascalmpl.library.util.Eval.eval; message: nullnull at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RVMonJVM.dynRun(RVMonJVM.java:548) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RVMonJVM.executeRVMProgram(RVMonJVM.java:239) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RVMJVM.executeRVMProgram(RVMJVM.java:137) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.ExecutionTools.executeProgram(ExecutionTools.java:142) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.ExecutionTools.executeProgram(ExecutionTools.java:101) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.repl.CommandExecutor.executeModule(CommandExecutor.java:387) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.repl.CommandExecutor.evalStatement(CommandExecutor.java:520) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.repl.CommandExecutor.eval(CommandExecutor.java:441) at org.rascalmpl.library.experiments.tutor3.TutorCommandExecutor.evalPrint(TutorCommandExecutor.java:75) at org.rascalmpl.library.experiments.tutor3.Concept.preprocess(Concept.java:264) at org.rascalmpl.library.experiments.tutor3.Onthology.<init>(Onthology.java:131) at org.rascalmpl.library.experiments.tutor3.CourseCompiler.compileCourse(CourseCompiler.java:92) at org.rascalmpl.library.experiments.tutor3.CourseCompiler.main(CourseCompiler.java:258) Caused by: java.lang.RuntimeException: org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.InternalCompilerError: Exception in CALLJAVA: org.rascalmpl.library.util.Eval.eval; message: nullnull at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RVMonJVM.jvmOCALL(RVMonJVM.java:802) at .ConsoleInput$Compiled.util::Eval\eval(list(str()):)#67(Unknown Source) at .ConsoleInput$Compiled.ConsoleInput\main()#0(Unknown Source) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RVMonJVM.dynRun(RVMonJVM.java:543) …​ 12 more Caused by: org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.InternalCompilerError: Exception in CALLJAVA: org.rascalmpl.library.util.Eval.eval; message: nullnull at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RVMonJVM.insnCALLJAVA(RVMonJVM.java:422) at .ConsoleInput$Compiled.util::Eval\eval(reified(parameter("T",value())(@boundGiven=false)):list(str()):)#64(Unknown Source) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RVMonJVM.jvmOCALL(RVMonJVM.java:794) …​ 15 more Caused by: java.lang.NullPointerException at org.rascalmpl.library.util.Eval.getSharedEvaluator(Eval.java:79) at org.rascalmpl.library.util.Eval.eval(Eval.java:119) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RVMCore.callJavaMethod(RVMCore.java:1179) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RVMonJVM.insnCALLJAVA(RVMonJVM.java:407) …​ 17 more

[[Eval-evalType]]
## evalType

.Function
* `str evalType(str command) throws Timeout, StaticError, ParseError`
* `str evalType(list[str] commands) throws Timeout, StaticError, ParseError`
* `str evalType(str command, int duration) throws Timeout, StaticError, ParseError`
* `str evalType(list[str] commands, int duration) throws Timeout, StaticError, ParseError`


.Synopsis
Evaluate a (list of) Rascal commands and return the type of the last command.

.Description
Evaluate a command or a list of commands and return the type of the value of the last command that is executed.
An optional `duration` argument may be present to limit the time
(in milliseconds) the execution may take. By default, the duration is set to 1000 ms.

.Examples
[source,rascal-shell]

rascal>import util::Eval; ok rascal>evalType("2 * 3;"); java.lang.NullPointerException at org.rascalmpl.library.util.Eval.getSharedEvaluator(Eval.java:79) at org.rascalmpl.library.util.Eval.evalType(Eval.java:129) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RVMCore.callJavaMethod(RVMCore.java:1179) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RVMonJVM.insnCALLJAVA(RVMonJVM.java:407) at .ConsoleInput$Compiled.util::Eval\evalType(str():)#84(Unknown Source) at .ConsoleInput$Compiled.ConsoleInput\main()#0(Unknown Source) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RVMonJVM.dynRun(RVMonJVM.java:543) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RVMonJVM.executeRVMProgram(RVMonJVM.java:239) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RVMJVM.executeRVMProgram(RVMJVM.java:137) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.ExecutionTools.executeProgram(ExecutionTools.java:142) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.ExecutionTools.executeProgram(ExecutionTools.java:101) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.repl.CommandExecutor.executeModule(CommandExecutor.java:387) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.repl.CommandExecutor.evalStatement(CommandExecutor.java:520) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.repl.CommandExecutor.eval(CommandExecutor.java:441) at org.rascalmpl.library.experiments.tutor3.TutorCommandExecutor.evalPrint(TutorCommandExecutor.java:75) at org.rascalmpl.library.experiments.tutor3.Concept.preprocess(Concept.java:264) at org.rascalmpl.library.experiments.tutor3.Onthology.<init>(Onthology.java:131) at org.rascalmpl.library.experiments.tutor3.CourseCompiler.compileCourse(CourseCompiler.java:92) at org.rascalmpl.library.experiments.tutor3.CourseCompiler.main(CourseCompiler.java:258) An unexpected internal error occurred: java.lang.RuntimeException: org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.InternalCompilerError: Exception in CALLJAVA: org.rascalmpl.library.util.Eval.evalType; message: nullnull at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RVMonJVM.dynRun(RVMonJVM.java:548) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RVMonJVM.executeRVMProgram(RVMonJVM.java:239) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RVMJVM.executeRVMProgram(RVMJVM.java:137) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.ExecutionTools.executeProgram(ExecutionTools.java:142) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.ExecutionTools.executeProgram(ExecutionTools.java:101) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.repl.CommandExecutor.executeModule(CommandExecutor.java:387) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.repl.CommandExecutor.evalStatement(CommandExecutor.java:520) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.repl.CommandExecutor.eval(CommandExecutor.java:441) at org.rascalmpl.library.experiments.tutor3.TutorCommandExecutor.evalPrint(TutorCommandExecutor.java:75) at org.rascalmpl.library.experiments.tutor3.Concept.preprocess(Concept.java:264) at org.rascalmpl.library.experiments.tutor3.Onthology.<init>(Onthology.java:131) at org.rascalmpl.library.experiments.tutor3.CourseCompiler.compileCourse(CourseCompiler.java:92) at org.rascalmpl.library.experiments.tutor3.CourseCompiler.main(CourseCompiler.java:258) Caused by: org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.InternalCompilerError: Exception in CALLJAVA: org.rascalmpl.library.util.Eval.evalType; message: nullnull at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RVMonJVM.insnCALLJAVA(RVMonJVM.java:422) at .ConsoleInput$Compiled.util::Eval\evalType(str():)#84(Unknown Source) at .ConsoleInput$Compiled.ConsoleInput\main()#0(Unknown Source) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RVMonJVM.dynRun(RVMonJVM.java:543) …​ 12 more Caused by: java.lang.NullPointerException at org.rascalmpl.library.util.Eval.getSharedEvaluator(Eval.java:79) at org.rascalmpl.library.util.Eval.evalType(Eval.java:129) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RVMCore.callJavaMethod(RVMCore.java:1179) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RVMonJVM.insnCALLJAVA(RVMonJVM.java:407) …​ 15 more rascal>evalType("[1, 2, 3];"); java.lang.NullPointerException at org.rascalmpl.library.util.Eval.getSharedEvaluator(Eval.java:79) at org.rascalmpl.library.util.Eval.evalType(Eval.java:129) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RVMCore.callJavaMethod(RVMCore.java:1179) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RVMonJVM.insnCALLJAVA(RVMonJVM.java:407) at .ConsoleInput$Compiled.util::Eval\evalType(str():)#84(Unknown Source) at .ConsoleInput$Compiled.ConsoleInput\main()#0(Unknown Source) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RVMonJVM.dynRun(RVMonJVM.java:543) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RVMonJVM.executeRVMProgram(RVMonJVM.java:239) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RVMJVM.executeRVMProgram(RVMJVM.java:137) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.ExecutionTools.executeProgram(ExecutionTools.java:142) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.ExecutionTools.executeProgram(ExecutionTools.java:101) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.repl.CommandExecutor.executeModule(CommandExecutor.java:387) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.repl.CommandExecutor.evalStatement(CommandExecutor.java:520) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.repl.CommandExecutor.eval(CommandExecutor.java:441) at org.rascalmpl.library.experiments.tutor3.TutorCommandExecutor.evalPrint(TutorCommandExecutor.java:75) at org.rascalmpl.library.experiments.tutor3.Concept.preprocess(Concept.java:264) at org.rascalmpl.library.experiments.tutor3.Onthology.<init>(Onthology.java:131) at org.rascalmpl.library.experiments.tutor3.CourseCompiler.compileCourse(CourseCompiler.java:92) at org.rascalmpl.library.experiments.tutor3.CourseCompiler.main(CourseCompiler.java:258) An unexpected internal error occurred: java.lang.RuntimeException: org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.InternalCompilerError: Exception in CALLJAVA: org.rascalmpl.library.util.Eval.evalType; message: nullnull at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RVMonJVM.dynRun(RVMonJVM.java:548) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RVMonJVM.executeRVMProgram(RVMonJVM.java:239) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RVMJVM.executeRVMProgram(RVMJVM.java:137) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.ExecutionTools.executeProgram(ExecutionTools.java:142) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.ExecutionTools.executeProgram(ExecutionTools.java:101) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.repl.CommandExecutor.executeModule(CommandExecutor.java:387) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.repl.CommandExecutor.evalStatement(CommandExecutor.java:520) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.repl.CommandExecutor.eval(CommandExecutor.java:441) at org.rascalmpl.library.experiments.tutor3.TutorCommandExecutor.evalPrint(TutorCommandExecutor.java:75) at org.rascalmpl.library.experiments.tutor3.Concept.preprocess(Concept.java:264) at org.rascalmpl.library.experiments.tutor3.Onthology.<init>(Onthology.java:131) at org.rascalmpl.library.experiments.tutor3.CourseCompiler.compileCourse(CourseCompiler.java:92) at org.rascalmpl.library.experiments.tutor3.CourseCompiler.main(CourseCompiler.java:258) Caused by: org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.InternalCompilerError: Exception in CALLJAVA: org.rascalmpl.library.util.Eval.evalType; message: nullnull at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RVMonJVM.insnCALLJAVA(RVMonJVM.java:422) at .ConsoleInput$Compiled.util::Eval\evalType(str():)#84(Unknown Source) at .ConsoleInput$Compiled.ConsoleInput\main()#0(Unknown Source) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RVMonJVM.dynRun(RVMonJVM.java:543) …​ 12 more Caused by: java.lang.NullPointerException at org.rascalmpl.library.util.Eval.getSharedEvaluator(Eval.java:79) at org.rascalmpl.library.util.Eval.evalType(Eval.java:129) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RVMCore.callJavaMethod(RVMCore.java:1179) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RVMonJVM.insnCALLJAVA(RVMonJVM.java:407) …​ 15 more

[[Eval-unimport]]
## unimport

.Function
`void unimport(str muduleName)`



:leveloffset: +1

:leveloffset: -1


[[util-IDE]]
# IDE
:concept: Libraries/util/IDE

WARNING: documentation awaits Eclipse integration

:leveloffset: +1

:leveloffset: -1



[[util-Math]]

[[util-Math]]
# Math
:concept: Libraries/util/Math
.Usage
`import util::Math;`


.Synopsis
Mathematical functions.

.Usage

.Description

The `Math` library provides the following functions:


* <<Libraries/util/Math-abs,abs>>: Absolute value of a number.
* <<Libraries/util/Math-arbInt,arbInt>>: Generate a random integer value.
* <<Libraries/util/Math-arbInt,arbInt>>:
* <<Libraries/util/Math-arbReal,arbReal>>: Generate a random real value in the interval [0.0,1.0).
* <<Libraries/util/Math-arbSeed,arbSeed>>: Define the seed for the generation of arbitrary values.
* <<Libraries/util/Math-arbRat,arbRat>>: Generate an arbitrary rational value.
* <<Libraries/util/Math-arbRat,arbRat>>:
* <<Libraries/util/Math-ceil,ceil>>: Compute the smallest integer that is larger than a given number.
* <<Libraries/util/Math-cos,cos>>: Calculate the cosine of a numeric value.
* <<Libraries/util/Math-denominator,denominator>>: Return the denominator of a rational value
* <<Libraries/util/Math-E,E>>: The constant E.
* <<Libraries/util/Math-exp,exp>>: Compute exp(x).
* <<Libraries/util/Math-floor,floor>>: Compute the largest integer that is smaller than a given number.
* <<Libraries/util/Math-ln,ln>>: Calculate the natural log of a numeric value.
* <<Libraries/util/Math-log,log>>: Calculate the log<sub>base</sub> of a numeric value.
* <<Libraries/util/Math-log10,log10>>: Compute the 10 based log(x)
* <<Libraries/util/Math-log2,log2>>: Compute the 2 based log(x)
* <<Libraries/util/Math-max,max>>: Determine the largest of two numeric values.
* <<Libraries/util/Math-min,min>>: Determine the smallest of two numeric values.
* <<Libraries/util/Math-numerator,numerator>>: Return the numerator of a rational value
* <<Libraries/util/Math-nroot,nroot>>: Calculate the n<sup>th</sup> root of a numeric value.
* <<Libraries/util/Math-PI,PI>>: The constant pi.
* <<Libraries/util/Math-pow,pow>>: Calculate an arbitrary power of a numeric value.
* <<Libraries/util/Math-pow,pow>>: Calculate an arbitrary power of a numeric value.
* <<Libraries/util/Math-precision,precision>>: Return the precision of a real number
* <<Libraries/util/Math-precision,precision>>: Return a real number with given precisio
* <<Libraries/util/Math-setPrecision,setPrecision>>: Define the precision for numeric calculations; returns the previous precision
* <<Libraries/util/Math-scale,scale>>: Return the scale of a real number
* <<Libraries/util/Math-unscaled,unscaled>>: Return the unscaled integer of a real
* <<Libraries/util/Math-remainder,remainder>>: Return the remainder of dividing the numerator by the denominator
* <<Libraries/util/Math-round,round>>: Round a number to the nearest multiple of a given number (default 1).
* <<Libraries/util/Math-round,round>>:
* <<Libraries/util/Math-percent,percent>>: Compute the ratio between two numbers as a percentage.
* <<Libraries/util/Math-sin,sin>>: Calculate the sine of a numeric value.
* <<Libraries/util/Math-sqrt,sqrt>>: Calculate the square root of a numeric value.
* <<Libraries/util/Math-tan,tan>>: Calculate the tangent of a numeric value.
* <<Libraries/util/Math-toInt,toInt>>: Convert a numeric value to an integer.
* <<Libraries/util/Math-toRat,toRat>>: Convert two numbers to a rational value (not supported on reals)
* <<Libraries/util/Math-toReal,toReal>>: Convert a numeric value to a real.
* <<Libraries/util/Math-toString,toString>>: Convert a numeric value to a string.
* <<Libraries/util/Math-primes,primes>>: generate prime numbers up to a maximu
* <<Libraries/util/Math-arbPrime,arbPrime>>:


[[Math-abs]]
## abs

.Function
`&T <: num abs(&T <: num N)`

.Synopsis
Absolute value of a number.

.Description
Absolute value of the number `n`. The result type is equal to the type of the argument `n`.

.Examples
[source,rascal-shell]

rascal>import util::Math; ok rascal>abs(13) int: 13 rascal>abs(-13) int: 13 rascal>abs(3.14) real: 3.14 rascal>abs(-3.14) real: 3.14

[[Math-arbInt]]
## arbInt

.Function
* `int arbInt()`
* `int arbInt(int limit)`


.Synopsis
Generate a random integer value.

.Description
Return an arbitrary integer value. When the argument `limit` is given, the generated value is in the interval [0, `limit`),
i.e., the limit is exclusive.

.Examples
[source,rascal-shell]

rascal>import util::Math; ok rascal>arbInt(); int: 1476819178 rascal>arbInt(); int: 287390617 rascal>arbInt(); int: -1119930153 rascal>arbInt(10); int: 9 rascal>arbInt(10); int: 5 rascal>arbInt(10); int: 5

.Benefits
`arbInt` is a convenient generator for pseudo-random integers.

[[Math-arbReal]]
## arbReal

.Function
`real arbReal()`

.Synopsis
Generate a random real value in the interval [0.0,1.0).

.Description
Generates an arbitrary real value in the interval [0.0, 1.0].

.Examples
[source,rascal-shell]

rascal>import util::Math; ok rascal>arbReal(); real: 0.7976332436968523 rascal>arbReal(); real: 0.12004126549184302 rascal>arbReal(); real: 0.6847512794939378

[[Math-arbSeed]]
## arbSeed

.Function
`void arbSeed(int seed)`

.Synopsis
Define the seed for the generation of arbitrary values.

.Description
Define the seed for the generation of arbitrary values such as <<arbBool>>, <<arbInt>>, <<arbReal>>,
<<arbRat>>, <<List-getOneFrom>>,<<Set-getOneFrom>>, <<List-takeOneFrom>> and <<Set-takeOneFrom>>. <<arbSeed>> resets the random number generator that
is used to choose arbitrary values. This can be used to generate a reproducible series of choices.

[[Math-arbRat]]
## arbRat

.Function
* `rat arbRat()`
* `rat arbRat(int limit1, int limit2)`


.Synopsis
Generate an arbitrary rational value.

.Examples
[source,rascal-shell]

rascal>import util::Math; ok rascal>arbRat(); rat: 1633344167r88521548 rascal>arbRat(); rat: -1837373037r1882291135 rascal>arbRat(); rat: 221949026r572494885 rascal>arbRat(10,100); rat: 0r rascal>arbRat(10,100); rat: 5r16 rascal>arbRat(10,100); rat: 3r85

[[Math-ceil]]
## ceil

.Function
`int ceil(num x)`

.Synopsis
Compute the smallest integer that is larger than a given number.

.Description
Computes the _ceiling_ of a given number.
Also see <<Math-floor>>.

.Examples
[source,rascal-shell]

rascal>import util::Math; ok rascal>ceil(3.2); int: 4 rascal>ceil(-3.2); int: -3

[[Math-cos]]
## cos

.Function
`real cos(num x)`

.Synopsis
Calculate the cosine of a numeric value.

.Description
The cosine of the number `x`.

.Examples
[source,rascal-shell]

rascal>import util::Math; ok rascal>cos(1.0) real: 0.54030230588 rascal>cos(60 * PI() / 180) real: 0.50000000000

[[Math-denominator]]
## denominator

.Function
`int denominator(rat n)`

.Synopsis
Return the denominator of a rational value.

[[Math-E]]
## E

.Function
`real E()`

.Synopsis
The constant E.

.Examples
[source,rascal-shell]

rascal>import util::Math; ok rascal>E(); real: 2.7182818285

[[Math-exp]]
## exp

.Function
`real exp(num x)`

.Synopsis
Compute exp(x).
.Description
Calculate `e`<sup>`x`</sup>.

[[Math-floor]]
## floor

.Function
`int floor(num x)`

.Synopsis
Compute the largest integer that is smaller than a given number.

.Description
Computes the _floor_ of a given number.
Also see <<Math-ceil>>.

.Examples
[source,rascal-shell]

rascal>import util::Math; ok rascal>floor(3.2); int: 3 rascal>floor(-3.2); int: -4

[[Math-ln]]
## ln

.Function
`real ln(num x)`

.Synopsis
Calculate the natural log of a numeric value.

.Description
Calculate natural log of `x`.

.Examples
[source,rascal-shell]

rascal>import util::Math; ok rascal>ln(20.0) real: 2.9957322736 rascal>ln(42.0) real: 3.7376696183

[[Math-log]]
## log

.Function
`real log(num x, num base)`

.Synopsis
Calculate the log<sub>base</sub> of a numeric value.

.Description
Calculate log<sub>base</sub> of `x`.

.Examples
[source,rascal-shell]

rascal>import util::Math; ok rascal>log(9.99999999, 10) real: 0.999999999566 rascal>log(10, 10) real: 1. rascal>log(256.0, 2) real: 7.99999999999

[[Math-log10]]
## log10

.Function
`real log10(num x)`

.Synopsis
Compute the 10 based log(x).

[[Math-log2]]
## log2

.Function
`real log2(num x)`

.Synopsis
Compute the 2 based log(x).

[[Math-max]]
## max

.Function
`&T <: num max(&T <: num N, &T <: num M)`

.Synopsis
Determine the largest of two numeric values.

.Description
The largest of two numbers. The type of the result is the same as the type of the largest argument.

.Examples
[source,rascal-shell]

rascal>import util::Math; ok rascal>max(12, 13); int: 13 rascal>max(12, 13.5); real: 13.5 rascal>max(12, 11.5); int: 12

[[Math-min]]
## min

.Function
`&T <: num min(&T <: num N, &T <: num M)`

.Synopsis
Determine the smallest of two numeric values.

.Description
The smallest of two numbers. The type of the result is the same as the type of the smallest argument.

.Examples
[source,rascal-shell]

rascal>import util::Math; ok rascal>min(12, 13); int: 12 rascal>min(12, -13); int: -13 rascal>min(3.14, 4); real: 3.14

[[Math-numerator]]
## numerator

.Function
`int numerator(rat n)`

.Synopsis
Return the numerator of a rational value.

[[Math-nroot]]
## nroot

.Function
`real nroot(num x, int n)`

.Synopsis
Calculate the n<sup>th</sup> root of a numeric value.

.Description
Calculate <sup>n</sup>&radic;`x` where `n` can only be a integer.

.Examples
[source,rascal-shell]

rascal>import util::Math; ok rascal>nroot(42 * 42, 2); real: 42.0000000000 rascal>nroot(42 * 42 * 42, 3); real: 42.0000000000 rascal>nroot(123456789012345678901234567890123456789.0, 100) real: 2.4038930938

[[Math-PI]]
## PI

.Function
`real PI()`

.Synopsis
The constant pi.

.Examples
[source,rascal-shell]

rascal>import util::Math; ok rascal>PI(); real: 3.1415926536

[[Math-pow]]
## pow

.Function
* `real pow(num x, int y)`
* `real pow(num x, real y)`


.Synopsis
Calculate an arbitrary power of a numeric value.

.Description
The calculate `x`<sup>`y`</sup> where `y` can only be a integer.

.Examples
[source,rascal-shell]

rascal>import util::Math; ok rascal>pow(sqrt(42), 2) real: 41.99999999989811976256 rascal>pow(12345678901234567890.0, 1000) real: 327323519862176629730082067574716643439462300540185122220961832511288805718030910484304325108222843885957688250811158315340566475836232001571619541935415038796348602192296984423155079801992333140052863080750492018420590783574245411031311510942905796189450351912614510641741094491709589411239576756065619918176653289948094430880732479266853021246187981170634861333302200580872985856560855518977488511675544145006801675791138351985746678734387422142342185164278661836498313416561398901718399810114596984172777042303963800096899625199810241300878005585014082782334502894938457546968837522885101157892509894692459561354313786780532679517827353604060468681961209174542267424246240853816845886755294209996435433895294269712878992262721644106226890031664370462222706979715904672586297266460593551184450504665032451235999357222433465060299295477020462819514888057483551478759508444976793225466736775132290553092049866427876353526626065630474037490603570383940996843823967040247622022658439400707006053650592894261198654836654639504753542843560398908885522596433160079097075880850067383018892541529465995345763588872837837593907229770700976597566733884202506653739605059379401347861288230399126563406134764726379055786459406660737522798066830604288612726394086519909309338994703718119693639450620275447776806553594104597194048560725083279242120977189767528195495335507571774589656293544257012451347889004221446663952536972136269481724663158860532924322053397767933001924701437115740854657082984585991651836842…​

[[Math-precision]]
## precision

.Function
* `int precision(num x)`
* `real precision(num x, int p)`


.Synopsis
Return the precision of a real number.

[[Math-setPrecision]]
## setPrecision

.Function
`int setPrecision(int p)`

.Synopsis
Define the precision for numeric calculations; returns the previous precision.

[[Math-scale]]
## scale

.Function
`int scale(num x)`

.Synopsis
Return the scale of a real number.

[[Math-unscaled]]
## unscaled

.Function
`int unscaled(real x)`

.Synopsis
Return the unscaled integer of a real.

[[Math-remainder]]
## remainder

.Function
`int remainder(rat n)`

.Synopsis
Return the remainder of dividing the numerator by the denominator.

[[Math-round]]
## round

.Function
* `int round(num d)`
* `(&T <: num) round(&T <: num r, &T <: num nearest)`


.Synopsis
Round a number to the nearest multiple of a given number (default 1).

.Examples
[source,rascal-shell]

rascal>import util::Math; ok rascal>round(3.4); int: 3 rascal>round(3.5); int: 4 rascal>round(3.6); int: 4 rascal>round(-3.4); int: -3 rascal>round(-3.5); int: -4 rascal>round(-3.6); int: -4 rascal>round(13, 5); int: 15 rascal>round(1.5,0.2); real: 1.6 rascal>round(3r2,1r4); rat: 3r2

[[Math-percent]]
## percent

.Function
`int percent(num part, num whole)`

.Synopsis
Compute the ratio between two numbers as a percentage.

.Examples
[source,rascal-shell]

rascal>import util::Math; ok rascal>percent(1r4, 1); int: 25 rascal>percent(13,250); int: 5 rascal>percent(80.0,160.0); int: 50

[[Math-sin]]
## sin

.Function
`real sin(num x)`

.Synopsis
Calculate the sine of a numeric value.

.Description
The sine of the number `x`.

.Examples
[source,rascal-shell]

rascal>import util::Math; ok rascal>sin(0) real: 0. rascal>sin(PI() / 2) real: 1.00000000000

[[Math-sqrt]]
## sqrt

.Function
`real sqrt(num x)`

.Synopsis
Calculate the square root of a numeric value.

.Description
Calculate &radic;`x`.

.Examples
[source,rascal-shell]

rascal>import util::Math; ok rascal>sqrt(42 * 42); real: 42.0000000000 rascal>sqrt(12345678901234567890.5 * 12345678901234567890.5); real: 12345678901234567890.5000000000

[[Math-tan]]
## tan

.Function
`real tan(num x)`

.Synopsis
Calculate the tangent of a numeric value.

.Description
The tangent of the number `x`.

.Examples
[source,rascal-shell]

rascal>import util::Math; ok rascal>tan(45 * PI() / 180) real: 1.0000000000

[[Math-toInt]]
## toInt

.Function
`int toInt(num N)`

.Synopsis
Convert a numeric value to an integer.

.Description
Convert a number to an integer. If `n` is an integer, this is the identity. If `n` is a real value (implemented as BigDecimal) to an integer (implemented as BigInteger). This conversion is analogous to a narrowing primitive conversion from double to long as defined in the Java Language Specification: any fractional part of this BigDecimal will be discarded. Note that this conversion can loose information about the precision of the BigDecimal value.

.Examples
[source,rascal-shell]

rascal>import util::Math; ok rascal>toInt(13) int: 13 rascal>toInt(13.5) int: 13

[[Math-toRat]]
## toRat

.Function
`rat toRat(int numerator, int denominator)`

.Synopsis
Convert two numbers to a rational value (not supported on reals).

[[Math-toReal]]
## toReal

.Function
`real toReal(num N)`

.Synopsis
Convert a numeric value to a real.

.Examples
[source,rascal-shell]

rascal>import util::Math; ok rascal>toReal(12) real: 12. rascal>toReal(3.14) real: 3.14

[[Math-toString]]
## toString

.Function
`str toString(num N)`

.Synopsis
Convert a numeric value to a string.

.Examples
[source,rascal-shell]

rascal>import util::Math; ok rascal>toString(12) str: "12" rascal>toString(3.14) str: "3.14"

[[Math-primes]]
## primes

.Function
`list[int] primes(int upTo)`

.Synopsis
generate prime numbers up to a maximum

[[Math-arbPrime]]
## arbPrime

.Function
`int arbPrime(int upTo)`



:leveloffset: +1

:leveloffset: -1



[[util-Monitor]]

[[util-Monitor]]
# Monitor
:concept: Libraries/util/Monitor
.Usage
`import util::Monitor;`


.Synopsis
Monitor the progress of a task/job.

[[Monitor-startJob]]
## startJob

.Function
* `void startJob(str name)`
* `void startJob(str name, int totalWork)`
* `void startJob(str name, int workShare, int totalWork)`


.Synopsis
Log the __start__ of a job.

.Description

The various forms of `startJob` do the following:

* Register a job with a name, a default amount of work contributed to the overall task,
  and an unknown amount of steps to do.
* Register a job with a name and a total amount of steps to do (this will also be the amount
  of work contributed to the parent job, if any
* Register a job with a name, the amount this will contribute to the overall task,
  and a total amount of steps to do.

[[Monitor-event]]
## event

.Function
* `void event(str name)`
* `void event(str name, int inc)`
* `void event(int inc)`


.Synopsis
Log the __start__ of an event (it is ended by another `event` or by `endJob`).

.Description
The various forms of `event` behave as follows:

* Log the start of an event.
* Log the start of an event with the amount of work that will be done when it's finished.
  An event is finished when the next event is logged, or when <<endJob>> is called.
* Log the start of an event with the amount of work that will be done when it's finished.
  An event is finished when the next event is logged, or when <<endJob>> is called.

[[Monitor-endJob]]
## endJob

.Function
`int endJob(bool succeeded)`

.Synopsis
Log the __end__ of a job.

.Description
This should always be called once for every startJob, unless an exception is thrown.
Returns the amount of work completed for this job (to help in future estimates)

[[Monitor-todo]]
## todo

.Function
`void todo(int work)`

.Synopsis
Set the estimated remaining work for the current (sub)job.

.Description
Set the estimated remaining work for the current (sub)job.
The argument `work` is the amount of work remaining to be done, or 0 for unknown.

:leveloffset: +1

:leveloffset: -1


[[util-ParseTreeUI]]
# ParseTreeUI
:concept: Libraries/util/ParseTreeUI

WARNING: documentation awaits Eclipse integration

:leveloffset: +1

:leveloffset: -1



[[util-PriorityQueue]]

[[util-PriorityQueue]]
# PriorityQueue
:concept: Libraries/util/PriorityQueue
.Usage
`import util::PriorityQueue;`


.Synopsis
A `PriorityQueue` datatype and associated functions.

.Usage
`import util::PriorityQueue;`

.Description
Priority queues maintain (priority, value) pairs in sorted order. They are implemented using a
http://en.wikipedia.org/wiki/Binomial_heap[Binomial Heap]. Priority queue are, for instance, used to implement shortest path algorithms.

Provides the following functions:

* <<Libraries/util/PriorityQueue-BinomialTree,BinomialTree>>:
* <<Libraries/util/PriorityQueue-binomialTree,binomialTree>>:
* <<Libraries/util/PriorityQueue-addSubTree,addSubTree>>:
* <<Libraries/util/PriorityQueue-mergeTree,mergeTree>>:
* <<Libraries/util/PriorityQueue-toString,toString>>:
* <<Libraries/util/PriorityQueue-PriorityQueue,PriorityQueue>>:
* <<Libraries/util/PriorityQueue-priorityQueue,priorityQueue>>:
* <<Libraries/util/PriorityQueue-mkPriorityQueue,mkPriorityQueue>>:
* <<Libraries/util/PriorityQueue-mkPriorityQueue,mkPriorityQueue>>:
* <<Libraries/util/PriorityQueue-isEmpty,isEmpty>>:
* <<Libraries/util/PriorityQueue-insertElement,insertElement>>:
* <<Libraries/util/PriorityQueue-findMinimum,findMinimum>>:
* <<Libraries/util/PriorityQueue-extractMinimum,extractMinimum>>:
* <<Libraries/util/PriorityQueue-toString,toString>>:
* <<Libraries/util/PriorityQueue-add,add>>:
* <<Libraries/util/PriorityQueue-mergeQueue,mergeQueue>>:


.Examples

.Benefits

.Pitfalls
Currently, both priority and associated value ("payload") have to be integers. This will be generalized.

[[PriorityQueue-BinomialTree]]
## BinomialTree
.Types
[source,rascal]

data BinomialTree = binomialTree(int priority, // priority of this tree int val, // payload int degree, // degree of tree list[BinomialTree] children // subtrees ) ;

[[PriorityQueue-addSubTree]]
## addSubTree

.Function
`BinomialTree addSubTree(BinomialTree p, BinomialTree q)`



[[PriorityQueue-mergeTree]]
## mergeTree

.Function
`BinomialTree mergeTree(BinomialTree p, BinomialTree q)`



[[PriorityQueue-toString]]
## toString

.Function
`str toString(BinomialTree T)`



[[PriorityQueue-PriorityQueue]]
## PriorityQueue
.Types
[source,rascal]

data PriorityQueue = priorityQueue(list[BinomialTree] trees, // trees in the heap int minIndex // index of minimal tree ) ;

[[PriorityQueue-mkPriorityQueue]]
## mkPriorityQueue

.Function
* `PriorityQueue mkPriorityQueue()`
* `PriorityQueue mkPriorityQueue(int priority, int val)`




[[PriorityQueue-isEmpty]]
## isEmpty

.Function
`bool isEmpty(PriorityQueue Q)`



[[PriorityQueue-insertElement]]
## insertElement

.Function
`PriorityQueue insertElement(PriorityQueue Q, int priority, int val)`



[[PriorityQueue-findMinimum]]
## findMinimum

.Function
`int findMinimum(PriorityQueue Q)`



[[PriorityQueue-extractMinimum]]
## extractMinimum

.Function
`tuple[int, int, PriorityQueue] extractMinimum(PriorityQueue Q)`



[[PriorityQueue-toString]]
## toString

.Function
`str toString(PriorityQueue Q)`



[[PriorityQueue-add]]
## add

.Function
`list[BinomialTree] add(list[BinomialTree] heap, BinomialTree t)`



[[PriorityQueue-mergeQueue]]
## mergeQueue

.Function
`PriorityQueue mergeQueue(PriorityQueue p, PriorityQueue q)`



:leveloffset: +1

:leveloffset: -1


[[util-Prompt]]
# Prompt
:concept: Libraries/util/Prompt

WARNING: documentation awaits Eclipse integration

:leveloffset: +1

:leveloffset: -1


[[util-ResourceMarkers]]
# ResourceMarkers
:concept: Libraries/util/ResourceMarkers

WARNING: documentation awaits Eclipse integration

:leveloffset: +1

:leveloffset: -1


:leveloffset: -1


:leveloffset: -1