The available Rascal libraries.
The libraries described here provide the following functionality:
1. Prelude
The Rascal standard prelude.
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
-
numeric functions, see the [Math] library,
-
statistical functions see [analysis-statistics],
-
graph functions see [analysis-graphs],
-
other common utilitites see [Libraries-util].
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
Messagedatatype 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.
This library makes it possible to import all core Rascal functionality with a single import.
-
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
import Boolean;
Library functions for Booleans.
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
bool arbBool()
Return an arbitrary Boolean value.
rascal>import Boolean;
ok
rascal>arbBool();
bool: false
rascal>arbBool();
bool: false
rascal>arbBool();
bool: true
arbInt is a convenient generator for arbitrary binary choices.
1.1.2. fromString
bool fromString(str s)
Convert the strings "true" or "false" to a bool.
1.1.3. toInt
int toInt(bool b)
Convert a Boolean value to integer.
Maps true to 1 and false to 0.
rascal>import Boolean;
ok
rascal>toInt(true);
int: 1
rascal>toInt(false);
int: 0
1.1.4. toReal
real toReal(bool b)
Convert Boolean value to real.
Maps true to 1.0 and false to 0.0.
rascal>import Boolean;
ok
rascal>toReal(true);
real: 1.0
rascal>toReal(false);
real: 0.0
1.1.5. toString
str toString(bool b)
Convert Boolean value to string.
Maps true to "true" and false to "false".
rascal>import Boolean;
ok
rascal>toString(true);
str: "true"
rascal>toString(false);
str: "false"
1.2. DateTime
import DateTime;
Library functions for date and time.
For operators on datetime see DateTime in the Rascal Language Reference.
The following functions are defined for datetime:
-
now: Get the current datetime.
-
createDate: Create a new date.
-
createTime: Create a new time (with optional timezone offset).
-
createDateTime: Create a new datetime (with optional timezone offset).
-
joinDateAndTime: Create a new datetime by combining a date and a time.
-
splitDateTime: Split an existing datetime into a tuple with the date and the time.
-
incrementYears: Increment the years by given amount or by 1.
-
incrementMonths: Increment the months by a given amount or by 1.
-
incrementDays: Increment the days by given amount or by 1.
-
incrementHours: Increment the hours by a given amount or by 1.`
-
incrementMinutes: Increment the minutes by a given amount or by 1.
-
incrementSeconds: Increment the seconds by a given amount or by 1.
-
incrementMilliseconds: Increment the milliseconds by a given amount or by 1.
-
decrementYears: Decrement the years by a given amount or by 1.
-
decrementMonths: Decrement the months by a given amount or by 1.
-
decrementDays: Decrement the days by a given amount or by 1.
-
decrementHours: Decrement the hours by a given amount or by 1.
-
decrementMinutes: Decrement the minutes by a given amount or by 1.
-
decrementSeconds: Decrement the seconds by a given amount or by 1.
-
decrementMilliseconds: Decrement the milliseconds by a given amount or by 1.
-
interval: A closed interval on the time axis
-
createInterval: Given two datetime values, create an interval.
-
Duration: A duration of time, measured in individual years, months, etc
-
createDuration: Create a new duration representing the duration between the begin and end dates.
-
daysInInterval: Return the number of days in an interval, including the begin and end days.
-
daysDiff: Return the difference between two dates and/or datetimes in days.
-
dateRangeByDay: Given an interval, return a list of days.
-
parseDate: Parse an input date given as a string using the given format string.
-
parseDateInLocale: Parse an input date given as a string using a specific locale and format string
-
parseTime: Parse an input time given as a string using the given format string.
-
parseTimeInLocale: Parse an input time given as a string using a specific locale and format string
-
parseDateTime: Parse an input datetime given as a string using the given format string.
-
parseDateTimeInLocale: Parse an input datetime given as a string using a specific locale and format string
-
printDate: Print an input date using the given format string.
-
printDateInLocale: Print an input date using a specific locale and format string.
-
printTime: Print an input time using the given format string.
-
printTimeInLocale: Print an input time using a specific locale and format string
-
printDateTime: Print an input datetime using the given format string.
-
printDateTimeInLocale: Print an input datetime using a specific locale and format string
1.2.1. now
datetime now()
Get the current datetime.
rascal>import DateTime;
ok
rascal>now();
datetime: $2017-07-03T13:44:41.429+00:00$
1.2.2. createDate
datetime createDate(int year, int month, int day)
Create a new date.
rascal>import DateTime;
ok
rascal>createDate(2012,1,1);
datetime: $2012-01-01$
1.2.3. createTime
-
datetime createTime(int hour, int minute, int second, int millisecond) -
datetime createTime(int hour, int minute, int second, int millisecond, int timezoneHourOffset, int timezoneMinuteOffset)
Create a new time (with optional timezone offset).
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
-
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)
Create a new datetime (with optional timezone offset).
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
datetime joinDateAndTime(datetime date, datetime time)
Create a new datetime by combining a date and a time.
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
tuple[datetime date, datetime time] splitDateTime(datetime dt)
Split an existing datetime into a tuple with the date and the time.
rascal>import DateTime;
ok
rascal>N = now();
datetime: $2017-07-03T13:44:42.489+00:00$
rascal>splitDateTime(N);
tuple[datetime,datetime]: <$2017-07-03$,$T13:44:42.489+00:00$>
1.2.7. incrementYears
-
datetime incrementYears(datetime dt, int n) -
datetime incrementYears(datetime dt)
Increment the years by given amount or by 1.
rascal>import DateTime;
ok
rascal>N = now();
datetime: $2017-07-03T13:44:42.714+00:00$
rascal>incrementYears(N);
datetime: $2018-07-03T13:44:42.714+00:00$
rascal>incrementYears(N, 5);
datetime: $2022-07-03T13:44:42.714+00:00$
1.2.8. incrementMonths
-
datetime incrementMonths(datetime dt, int n) -
datetime incrementMonths(datetime dt)
Increment the months by a given amount or by 1. .Function
rascal>import DateTime;
ok
rascal>N = now();
datetime: $2017-07-03T13:44:43.076+00:00$
rascal>incrementMonths(N);
datetime: $2017-08-03T13:44:43.076+00:00$
rascal>incrementMonths(N, 5);
datetime: $2017-12-03T13:44:43.076+00:00$
1.2.9. incrementDays
-
datetime incrementDays(datetime dt, int n) -
datetime incrementDays(datetime dt)
Increment the days by given amount or by 1.
rascal>import DateTime;
ok
rascal>N = now();
datetime: $2017-07-03T13:44:43.353+00:00$
rascal>incrementDays(N);
datetime: $2017-07-04T13:44:43.353+00:00$
rascal>incrementDays(N, 5);
datetime: $2017-07-08T13:44:43.353+00:00$
1.2.10. incrementHours
-
datetime incrementHours(datetime dt, int n) -
datetime incrementHours(datetime dt)
Increment the hours by a given amount or by 1.`
rascal>import DateTime;
ok
rascal>N = now();
datetime: $2017-07-03T13:44:43.649+00:00$
rascal>incrementHours(N);
datetime: $2017-07-03T14:44:43.649+00:00$
rascal>incrementHours(N, 5);
datetime: $2017-07-03T18:44:43.649+00:00$
1.2.11. incrementMinutes
-
datetime incrementMinutes(datetime dt, int n) -
datetime incrementMinutes(datetime dt)
Increment the minutes by a given amount or by 1.
rascal>import DateTime;
ok
rascal>N = now();
datetime: $2017-07-03T13:44:43.921+00:00$
rascal>incrementMinutes(N);
datetime: $2017-07-03T13:45:43.921+00:00$
rascal>incrementMinutes(N, 5);
datetime: $2017-07-03T13:49:43.921+00:00$
1.2.12. incrementSeconds
-
datetime incrementSeconds(datetime dt, int n) -
datetime incrementSeconds(datetime dt)
Increment the seconds by a given amount or by 1.
rascal>import DateTime;
ok
rascal>N = now();
datetime: $2017-07-03T13:44:44.216+00:00$
rascal>incrementSeconds(N);
datetime: $2017-07-03T13:44:45.216+00:00$
rascal>incrementSeconds(N, 5);
datetime: $2017-07-03T13:44:49.216+00:00$
1.2.13. incrementMilliseconds
-
datetime incrementMilliseconds(datetime dt, int n) -
datetime incrementMilliseconds(datetime dt)
Increment the milliseconds by a given amount or by 1.
rascal>import DateTime;
ok
rascal>N = now();
datetime: $2017-07-03T13:44:44.490+00:00$
rascal>incrementMilliseconds(N);
datetime: $2017-07-03T13:44:44.491+00:00$
rascal>incrementMilliseconds(N, 5);
datetime: $2017-07-03T13:44:44.495+00:00$
1.2.14. decrementYears
-
datetime decrementYears(datetime dt, int n) -
datetime decrementYears(datetime dt)
Decrement the years by a given amount or by 1.
rascal>import DateTime;
ok
rascal>N = now();
datetime: $2017-07-03T13:44:44.778+00:00$
rascal>decrementYears(N);
datetime: $2016-07-03T13:44:44.778+00:00$
rascal>decrementYears(N, 5);
datetime: $2012-07-03T13:44:44.778+00:00$
1.2.15. decrementMonths
-
datetime decrementMonths(datetime dt, int n) -
datetime decrementMonths(datetime dt)
Decrement the months by a given amount or by 1.
rascal>import DateTime;
ok
rascal>N = now();
datetime: $2017-07-03T13:44:45.089+00:00$
rascal>decrementMonths(N);
datetime: $2017-06-03T13:44:45.089+00:00$
rascal>decrementMonths(N, 5);
datetime: $2017-02-03T13:44:45.089+00:00$
1.2.16. decrementDays
-
datetime decrementDays(datetime dt, int n) -
datetime decrementDays(datetime dt)
Decrement the days by a given amount or by 1.
rascal>import DateTime;
ok
rascal>N = now();
datetime: $2017-07-03T13:44:45.380+00:00$
rascal>decrementDays(N);
datetime: $2017-07-02T13:44:45.380+00:00$
rascal>decrementDays(N, 3);
datetime: $2017-06-30T13:44:45.380+00:00$
1.2.17. decrementHours
-
datetime decrementHours(datetime dt, int n) -
datetime decrementHours(datetime dt)
Decrement the hours by a given amount or by 1.
rascal>import DateTime;
ok
rascal>N = now();
datetime: $2017-07-03T13:44:45.689+00:00$
rascal>decrementHours(N);
datetime: $2017-07-03T12:44:45.689+00:00$
rascal>decrementHours(N, 5);
datetime: $2017-07-03T08:44:45.689+00:00$
1.2.18. decrementMinutes
-
datetime decrementMinutes(datetime dt, int n) -
datetime decrementMinutes(datetime dt)
Decrement the minutes by a given amount or by 1.
rascal>import DateTime;
ok
rascal>N = now();
datetime: $2017-07-03T13:44:45.966+00:00$
rascal>decrementMinutes(N);
datetime: $2017-07-03T13:43:45.966+00:00$
rascal>decrementMinutes(N, 5);
datetime: $2017-07-03T13:39:45.966+00:00$
1.2.19. decrementSeconds
-
datetime decrementSeconds(datetime dt, int n) -
datetime decrementSeconds(datetime dt)
Decrement the seconds by a given amount or by 1.
rascal>import DateTime;
ok
rascal>N = now();
datetime: $2017-07-03T13:44:46.226+00:00$
rascal>decrementSeconds(N);
datetime: $2017-07-03T13:44:45.226+00:00$
rascal>decrementSeconds(N, 5);
datetime: $2017-07-03T13:44:41.226+00:00$
1.2.20. decrementMilliseconds
-
datetime decrementMilliseconds(datetime dt, int n) -
datetime decrementMilliseconds(datetime dt)
Decrement the milliseconds by a given amount or by 1.
rascal>import DateTime;
ok
rascal>N = now();
datetime: $2017-07-03T13:44:46.511+00:00$
rascal>decrementMilliseconds(N);
datetime: $2017-07-03T13:44:46.510+00:00$
rascal>decrementMilliseconds(N, 5);
datetime: $2017-07-03T13:44:46.506+00:00$
1.2.21. interval
data interval
= Interval(datetime begin, datetime end)
;
A closed interval on the time axis.
1.2.22. createInterval
interval createInterval(datetime begin, datetime end)
Given two datetime values, create an interval.
rascal>import DateTime;
ok
rascal>B = now();
datetime: $2017-07-03T13:44:46.773+00:00$
rascal>E = incrementDays(B, 2);
datetime: $2017-07-05T13:44:46.773+00:00$
rascal>createInterval(B, E);
interval: Interval($2017-07-03T13:44:46.773+00:00$,$2017-07-05T13:44:46.773+00:00$)
1.2.23. Duration
data Duration
= duration(int years, int months, int days, int hours, int minutes, int seconds, int milliseconds)
;
A duration of time, measured in individual years, months, etc.
1.2.24. createDurationInternal
tuple[int,int,int,int,int,int,int] createDurationInternal(datetime begin, datetime end)
1.2.25. createDuration
-
Duration createDuration(datetime begin, datetime end) -
Duration createDuration(interval i)
Create a new duration representing the duration between the begin and end dates.
rascal>import DateTime;
ok
rascal>B = now();
datetime: $2017-07-03T13:44:47.113+00:00$
rascal>E1 = incrementHours(B);
datetime: $2017-07-03T14:44:47.113+00:00$
rascal>createDuration(B, E1);
Duration: duration(0,0,0,1,0,0,0)
rascal>E2 = incrementMinutes(B);
datetime: $2017-07-03T13:45:47.113+00:00$
rascal>createDuration(B, E2);
Duration: duration(0,0,0,0,1,0,0)
1.2.26. daysInInterval
int daysInInterval(interval i)
Return the number of days in an interval, including the begin and end days.
rascal>import DateTime;
ok
rascal>B = now();
datetime: $2017-07-03T13:44:47.582+00:00$
rascal>E = incrementDays(B, 2);
datetime: $2017-07-05T13:44:47.582+00:00$
rascal>I = createInterval(B, E);
interval: Interval($2017-07-03T13:44:47.582+00:00$,$2017-07-05T13:44:47.582+00:00$)
rascal>daysInInterval(I);
int: 2
1.2.27. daysDiff
int daysDiff(datetime begin, datetime end)
Return the difference between two dates and/or datetimes in days.
rascal>import DateTime;
ok
rascal>B = now();
datetime: $2017-07-03T13:44:48.010+00:00$
rascal>E = incrementDays(B, 2);
datetime: $2017-07-05T13:44:48.010+00:00$
rascal>daysDiff(B, E);
int: 2
1.2.28. dateRangeByDay
list[datetime] dateRangeByDay(interval i)
Given an interval, return a list of days.
Given an interval i, return a list of days [i.begin, …, i.end].
rascal>import DateTime;
ok
rascal>B = now();
datetime: $2017-07-03T13:44:48.324+00:00$
rascal>E = incrementDays(B, 2);
datetime: $2017-07-05T13:44:48.324+00:00$
rascal>I = createInterval(B, E);
interval: Interval($2017-07-03T13:44:48.324+00:00$,$2017-07-05T13:44:48.324+00:00$)
rascal>//dateRangeByDay(I);
[red]##Parse error##
1.2.29. parseDate
datetime parseDate(str inputDate, str formatString)
Parse an input date given as a string using the given format string.
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
datetime parseDateInLocale(str inputDate, str formatString, str locale)
Parse an input date given as a string using a specific locale and format string.
1.2.31. parseTime
datetime parseTime(str inputTime, str formatString)
Parse an input time given as a string using the given format string.
rascal>import DateTime;
ok
rascal>parseTime("11/21/19", "HH/mm/ss");
datetime: $T11:21:19.000+01:00$
1.2.32. parseTimeInLocale
datetime parseTimeInLocale(str inputTime, str formatString, str locale)
Parse an input time given as a string using a specific locale and format string.
1.2.33. parseDateTime
datetime parseDateTime(str inputDateTime, str formatString)
Parse an input datetime given as a string using the given format string.
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
datetime parseDateTimeInLocale(str inputDateTime, str formatString, str locale)
Parse an input datetime given as a string using a specific locale and format string.
1.2.35. printDate
-
str printDate(datetime inputDate, str formatString) -
str printDate(datetime inputDate)
Print an input date using the given format string.
rascal>import DateTime;
ok
rascal>printDate(now());
str: "2017-07-03"
rascal>printDate(now(), "YYYYMMdd");
str: "20170703"
1.2.36. printDateInLocale
-
str printDateInLocale(datetime inputDate, str formatString, str locale) -
str printDateInLocale(datetime inputDate, str locale)
Print an input date using a specific locale and format string.
rascal>import DateTime;
ok
rascal>printDateInLocale(now(), "Europe/Netherlands");
str: "2017-07-03"
rascal>printDateInLocale(now(), "French");
str: "2017-07-03"
1.2.37. printTime
-
str printTime(datetime inputTime, str formatString) -
str printTime(datetime inputTime)
Print an input time using the given format string.
rascal>import DateTime;
ok
rascal>N = now();
datetime: $2017-07-03T13:44:49.472+00:00$
rascal>printTime(N);
str: "13:44:49.472+0000"
rascal>printTime(N, "HH/mm/ss");
str: "13/44/49"
1.2.38. printTimeInLocale
-
str printTimeInLocale(datetime inputTime, str formatString, str locale) -
str printTimeInLocale(datetime inputTime, str locale)
Print an input time using a specific locale and format string.
1.2.39. printDateTime
-
str printDateTime(datetime inputDateTime, str formatString) -
str printDateTime(datetime inputDateTime)
Print an input datetime using the given format string.
rascal>import DateTime;
ok
rascal>N = now();
datetime: $2017-07-03T13:44:49.747+00:00$
rascal>printDateTime(N);
str: "2017-07-03 13:44:49.747+0000"
rascal>printDateTime(N, "yyyy-MM-dd\'T\'HH:mm:ss.SSSZZ");
str: "2017-07-03T13:44:49.747+0000"
rascal>printDateTime(N, "YYYY/MM/dd/HH/mm/ss");
str: "2017/07/03/13/44/49"
1.2.40. printDateTimeInLocale
-
str printDateTimeInLocale(datetime inputDateTime, str formatString, str locale) -
str printDateTimeInLocale(datetime inputDateTime, str locale)
Print an input datetime using a specific locale and format string.
1.3. Exception
import Exception;
Exceptions thrown by the Rascal run-time.
1.3.1. RuntimeException
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()
;
The Exception datatype used in all Rascal exceptions.
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.
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
import IO;
Library functions for input/output.
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]
-
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.
-
println: Print a value to the output stream and add a newline.
-
printlnExp: Print a value followed by a newline and return it as result.
-
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.
-
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.
1.4.1. registerLocations
void registerLocations(str scheme, str authority, map[loc logical, loc physical] m)
register a logical file scheme including the resolution method via a table.
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.
-
Logical source locations are supported by IDE features such as hyperlinks
-
Logical source locations are supported by all IO functions as well
-
repeated calls to registerLocations for the same
schemeandauthoritywill overwrite themmap. -
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
void unregisterLocations(str scheme, str authority)
undo the effect of [registerLocations]
For debugging or for memory management you may wish to remove a lookup table.
1.4.3. resolveLocation
loc resolveLocation(loc l)
1.4.4. appendToFile
void appendToFile(loc file, value V…)
throws PathNotFound(loc file), IO(str msg)
Append a value to a file.
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.
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.
-
The same encoding pitfalls as the readFile function.
1.4.5. appendToFileEnc
void appendToFileEnc(loc file, str charset, value V…)
throws PathNotFound(loc file), IO(str msg)
Append a value to a file.
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
set[str] charsets()
Returns all available character sets.
1.4.7. canEncode
set[str] canEncode(str charset)
Returns whether this charset can be used for encoding (use with writeFile)
1.4.8. bprintln
bool bprintln(value arg)
Print a value and return true.
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.
rascal>import IO;
ok
rascal>bprintln("Hello World");
Hello World
1.4.9. exists
bool exists(loc file)
Check whether a given location exists.
Check whether a certain location exists, i.e., whether an actual file is associated with it.
rascal>import IO;
ok
Does the library file IO.rsc exist?
rascal>exists(|std:///IO.rsc|);
bool: true
1.4.10. find
loc find(str name, list[loc] path) throws PathNotFound
Find a named file in a list of locations.
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
bool isDirectory(loc file)
Check whether a given location is a directory.
Check whether the location file is a directory.
1.4.12. iprint
void iprint(value arg, int lineLimit = 1000)
Print an indented representation of a value.
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.
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
&T iprintlnExp(&T v)
Print an indented representation of a value followed by a newline and returns the value as result.
See [IO-iprintExp] for a version that does not add a newline.
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
void iprintln(value arg, int lineLimit = 1000)
Print a indented representation of a value and add a newline at the end.
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.
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
bool isFile(loc file)
Check whether a given location is actually a file (and not a directory).
Check whether location file is actually a file.
1.4.16. lastModified
datetime lastModified(loc file)
Last modification date of a location.
Returns last modification time of the file at location file.
rascal>import IO;
ok
Determine the last modification date of the Rascal standard library:
rascal>lastModified(|std:///IO.rsc|);
datetime: $2017-07-03T13:22:56.000+00:00$
1.4.17. listEntries
list[str] listEntries(loc file)
List the entries in a directory.
List the entries in directory file.
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
void mkDirectory(loc file)
throws PathNotFound(loc file), IO(str msg)
Create a new directory.
Create a directory at location file.
1.4.19. print
void print(value arg)
Print a value without subsequent newline.
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.
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
-
void println(value arg) -
void println()
Print a value to the output stream and add a newline.
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.
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
-
&T printlnExp(&T v) -
&T printlnExp(str msg, &T v)
Print a value followed by a newline and return it as result.
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
void rprint(value arg)
Raw print of a value.
This function is only available for internal use in the Rascal development team.
1.4.23. rprintln
void rprintln(value arg)
Raw print of a value followed by newline.
This function is only available for internal use in the Rascal development team.
1.4.24. readFile
str readFile(loc file)
throws PathNotFound(loc file), IO(str msg)
Read the contents of a location and return it as string value.
Return the contents of a file location as a single string. Also see readFileLines.
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.
-
The second version of
readFilewith 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
str readFileEnc(loc file, str charset)
throws PathNotFound(loc file), IO(str msg)
Read the contents of a location and return it as string value.
Return the contents (decoded using the Character set supplied) of a file location as a single string. Also see readFileLinesEnc.
1.4.26. readFileBytes
list[int] readFileBytes(loc file)
throws PathNotFound(loc file), IO(str msg)
Read the contents of a file and return it as a list of bytes.
1.4.27. readFileLines
list[str] readFileLines(loc file)
throws PathNotFound(loc file), IO(str msg)
Read the contents of a file location and return it as a list of strings.
Return the contents of a file location as a list of lines. Also see readFile.
Look at readFile to understand how this function chooses the character set. If you know the character set used, please use readFileLinesEnc.
-
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
list[str] readFileLinesEnc(loc file, str charset)
throws PathNotFound(loc file), IO(str msg)
Read the contents of a file location and return it as a list of strings.
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
void remove(loc file) throws IO(str msg)
1.4.30. writeFile
void writeFile(loc file, value V…)
throws PathNotFound(loc file), IO(str msg)
Write values to a file.
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
void writeFileBytes(loc file, list[int] bytes)
throws PathNotFound(loc file), IO(str msg)
Write a list of bytes to a file.
1.4.32. writeFileEnc
void writeFileEnc(loc file, str charset, value V…)
throws PathNotFound(loc file), IO(str msg)
Write values to a file.
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
void touch(loc file)
throws PathNotFound(loc file), IO(str msg)
Changes the last modification date of a file.
1.4.34. md5HashFile
str md5HashFile(loc file)
throws PathNotFound(loc file), IO(str msg)
Read the contents of a location and return its MD5 hash.
MD5 hash the contents of a file location.
1.4.35. createLink
str createLink(str title, str target)
1.4.36. toBase64
str toBase64(loc file)
throws PathNotFound(loc file), IO(str msg)
1.4.37. copyFile
bool copyFile(loc source, loc target)
1.4.38. copyDirectory
bool copyDirectory(loc source, loc target)
1.5. List
import List;
Library functions for lists.
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.
-
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.
-
min: Determine the smallest element in a list.
-
mix: Mix the elements of two lists.
-
permutations: Compute all permutations of a list.
-
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).
-
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).
-
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
list[&T] concat(list[list[&T]] xxs)
Concatenate a list of lists.
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
list[&T] delete(list[&T] lst, int n)
Delete an element from a list.
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.
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
map[&T element, int occurs] distribution(list[&T] lst)
Get the distribution of the elements of the list. That is how often does each element occur in the list?
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
list[&T] drop(int n, list[&T] lst)
Drop elements from the head of a list.
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].
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
list[&T] dup(list[&T] lst)
Remove multiple occurrences of elements in a list. The first occurrence remains.
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
&T elementAt(list[&T] lst, int index)
1.5.7. getOneFrom
&T getOneFrom(list[&T] lst)
Pick a random element from a list.
Get an arbitrary element from a list. See takeOneFrom for a function that also removes the selected element.
rascal>import List;
ok
rascal>getOneFrom(["zebra", "elephant", "snake", "owl"]);
str: "snake"
rascal>getOneFrom(["zebra", "elephant", "snake", "owl"]);
str: "snake"
rascal>getOneFrom(["zebra", "elephant", "snake", "owl"]);
str: "elephant"
1.5.8. getFirstFrom
&T getFirstFrom(list[&T] lst)
Pick first element from a list.
Get the first element from a list. As opposed to getOneFrom this function always returns the same (first) list element.
1.5.9. head
-
&T head(list[&T] lst) throws EmptyList -
list[&T] head(list[&T] lst, int n) throws IndexOutOfBounds
Get the first element(s) from a list.
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
tuple[&T, list[&T]] headTail(list[&T] lst) throws EmptyList
Split a list in a head and a tail.
This function is identical to pop.
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
list[int] index(list[&T] lst)
A list of legal index values of a list.
Returns a list of all legal index values for a given list lst.
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]
This function is useful in for loops over lists.
1.5.12. indexOf
int indexOf(list[&T] lst, &T elt)
Index of first occurrence of an element in a list.
Return index of first occurrence of elt in lst, or -1 if elt is not found.
Also see lastIndexOf.
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
list[&T] insertAt(list[&T] lst, int n, &T elm) throws IndexOutOfBounds
Insert an element at a specific position in a list.
Returns a new list with the value of elm inserted at index position n of the old list.
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
str intercalate(str sep, list[value] l)
Join a list of values into a string separated by a separator.
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
list[&T] intersperse(&T sep, list[&T] xs)
Intersperses a list of values with a separator.
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
bool isEmpty(list[&T] lst)
Test whether a list is empty.
Returns true when a list is empty and false otherwise.
rascal>import List;
ok
rascal>isEmpty([]);
bool: true
rascal>isEmpty([1, 2, 3]);
bool: false
1.5.17. last
&T last(list[&T] lst) throws EmptyList
Return the last element of a list, if any.
Also see tail that returns a list of one or more of the last elements of a list.
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
int lastIndexOf(list[&T] lst, &T elt)
Return index of last occurrence of elt in lst, or -1 if elt is not found.
Also see indexOf.
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
list[&U] mapper(list[&T] lst, &U (&T) fn)
Apply a function to all list elements and return list of results.
Apply a function fn to each element of lst and return the list of results.
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
&T max(list[&T] lst) throws EmptyList
Determine the largest element in a list.
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
-
list[&T] merge(list[&T] left, list[&T] right) -
list[&T] merge(list[&T] left, list[&T] right, bool (&T a, &T b) lessOrEqual)
Merge the elements of two sorted lists into one list.
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.
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
&T min(list[&T] lst)
Determine the smallest element in a list.
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
list[&T] mix(list[&T] l, list[&T] r)
Mix the elements of two lists.
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.
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
set[list[&T]] permutations(list[&T] lst)
Compute all permutations of a list.
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
set[list[&T]] permutationsBag(map[&T element, int occurs] b)
1.5.26. pop
tuple[&T, list[&T]] pop(list[&T] lst) throws EmptyList
Pop top element from list, return a tuple. .Description This function is identical to headTail. Also see push and top.
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
list[&T] prefix(list[&T] lst)
Return all but the last element of a list.
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
list[&T] push(&T elem, list[&T] lst)
Push an element in front of a list.
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
&T reducer(list[&T] lst, &T (&T, &T) fn, &T unit)
Apply a function to successive elements of list and combine the results (deprecated).
Apply the function fn to successive elements of list lst starting with unit.
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
WARNING: This function is deprecated, use a reducer instead.
1.5.30. remove
list[&T] remove(list[&T] lst, int indexToDelete)
1.5.31. removeFromBag
-
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
list[&T] reverse(list[&T] lst)
Reverse a list.
Returns a list with the elements of lst in reverse order.
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
int size(list[&T] lst)
Determine the number of elements in a list.
rascal>import List;
ok
rascal>size([20, 10, 30]);
int: 3
rascal>size(["zebra", "elephant", "snake", "owl"]);
int: 4
1.5.34. slice
list[&T] slice(list[&T] lst, int begin, int len)
Compute a sublist of a list.
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. |
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
-
list[&T] sort(list[&T] lst) -
list[&T] sort(list[&T] l, bool (&T a, &T b) less)
Sort the elements of a list.
Sort the elements of a list:
-
Use the built-in ordering on values to compare list elements.
-
Give an additional
lessThanfunction that will be used to compare elements.
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","grape","mango","kiwi","pear"]
1.5.36. shuffle
-
list[&T] shuffle(list[&T] l) -
list[&T] shuffle(list[&T] l, int seed)
Shuffle a list.
Returns a random (unbiased) shuffled list.
rascal>import List;
ok
rascal>shuffle([1,4,2,3]);
list[int]: [1,2,3,4]
rascal>shuffle(["zebra", "elephant", "snake", "owl"]);
list[str]: ["snake","owl","elephant","zebra"]
1.5.37. split
tuple[list[&T],list[&T]] split(list[&T] l)
Split a list into two halves.
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
-
(&T <:num) sum(list[(&T <:num)] _:[]) -
default (&T <:num) sum([(&T <: num) hd, *(&T <: num) tl])
1.5.39. tail
-
list[&T] tail(list[&T] lst) throws EmptyList -
list[&T] tail(list[&T] lst, int len) throws IndexOutOfBounds
Get the tail element(s) from a list.
-
Return a list consisting of all but the first element of
lst. -
Return a list consisting of the last
nelements oflst.
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
list[&T] take(int n, list[&T] lst)
Get number of elements from the head of a list.
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.
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
tuple[&T, list[&T]] takeOneFrom(list[&T] lst)
Remove an arbitrary element from a list, returns the element and the modified list.
Select an arbitrary element from lst, and return a tuple consisting of:
-
the selected element, and
-
a new list consisting of all elements of
lstexcept the selected element.
See getOneFrom to only selected an element from a list.
rascal>import List;
ok
rascal>takeOneFrom([10,20,30,40,50]);
tuple[int,list[int]]: <10,[20,30,40,50]>
rascal>takeOneFrom([10,20,30,40,50]);
tuple[int,list[int]]: <20,[10,30,40,50]>
rascal>takeOneFrom([10,20,30,40,50]);
tuple[int,list[int]]: <30,[10,20,40,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]]: <"zebra",["elephant","snake","owl"]>
rascal>takeOneFrom(["zebra", "elephant", "snake", "owl"]);
tuple[str,list[str]]: <"owl",["zebra","elephant","snake"]>
1.5.42. takeWhile
list[&T] takeWhile(list[&T] lst, bool (&T a) take)
Take elements from the front of the list as long as a predicate is true.
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
map[&A,set[&B]] toMap(list[tuple[&A, &B]] lst) throws MultipleKey
Convert a list of pairs to a map; first elements are associated with a set of second elements.
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.
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}
)
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
map[&A,&B] toMapUnique(list[tuple[&A, &B]] lst) throws MultipleKey
Convert a list of tuples to a map; result must be a map.
Convert a list of tuples to a map; result must be a map.
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)
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
&T top(list[&T] lst) throws EmptyList
Take the top element of a list. .Description This function is identical to [head]. Also see pop and push.
rascal>import List;
ok
rascal>top([3, 1, 4, 5]);
int: 3
rascal>top(["zebra", "elephant", "snake", "owl"]);
str: "zebra"
1.5.46. toRel
rel[&T,&T] toRel(list[&T] lst)
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.
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
set[&T] toSet(list[&T] lst)
Convert a list to a set.
Convert lst to a set.
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
str toString(list[&T] lst)
Convert a list to a string.
Convert lst to a string.
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
str itoString(list[&T] lst)
Convert a list to an indented string.
Convert lst to a indented string.
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
-
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)
Make a pair (triple) of lists from a list of pairs (triples).
Also see unzip;
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
list[int] upTill(int n)
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.
rascal>import List;
ok
rascal>upTill(10);
list[int]: [0,1,2,3,4,5,6,7,8,9]
1.5.52. zip
-
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)
Make a list of pairs from two (three) lists of the same length.
Also see unzip.
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
import ListRelation;
Library functions for list relations.
For operators on listrelations see ListRelation in the Rascal Language Reference.
The following functions are defined for list relations :
-
carrier: Return the list of all elements in any tuple in a list relation.
-
carrierR: A list relation restricted to certain element values in tuples.
-
carrierX: A list relation excluding tuples containing certain values.
-
complement: Complement of a list relation.
-
domain: Domain of a list relation: a list consisting of the first element of each tuple.
-
domainR: List relation restricted to certain domain elements.
-
domainX: List relation excluding certain domain values.
-
groupDomainByRange: Make sets of elements in the domain that relate to the same element in the range.
-
groupRangeByDomain: Make sets of elements in the range that relate to the same element in the domain.
-
ident: The identity list relation.
-
invert: Invert the tuples in a list relation.
-
range: The range composed of all but the first element of each tuple of a list relation.
-
rangeR: List relation restricted to certain range values.
-
rangeX: List relation excluding certain range values.
-
index: Listes a binary list relation as a map
1.6.1. carrier
-
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)
Return the list of all elements in any tuple in a list relation.
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
-
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)
A list relation restricted to certain element values in tuples.
Returns list relation R restricted to tuples with elements in set S.
rascal>import ListRelation;
ok
rascal>carrierR([<1,10>, <2,20>, <3,30>], {10, 1, 20});
lrel[int,int]: [<1,10>]
1.6.3. carrierX
-
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)
A list relation excluding tuples containing certain values.
Returns list relation R excluding tuples with some element in S.
rascal>import ListRelation;
ok
rascal>carrierX([<1,10>, <2,20>, <3,30>], {10, 1, 20});
lrel[int,int]: [<3,30>]
1.6.4. complement
-
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)
Complement of a list relation.
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.
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
-
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)
Domain of a list relation: a list consisting of the first element of each tuple.
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
-
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)
List relation restricted to certain domain elements.
Restriction of a list relation R to tuples with first element in S.
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
-
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)
List relation excluding certain domain values.
List relation R excluding tuples with first element in S.
rascal>import ListRelation;
ok
rascal>domainX([<1,10>, <2,20>, <3,30>], {3, 1});
lrel[int,int]: [<2,20>]
1.6.8. groupDomainByRange
list[list[&U]] groupDomainByRange(lrel[&U dom, &T ran] input)
Make sets of elements in the domain that relate to the same element in the range.
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
list[list[&T]] groupRangeByDomain(lrel[&U dom, &T ran] input)
Make sets of elements in the range that relate to the same element in the domain.
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
lrel[&T, &T] ident (list[&T] S)
The identity list relation.
The identity list relation for set S.
rascal>import ListRelation;
ok
rascal>ident(["mon", "tue", "wed"]);
lrel[str,str]: [
<"mon","mon">,
<"tue","tue">,
<"wed","wed">
]
1.6.11. invert
-
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)
Invert the tuples in a list relation.
rascal>import ListRelation;
ok
rascal>invert([<1,10>, <2,20>]);
lrel[int,int]: [
<10,1>,
<20,2>
]
1.6.12. range
-
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)
The range composed of all but the first element of each tuple of a list relation.
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
-
lrel[&T0,&T1] rangeR (lrel[&T0,&T1] R, set[&T1] S) -
lrel[&T0,&T1] rangeR (lrel[&T0,&T1] R, list[&T1] L)
List relation restricted to certain range values.
Restriction of binary list relation R to tuples with second element in set S.
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
-
lrel[&T0,&T1] rangeX (lrel[&T0,&T1] R, set[&T1] S) -
lrel[&T0,&T1] rangeX (lrel[&T0,&T1] R, list[&T1] S)
List relation excluding certain range values.
Restriction of binary list relation R to tuples with second element not in set S.
rascal>import ListRelation;
ok
rascal>rangeX([<1,10>, <2,20>, <3,30>], {30, 10});
lrel[int,int]: [<2,20>]
1.6.15. toMap
map[&T0,list[&T1]] toMap(lrel[&T0,&T1] R)
1.6.16. index
map[&K, set[&V]] index(lrel[&K, &V] R)
Listes a binary list relation as a map
Converts a binary list relation to a map of the domain to a set of the range.
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
list[&T] squeeze(list[&T] xs)
1.7. Map
import Map;
Library functions for maps.
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.
-
toString: Convert a map to a string.
-
itoString: Convert a map to a indented string.
1.7.1. delete
map[&K,&V] delete(map[&K,&V] m, &K k)
Delete a key from a map.
Returns the map m minus the key k.
rascal>import Map;
ok
rascal>delete(("apple":1,"pear":2), "apple");
map[str, int]: ("pear":2)
1.7.2. domain
set[&K] domain(map[&K, &V] M)
Determine the domain (set of keys) of a map.
Returns the domain (set of keys) of map M.
rascal>import Map;
ok
rascal>domain(("apple": 1, "pear": 2));
set[str]: {"pear","apple"}
1.7.3. domainR
map[&K, &V] domainR(map[&K, &V] M, set[&K] S)
Map restricted to certain keys.
Return the map M restricted to pairs with key in S.
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
map[&K, &V] domainX(map[&K, &V] M, set[&K] S)
Map with certain keys excluded.
Return the map M restricted to pairs with key not in S.
rascal>import Map;
ok
rascal>domainX(("apple": 1, "pear": 2, "orange": 3), {"apple", "pear"});
map[str, int]: ("orange":3)
1.7.5. getOneFrom
&K getOneFrom(map[&K, &V] M)
Get a n arbitrary key from a map.
Returns an arbitrary key of map M.
rascal>import Map;
ok
rascal>getOneFrom(("apple": 1, "pear": 2, "pineapple": 3));
str: "pear"
rascal>getOneFrom(("apple": 1, "pear": 2, "pineapple": 3));
str: "pineapple"
rascal>getOneFrom(("apple": 1, "pear": 2, "pineapple": 3));
str: "pear"
1.7.6. invert
map[&V, set[&K]] invert(map[&K, &V] M)
Invert the (key,value) pairs in a map.
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.
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
map[&V, &K] invertUnique(map[&K, &V] M)
Invert the (key,value) pairs in a map.
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.
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
bool isEmpty(map[&K, &V] M)
Test whether a map is empty.
Returns true if map M is empty, and false otherwise.
rascal>import Map;
ok
rascal>isEmpty(());
bool: true
rascal>isEmpty(("apple": 1, "pear": 2, "orange": 3));
bool: false
1.7.9. mapper
map[&K, &V] mapper(map[&K, &V] M, &L (&K) F, &W (&V) G)
Apply a function to all (key, value) pairs in a map.
Apply the functions F and G to each key/value pair in a map and return the transformed map.
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
set[&V] range(map[&K, &V] M)
The range (set of values that correspond to its keys) of a map.
Returns the range (set of values) of map M.
rascal>import Map;
ok
rascal>range(("apple": 1, "pear": 2));
set[int]: {1,2}
1.7.11. rangeR
map[&K, &V] rangeR(map[&K, &V] M, set[&V] S)
Map restricted to certain values in (key,values) pairs.
Returns the map restricted to pairs with values in S.
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
map[&K, &V] rangeX(map[&K, &V] M, set[&V] S)
Map with certain values in (key,value) pairs excluded.
Returns the map restricted to pairs with values not in S.
rascal>import Map;
ok
rascal>rangeX(("apple": 1, "pear": 2, "orange": 3), {2, 3});
map[str, int]: ("apple":1)
1.7.13. size
int size(map[&K, &V] M)
Number of (key, value) pairs in a map.
Returns the number of pairs in map M.
rascal>import Map;
ok
rascal>size(("apple": 1, "pear": 2, "orange": 3));
int: 3
1.7.14. toList
list[tuple[&K, &V]] toList(map[&K, &V] M)
Convert a map to a list of tuples.
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
-
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)
Convert a map to a relation.
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
str toString(map[&K, &V] M)
Convert a map to a string.
rascal>import Map;
ok
rascal>toString(("apple": 1, "pear": 2, "orange": 3));
str: "(\"pear\":2,\"orange\":3,\"apple\":1)"
1.7.17. itoString
str itoString(map[&K, &V] M)
Convert a map to a indented string.
rascal>import Map;
ok
rascal>itoString(("apple": 1, "pear": 2, "orange": 3));
str: "(\"pear\":2,\"orange\":3,\"apple\":1)"
1.8. Message
import Message;
A Message datatype that represents messages in the IDE.
data Message = error(str msg, loc at)
| warning(str msg, loc at)
| info(str msg, loc at);
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
data Message
= error(str msg, loc at)
| warning(str msg, loc at)
| info(str msg, loc at)
;
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
import Node;
Library functions for nodes.
For operators on nodes see Node in the Rascal Language Reference.
The following functions are defined for nodes:
-
arity: Determine the number of children of a node.
-
delAnnotation: Delete a specific annotation from a node.
-
delAnnotations: Delete all annotations from a node.
-
delAnnotationsRec: Delete recursively all annotations from all nodes in a value.
-
getAnnotations: Retrieve the annotations of a node value as a map.
-
getChildren: Get the children of a node.
-
getKeywordParameters: Get the keyword parameters of a node.
-
setKeywordParameters: Set the keyword parameters of a node.
-
getName: Determine the name of a node.
-
makeNode: Create a node given its function name and arguments.
-
setAnnotations: Add a map of annotations to a node value.
-
unset: Set a specific parameter back to default on a node
-
unset: Set all keyword parameters back to default
-
toString: Convert a node to a string.
-
itoString: Convert a node to an indented string.
1.9.1. arity
int arity(node T)
Determine the number of children of a node.
rascal>import Node;
ok
rascal>arity("f"(10, "abc"));
int: 2
rascal>arity("f"(10, "abc", false));
int: 3
1.9.2. delAnnotation
&T <: node delAnnotation(&T <: node x, str label)
Delete a specific annotation from a node.
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
&T <: node delAnnotations(&T <: node x)
Delete all annotations from a node.
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
&T delAnnotationsRec(&T v)
Delete recursively all annotations from all nodes in a value.
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
map[str,value] getAnnotations(node x)
Retrieve the annotations of a node value as a map.
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
list[value] getChildren(node T)
Get the children of a node.
rascal>import Node;
ok
rascal>getChildren("f"(10, "abc"));
list[value]: [10,"abc"]
1.9.7. getKeywordParameters
map[str,value] getKeywordParameters(node T)
Get the keyword parameters of a node.
rascal>import Node;
ok
rascal>getKeywordParameters("f"(10, "abc", height=0));
map[str, int]: ("height":0)
1.9.8. setKeywordParameters
&T <: node setKeywordParameters(&T <: node x, map[str,value] keywordParameters)
Set the keyword parameters of a node.
rascal>import Node;
ok
rascal>setKeywordParameters("f"(10, "abc"), ("height":0));
node: "f"(10,"abc",
height=0)
1.9.9. getName
str getName(node T)
Determine the name of a node.
rascal>import Node;
ok
rascal>getName("f"(10, "abc"));
str: "f"
1.9.10. makeNode
node makeNode(str N, value V…, map[str, value] keywordParameters = ())
Create a node given its function name and arguments.
rascal>import Node;
ok
rascal>makeNode("f", [10, "abc"]);
node: "f"(10,"abc")
1.9.11. setAnnotations
&T <: node setAnnotations(&T <: node x, map[str, value] annotations)
Add a map of annotations to a node value.
Set the annotations on node value x as described by the map annotations.
rascal>import Node;
ok
rascal>setAnnotations("f"(10, "abc"), ("color" : "red", "size" : "large"));
node: "f"(10,"abc")[
@size="large",
@color="red"
]
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
-
&T <: node unset(&T <: node x, str label) -
&T <: node unset(&T <: node x)
Set a specific parameter back to default on a node.
1.9.13. unsetRec
&T <: node unsetRec(&T <: node x)
1.9.14. toString
str toString(node T)
Convert a node to a string.
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
str itoString(node T)
Convert a node to an indented string.
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
import ParseTree;
Library functions for parse trees.
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.
-
Treeis 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
\locannotation 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 aProductionto a list of childrenTreenodes.Productionis the abstract representation of a rule in a syntax definition, which consists of a definition of an alternative for aSymbolby a list ofSymbols. -
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 alternativeTreenodes.
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:
-
Directly on the
Treelevel, just like any other algebraic data type. -
Using concrete syntax expressions and concrete syntax patterns.
-
Using actions.
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.
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.
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
data Tree
= appl(Production prod, list[Tree] args)
| cycle(Symbol symbol, int cycleLength)
| amb(set[Tree] alternatives)
| char(int character)
;
The Tree data type as produced by the parser.
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
data Production
= prod(Symbol def, list[Symbol] symbols, set[Attr] attributes)
| regular(Symbol def)
| error(Production prod, int dot)
| skipped()
;
Production in ParseTrees
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
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
data Attr
= \assoc(Associativity \assoc)
| \bracket()
;
Attributes in productions.
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
data Associativity
= \left()
| \right()
| \assoc()
| \non-assoc()
;
Associativity attribute.
Associativity defines the various kinds of associativity of a specific production.
1.10.6. CharRange
data CharRange
= range(int begin, int end)
;
Character ranges and character class .Description
-
CharRangedefines a range of characters. -
A
CharClassconsists of a list of characters ranges.
1.10.7. CharClass
list[CharRange]
1.10.8. Symbol
data Symbol
= \start(Symbol symbol)
;
Symbols that can occur in a ParseTree
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
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
data Symbol
= \lit(str string)
| \cilit(str string)
| \char-class(list[CharRange] ranges)
;
1.10.11. Symbol
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
data Symbol
= \conditional(Symbol symbol, set[Condition] conditions)
;
1.10.13. subtype
bool subtype(Symbol::\sort(_), Symbol::\adt("Tree", _))
1.10.14. Condition
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)
;
Datatype for declaring preconditions and postconditions on symbols
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
Production priority(Symbol s, [*Production a, priority(Symbol t, list[Production] b), *Production c])
Nested priority is flattened.
1.10.16. associativity
-
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)})
Normalization of associativity.
-
Choice (see the
choiceconstructor in [Type-ParseTree]) under associativity is flattened. -
Nested (equal) associativity is flattened.
-
Priority under an associativity group defaults to choice.
1.10.17. parse
-
&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)
Parse input text (from a string or a location) and return a parse tree.
-
Parse a string and return a parse tree.
-
Parse a string and return a parse tree,
origindefines the original location of the input. -
Parse the contents of resource input and return a parse tree.
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
str unparse(Tree tree)
Yield the string of characters that form the leafs of the given parse tree.
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
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
str saveParser(loc outFile)
Save the current object parser to a file.
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.
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
str printSymbol(Symbol sym, bool withLayout)
1.10.21. implode
&T<:value implode(type[&T<:value] t, Tree tree)
Implode a parse tree according to a given (ADT) type.
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
strthe 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;
Here are some examples for the above rules.
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).
Given the grammar
syntax Formal = formal: "VAR"? {Id ","}+ ":" Type;
The corresponding ADT could be:
data Formal = formal(bool, list[str], Type);
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);
Given the grammar
syntax Exp = left add: Exp "+" Exp;
Can be imploded into:
data Exp = add(Exp, Exp);
1.10.22. TreeSearchResult
data TreeSearchResult[&T<:Tree]
= treeFound(&T tree)
| treeNotFound()
;
Tree search result type for treeAt.
1.10.23. treeAt
-
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)
Select the innermost Tree of a given type which is enclosed by a given location.
1.10.24. sameType
-
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
-
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)
Determine if the given type is a non-terminal type.
1.11. Relation
import Relation;
Library functions for relations.
For operators on relations see Relation in the Rascal Language Reference.
The following functions are defined for relations:
-
carrier: Return the set of all elements in any tuple in a relation.
-
carrierR: A relation restricted to certain element values in tuples.
-
carrierX: A relation excluded tuples containing certain values.
-
complement: Complement of a relation.
-
domain: Domain of a relation: a set consisting of the first element of each tuple.
-
domainR: Relation restricted to certain domain elements.
-
domainX: Relation excluding certain domain values.
-
groupDomainByRange: Make sets of elements in the domain that relate to the same element in the range.
-
groupRangeByDomain: Make sets of elements in the range that relate to the same element in the domain.
-
ident: The identity relation.
-
invert: Invert the tuples in a relation.
-
range: The range (i.e., all but the first element of each tuple) of a relation.
-
rangeR: Relation restricted to certain range values.
-
rangeX: Relation excluding certain range values.
-
index: Indexes a binary relation as a map
1.11.1. carrier
-
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)
Return the set of all elements in any tuple in a relation.
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
-
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)
A relation restricted to certain element values in tuples.
Returns relation R restricted to tuples with elements in set S.
rascal>import Relation;
ok
rascal>carrierR({<1,10>, <2,20>, <3,30>}, {10, 1, 20});
rel[int,int]: {<1,10>}
1.11.3. carrierX
-
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)
A relation excluded tuples containing certain values.
Returns relation R excluding tuples with some element in S.
rascal>import Relation;
ok
rascal>carrierX({<1,10>, <2,20>, <3,30>}, {10, 1, 20});
rel[int,int]: {<3,30>}
1.11.4. complement
-
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)
Complement of a relation.
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.
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
-
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)
Domain of a relation: a set consisting of the first element of each tuple.
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
-
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)
Relation restricted to certain domain elements.
Restriction of a relation R to tuples with first element in S.
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
-
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)
Relation excluding certain domain values.
Relation R excluded tuples with first element in S.
rascal>import Relation;
ok
rascal>domainX({<1,10>, <2,20>, <3,30>}, {3, 1});
rel[int,int]: {<2,20>}
1.11.8. groupDomainByRange
set[set[&U]] groupDomainByRange(rel[&U dom, &T ran] input)
Make sets of elements in the domain that relate to the same element in the range.
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
set[set[&T]] groupRangeByDomain(rel[&U dom, &T ran] input)
Make sets of elements in the range that relate to the same element in the domain.
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
rel[&T, &T] ident (set[&T] S)
The identity relation.
The identity relation for set S.
rascal>import Relation;
ok
rascal>ident({"mon", "tue", "wed"});
rel[str,str]: {
<"tue","tue">,
<"mon","mon">,
<"wed","wed">
}
1.11.11. invert
-
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)
Invert the tuples in a relation.
rascal>import Relation;
ok
rascal>invert({<1,10>, <2,20>});
rel[int,int]: {
<10,1>,
<20,2>
}
1.11.12. range
-
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)
The range (i.e., all but the first element of each tuple) of a relation.
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
rel[&T0,&T1] rangeR (rel[&T0,&T1] R, set[&T2] S)
Relation restricted to certain range values.
Restriction of binary relation R to tuples with second element in set S.
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
rel[&T0,&T1] rangeX (rel[&T0,&T1] R, set[&T2] S)
Relation excluding certain range values.
Restriction of binary relation R to tuples with second element not in set S.
rascal>import Relation;
ok
rascal>rangeX({<1,10>, <2,20>, <3,30>}, {30, 10});
rel[int,int]: {<2,20>}
1.11.15. index
map[&K, set[&V]] index(rel[&K, &V] R)
Indexes a binary relation as a map
Converts a binary relation to a map of the domain to a set of the range.
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
import Set;
Library functions for sets.
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
map[&K,set[&V]] classify(set[&V] input, &K (&V) getClass)
Classify elements in a set.
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
&T getOneFrom(set[&T] st) throws EmptySet
Pick a random element from a set.
rascal>import Set;
ok
rascal>getOneFrom({1,2,3,4});
int: 1
rascal>getOneFrom({1,2,3,4});
int: 3
rascal>getOneFrom({1,2,3,4});
int: 1
rascal>getOneFrom({1,2,3,4});
int: 3
1.12.3. getFirstFrom
&T getFirstFrom(set[&T] st) throws EmptySet
Get "first" element from a set.
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.
This function helps to make set-based code more deterministic, for instance, for testing purposes.
1.12.4. group
set[set[&T]] group(set[&T] input, bool (&T a, &T b) similar)
Group elements in a set given an equivalence function.
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:544)
at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RVMonJVM.executeRVMProgram(RVMonJVM.java:235)
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:803)
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:539)
... 12 more
| check compiler. |
1.12.5. index
map[&T,int] index(set[&T] s)
Map set elements to a fixed index.
rascal>import Set;
ok
rascal>index({"elephant", "zebra", "snake"});
map[str, int]: ("snake":2,"zebra":1,"elephant":0)
1.12.6. isEmpty
bool isEmpty(set[&T] st)
Test whether a set is empty.
Yields true if s is empty, and false otherwise.
rascal>import Set;
ok
rascal>isEmpty({1, 2, 3});
bool: false
rascal>isEmpty({});
bool: true
1.12.7. mapper
set[&U] mapper(set[&T] st, &U (&T) fn)
Apply a function to all set elements and return set of results.
Return a set obtained by applying function fn to all elements of set s.
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
&T max(set[&T] st)
Determine the largest element of a set.
rascal>import Set;
ok
rascal>max({1, 3, 5, 2, 4});
int: 5
rascal>max({"elephant", "zebra", "snake"});
str: "zebra"
1.12.9. min
&T min(set[&T] st)
Determine the smallest element of a set.
rascal>import Set;
ok
rascal>min({1, 3, 5, 4, 2});
int: 1
1.12.10. power
set[set[&T]] power(set[&T] st)
Determine the powerset of a set.
Returns a set with all subsets of s.
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
set[set[&T]] power1(set[&T] st)
The powerset (excluding the empty set) of a set value.
Returns all subsets (excluding the empty set) of s.
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
&T reducer(set[&T] st, &T (&T,&T) fn, &T unit)
Apply a function to successive elements of a set and combine the results (deprecated).
Apply the function fn to successive elements of set s starting with unit.
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
int size(set[&T] st)
Determine the number of elements in a set.
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
-
(&T <:num) sum(set[(&T <:num)] _:{}) -
default (&T <:num) sum({(&T <: num) e, *(&T <: num) r})
1.12.15. getOneFrom
&T getOneFrom(set[&T] st) throws EmptySet
Pick an arbitrary element from a set.
rascal>import Set;
ok
rascal>getOneFrom({"elephant", "zebra", "snake"});
str: "zebra"
rascal>getOneFrom({"elephant", "zebra", "snake"});
str: "snake"
rascal>getOneFrom({"elephant", "zebra", "snake"});
str: "snake"
rascal>getOneFrom({"elephant", "zebra", "snake"});
str: "elephant"
1.12.16. takeOneFrom
tuple[&T, set[&T]] takeOneFrom(set[&T] st) throws EmptySet
Remove an arbitrary element from a set, returns the element and a set without that element.
Remove an arbitrary element from set s and return a tuple consisting of the element and a set without that element.
Also see getOneFrom.
rascal>import Set;
ok
rascal>takeOneFrom({1, 2, 3, 4});
tuple[int,set[int]]: <2,{1,3,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]]: <1,{3,2,4}>
1.12.17. takeFirstFrom
tuple[&T, set[&T]] takeFirstFrom(set[&T] st) throws EmptySet
Remove "first" element from a set, returns the element and a set without that element.
element of a set.
1.12.18. toList
list[&T] toList(set[&T] st)
Convert a set to a list.
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]
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
map[&A,set[&B]] toMap(rel[&A, &B] st)
Convert a set of tuples to a map; each key is associated with a set of values.
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.
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
map[&A,&B] toMapUnique(rel[&A, &B] st) throws MultipleKey
Convert a set of tuples to a map (provided that there are no multiple keys).
Convert a set of tuples to a map. The result should be a legal map (i.e., without multiple keys).
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
str toString(set[&T] st)
Convert a set to a string.
rascal>import Set;
ok
rascal>toString({1, 2, 3});
str: "{1,3,2}"
rascal>toString({"elephant", "zebra", "snake"});
str: "{\"snake\",\"zebra\",\"elephant\"}"
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
str itoString(set[&T] st)
Convert a set to an indented string.
rascal>import Set;
ok
rascal>toString({1, 2, 3});
str: "{1,3,2}"
rascal>toString({"elephant", "zebra", "snake"});
str: "{\"snake\",\"zebra\",\"elephant\"}"
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
-
list[&T] sort(set[&T] s) -
list[&T] sort(set[&T] l, bool (&T a, &T b) less)
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
lessThanfunction 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 < bandb < cthena < c.
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
set[&T] union(set[set[&T]] sets)
Flatten a set of sets into a single set.
1.13. String
import String;
Library functions for strings.
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.
-
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.
-
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.
-
toInt: Convert a string value to integer.
-
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
-
wrap: Word wrap a string to fit in a certain width.
-
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
-
str center(str s, int n) -
str center(str s, int n, str pad)
Center a string in given space.
-
Center string
sin string of lengthnusing spaces. -
Center string
sin string of lengthnusingpadas padding character.
rascal>import String;
ok
rascal>center("abc", 10);
str: " abc "
rascal>center("abc", 10, "x");
str: "xxxabcxxxx"
1.13.2. charAt
int charAt(str s, int i) throws IndexOutOfBounds(str msg)
Return character in a string by its index position.
Return the character at position i in string s as integer character code.
Also see stringChar that converts character codes back to string.
rascal>import String;
ok
rascal>charAt("abc", 0);
int: 97
rascal>stringChar(charAt("abc", 0));
str: "a"
1.13.3. chars
list[int] chars(str s)
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.
rascal>import String;
ok
rascal>chars("abc");
list[int]: [97,98,99]
rascal>stringChars(chars("abc")) == "abc";
bool: true
1.13.4. contains
bool contains(str input, str find)
Check that a string contains another string.
Check whether the string find occurs as substring in the string subject.
rascal>import String;
ok
rascal>contains("abracadabra", "bra");
bool: true
rascal>contains("abracadabra", "e");
bool: false
1.13.5. endsWith
bool endsWith(str subject, str suffix)
Check whether a string ends with a given substring.
Yields true if string subject ends with the string suffix.
rascal>import String;
ok
rascal>endsWith("Hello.rsc", ".rsc");
bool: true
1.13.6. escape
str escape(str subject, map[str,str] mapping)
Replace single characters in a string.
Return a copy of subject in which each single character key in replacements
has been replaced by its associated value.
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
list[int] findAll(str subject, str find)
Find all occurrences of a string in another string.
Find all occurrences of string find in string subject.
The result is a (possible empty) list of positions where find matches.
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
int findFirst(str subject, str find)
Find the first occurrence of a string in another string.
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.
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
int findLast(str subject, str find)
Find the last occurrence of a string in another string.
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.
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
bool isEmpty(str s)
Check whether a string is empty.
Returns true if string s is empty.
rascal>import String;
ok
rascal>isEmpty("");
bool: true
rascal>isEmpty("abc");
bool: false
1.13.11. left
-
str left(str s, int n) -
str left(str s, int n, str pad)
Left alignment of string in given space.
-
Left align string
sin string of lengthnusing spaces. -
Left align string
sin string of lengthnusingpadas pad character.
rascal>import String;
ok
rascal>left("abc", 10);
str: "abc "
rascal>left("abc", 10, "x");
str: "abcxxxxxxx"
1.13.12. replaceAll
str replaceAll(str subject, str find, str replacement)
Replace all occurrences of a string in another string.
Return a copy of subject in which all occurrences of find (if any) have been replaced by replacement.
Also see replaceFirst and replaceLast.
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"
Note that find is a string (as opposed to, for instance, a regular expression in Java).
1.13.13. replaceFirst
str replaceFirst(str subject, str find, str replacement)
Replace the first occurrence of a string in another string.
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.
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"
Note that find is a string (as opposed to, for instance, a regular expression in Java).
1.13.14. replaceLast
str replaceLast(str subject, str find, str replacement)
Replace the last occurrence of a string in another string.
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.
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"
Note that find is a string (as opposed to, for instance, a regular expression in Java).
1.13.15. reverse
str reverse(str s)
Return a string with all characters in reverse order.
Returns string with all characters of string s in reverse order.
rascal>import String;
ok
rascal>reverse("abc");
str: "cba"
1.13.16. right
-
str right(str s, int n) -
str right(str s, int n, str pad)
Right alignment of a string value in a given space.
-
Right align string
sin string of lengthnusing spaces. -
Right align string
sin string of lengthnusingpadas pad character.
rascal>import String;
ok
rascal>right("abc", 10);
str: " abc"
rascal>right("abc", 10, "x");
str: "xxxxxxxabc"
1.13.17. size
int size(str s)
Determine length of a string value.
Returns the length (number of characters) in string s.
rascal>import String;
ok
rascal>size("abc");
int: 3
rascal>size("");
int: 0
1.13.18. startsWith
bool startsWith(str subject, str prefix)
Check whether a string starts with a given prefix.
Yields true if string subject starts with the string prefix.
rascal>import String;
ok
rascal>startsWith("Hello.rsc", "Hell");
bool: true
1.13.19. stringChar
str stringChar(int char) throws IllegalArgument(int character)
Convert a character code into a string.
1.13.20. stringChars
str stringChars(list[int] chars) throws IllegalArgument(int character)
Convert a list of character codes into a string.
1.13.21. isValidCharacter
bool isValidCharacter(int ch)
Check that a given integer value is a valid Unicode code point.
1.13.22. substring
-
str substring(str s, int begin) -
str substring(str s, int begin, int end)
Extract a substring from a string value.
-
Yields substring of string
sfrom indexbeginto the end of the string. -
Yields substring of string
sfrom indexbeginto (but not including) indexend.
rascal>import String;
ok
rascal>substring("abcdef", 2);
str: "cdef"
rascal>substring("abcdef", 2, 4);
str: "cd"
1.13.23. toInt
-
int toInt(str s) throws IllegalArgument -
int toInt(str s, int r) throws IllegalArgument
Convert a string value to integer.
-
Converts string
sto integer. -
Convert string
sto integer using radixr.
Throws IllegalArgument when s cannot be converted.
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
str toLowerCase(str s)
Convert the characters in a string value to lower case.
Convert all characters in string s to lowercase. Also see toUpperCase.
rascal>import String;
ok
rascal>toLowerCase("AaBbCc123");
str: "aabbcc123"
1.13.25. toReal
real toReal(str s)
Convert a string value to real.
Converts string s to a real. Throws IllegalArgument when s cannot be converted.
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
str toUpperCase(str s)
Convert the characters in a string value to upper case.
Converts all characters in string s to upper case.
Also see toLowerCase.
rascal>import String;
ok
rascal>toUpperCase("AaBbCc123");
str: "AABBCC123"
1.13.27. trim
str trim(str s)
Returns string with leading and trailing whitespace removed.
rascal>import String;
ok
rascal>trim(" jelly
>>>>>>>beans ");
str: "jelly\nbeans"
1.13.28. squeeze
str squeeze(str src, str charSet)
Squeeze repeated occurrences of characters.
.Description
Squeeze repeated occurrences in src of characters in charSet removed.
See Apache
for the allowed syntax in charSet.
rascal>import String;
ok
rascal>squeeze("hello", "el");
str: "helo"
1.13.29. split
list[str] split(str sep, str src)
Split a string into a list of strings based on a literal separator.
1.13.30. capitalize
str capitalize(str src)
1.13.31. uncapitalize
str uncapitalize(str src)
1.13.32. toBase64
str toBase64(str src)
1.13.33. fromBase64
str fromBase64(str src)
1.13.34. wrap
str wrap(str src, int wrapLength)
Word wrap a string to fit in a certain width.
Inserts newlines in a string in order to fit the string in a certain width. It only breaks on spaces (' ').
1.13.35. format
str format(str s, str dir, int n, str pad)
1.13.36. rexpMatch
bool rexpMatch(str s, str re)
Determine if a string matches the given (Java-syntax) regular expression.
1.13.37. toLocation
loc toLocation(str s)
Convert a string value to a (source code) location.
-
Converts string
sto a location. -
If the scheme is not provided, it is assumed to be
cwd.
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
str substitute(str src, map[loc,str] s)
Substitute substrings in a string based on a substitution map from location to string.
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
import Type;
Rascal’s type system, implemented in Rascal itself.
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.
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
data Symbol
= \int()
| \bool()
| \real()
| \rat()
| \str()
| \num()
| \node()
| \void()
| \value()
| \loc()
| \datetime()
;
A Symbol represents a Rascal Type.
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. |
1.14.2. Symbol
data Symbol
= \label(str name, Symbol symbol)
;
1.14.3. Symbol
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
data Symbol
= \parameter(str name, Symbol bound)
;
1.14.5. Production
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)
;
A production in a grammar or constructor in a data type.
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
data Attr
= \tag(value \tag)
;
Attributes register additional semantics annotations of a definition.
[[Type-\var-func]] ## \var-func
Symbol \var-func(Symbol ret, list[Symbol] parameters, Symbol varArg)
Transform a function with varargs (…) to a normal function with a list argument.
1.14.7. choice
Production choice(Symbol s, set[Production] choices)
Normalize the choice between alternative productions.
Nested choice is flattened.
1.14.8. subtype
-
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)
Subtype on types.
1.14.9. comparable
bool comparable(Symbol s, Symbol t)
Check if two types are comparable, i.e., have a common supertype.
1.14.10. equivalent
bool equivalent(Symbol s, Symbol t)
Check if two types are equivalent.
1.14.11. eq
bool eq(value x, value y)
Structural equality between values.
The difference is that no implicit coercions are done between values of incomparable types, such as == does for int, real and rat.
rascal>import Type;
ok
rascal>1 == 1.0
bool: true
rascal>eq(1,1.0)
bool: false
1.14.12. lub
-
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))
The least-upperbound (lub) between two types.
This function documents and implements the lub operation in Rascal’s type system.
1.14.13. keepParams
bool keepParams(Symbol::\parameter(str s1, Symbol bound1), Symbol::\parameter(str s2, Symbol bound2))
1.14.14. lub
-
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
bool allLabeled(list[Symbol] l)
1.14.16. noneLabeled
bool noneLabeled(list[Symbol] l)
1.14.17. getLabels
list[str] getLabels(list[Symbol] l)
1.14.18. addLabels
-
list[Symbol] addLabels(list[Symbol] l, list[str] s) -
default list[Symbol] addLabels(list[Symbol] l, list[str] s)
1.14.19. stripLabels
list[Symbol] stripLabels(list[Symbol] l)
1.14.20. getParamLabels
list[str] getParamLabels(list[Symbol] l)
1.14.21. addParamLabels
-
list[Symbol] addParamLabels(list[Symbol] l, list[str] s) -
default list[Symbol] addParamLabels(list[Symbol] l, list[str] s)
1.14.22. glb
-
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)
The greatest lower bound (glb) between two types.
This function documents and implements the glb operation in Rascal’s type system.
1.14.23. Exception
data Exception
= typeCastException(Symbol from, type[value] to)
;
1.14.24. typeCast
&T typeCast(type[&T] typ, value v)
1.14.25. make
-
&T make(type[&T] typ, str name, list[value] args) -
&T make(type[&T] typ, str name, list[value] args, map[str,value] keywordArgs)
Instantiate an ADT constructor of a given type with the given children and optional keyword arguments.
This function will build a constructor if the definition exists and throw an exception otherwise.
1.14.26. typeOf
Symbol typeOf(value v)
Returns the dynamic type of a value as a reified type.
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.
rascal>import Type;
ok
rascal>value x = 1;
int: 1
rascal>typeOf(x)
Symbol: int()
-
Note that the
typeOffunction 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
-
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 _)
Determine if the given type is an int.
1.14.28. isBoolType
-
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 _)
Determine if the given type is a bool.
1.14.29. isRealType
-
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 _)
Determine if the given type is a real.
1.14.30. isRatType
-
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 _)
Determine if the given type is a rational.
1.14.31. isStrType
-
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 _)
Determine if the given type is a string.
1.14.32. isNumType
-
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 _)
Determine if the given type is a num.
1.14.33. isNodeType
-
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 _)
Determine if the given type is a node.
1.14.34. isVoidType
-
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 _)
Determine if the given type is a void.
1.14.35. isValueType
-
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 _)
Determine if the given type is a value.
1.14.36. isLocType
-
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 _)
Determine if the given type is a loc.
1.14.37. isDateTimeType
-
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 _)
Determine if the given type is a datetime.
1.14.38. isSetType
-
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 _)
Determine if the given type is a set.
1.14.39. isRelType
-
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 _)
Determine if the given type is a relation.
1.14.40. isListRelType
-
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 _)
Determine if the given type is a list relation.
1.14.41. isTupleType
-
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 _)
Determine if the given type is a tuple.
1.14.42. isListType
-
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 _)
Determine if the given type is a list.
1.14.43. isListRelType
-
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 _)
Determine if the given type is a list relation.
1.14.44. isMapType
-
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 _)
Determine if the given type is a map.
1.14.45. isBagType
-
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 _)
Determine if the given type is a bag (bags are not yet implemented).
1.14.46. isADTType
-
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 _)
Determine if the given type is an Abstract Data Type (ADT).
1.14.47. isConstructorType
-
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 _)
Determine if the given type is a constructor.
1.14.48. isAliasType
-
bool isAliasType(Symbol::\alias(,,_)) -
bool isAliasType(Symbol::\parameter(_,Symbol tvb)) -
bool isAliasType(Symbol::\label(_,Symbol lt)) -
default bool isAliasType(Symbol _)
Determine if the given type is an alias.
1.14.49. isFunctionType
-
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 _)
Determine if the given type is a function.
1.14.50. isReifiedType
-
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 _)
Determine if the given type is a reified type.
1.14.51. isTypeVar
-
bool isTypeVar(Symbol::\parameter(,)) -
bool isTypeVar(Symbol::\alias(,,Symbol at)) -
bool isTypeVar(Symbol::\label(_,Symbol lt)) -
default bool isTypeVar(Symbol _)
Determine if the given type is an type variable (parameter).
1.15. ValueIO
import ValueIO;
Library functions for reading and writing values in textual and binary format.
1.15.1. readValueFile
value readValueFile(loc file)
Read a value from a binary file in PBF format.
1.15.2. getFileLength
int getFileLength(loc file)
Get length of a file in number of bytes.
1.15.3. readBinaryValueFile
-
&T readBinaryValueFile(type[&T] result, loc file) -
value readBinaryValueFile(loc file)
Read a typed value from a binary file.
1.15.4. readTextValueFile
-
&T readTextValueFile(type[&T] result, loc file) -
value readTextValueFile(loc file)
Read a typed value from a text file.
1.15.5. readTextValueFileWithEmbeddedTypes
&T readTextValueFileWithEmbeddedTypes(type[&T] result, loc file)
If you have written a file containing reified types, then you can use this function to read them back.
1.15.6. readTextValueString
-
value readTextValueString(str input) -
&T readTextValueString(type[&T] result, str input)
Parse a textual string representation of a value.
1.15.7. writeBinaryValueFile
void writeBinaryValueFile(loc file, value val, bool compression = true)
Write a value to a file using an efficient binary file format.
1.15.8. writeTextValueFile
void writeTextValueFile(loc file, value val)
Write a value to a file using a textual file format.
2. Vis
Functions for creating visualisations.
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
Overview of the complete Figure library.
import vis::Figure;
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:
-
FPropertydescribes 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]
-
-
Figuredescribes 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].
-
One of the functions [Render-render] or [Render-renderSave] are needed to actually view a Figure.
2.1.1. Angles
Conventions for defining angles.
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:
There is at the moment no support for angles expressed in radians.
2.1.2. ColorModel
The model used for defining colors.
alias Color = int;
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.
[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]##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
Creates an arbitrary color.
FProperty arbColor()
[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]##Error: Name fillColor is not in scope##
[red]##Error: Name arbColor is not in scope##
[red]##Error: Name box is not in scope##
[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##
color
Return a color with a given name.
Color color(str name)
Color color(str name, real alpha)
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.
[red]##Error: Name color is not in scope##
[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]##Error: Name color is not in scope##
[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
Sorted list of available color names that can be used by the [color] function.
list[str] colorNames()
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]##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##
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]##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##
colorScale
Compute a color scale for range of values.
Color(&T <: num) colorScale(list[&T <: num] values, Color from, Color to)
Given a list of numbers values, colorScale returns a function that maps these numbers to a color scale between the colors from and to.
list[int]: [10,20,-50,13,-40,25]
[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]##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
Create a list of intermediate colors between two colors.
list[Color] colorSteps(Color from, Color to, int steps)
Create a list of interpolated colors between from and to in a given number of steps.
[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:
gray
The color gray.
Color gray(int g)
Color gray(int g, real alpha)
Color gray(real perc)
Color gray(real perc, real alpha)
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.
Setting gray values with an integer in the range [0,255]:
[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]##Error: Name fillColor is not in scope##
[red]##Error: Name gray is not in scope##
[red]##Error: Name box is not in scope##
[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]##Error: Name fillColor is not in scope##
[red]##Error: Name gray is not in scope##
[red]##Error: Name box is not in scope##
[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]##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]##Error: Name fillColor is not in scope##
[red]##Error: Name gray is not in scope##
[red]##Error: Name box is not in scope##
[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]##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
Interpolate between two colors.
Color interpolateColor(Color from, Color to, real percentage)
Interpolate between two colors (in RGB space). The percentage indicates the distance between
the from and the to color.
[red]##Error: Name color is not in scope##
[red]##Error: Name color is not in scope##
[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]##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]##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]##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]##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]##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
A standard palette of 12 colors.
str palette(int n)
Provides a color name from a palette of 12 good distinguishable colors.
[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:
Arguments outside the interval [0,11] are mapped to "black".
rgb
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)
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).
[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]##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]##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]##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]##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
The model for composing figures.
The Figure library uses the following model for the composition of figures:
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 |
|
:------------ |
:------------------- |
:--------------------- |
|
|
|
[Properties/left] |
|
|
|
[Properties/hcenter] |
|
|
|
[Properties/right] |
|
|
|
[Properties/top] |
|
|
|
[Properties/vcenter] |
|
|
|
[Properties/bottom] |
|
|
|
[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.
-
Although sizes are traditionally used to determine the size of geometric figures, it is better to use relative sizes using
grow,shrinkandalignsince this makes figures resizable. -
[resizable] can be used to control the resizing behaviour of a figure.
2.1.4. Figures
Overview of all figures.
-
Figure -
alias Figures = list[Figure];
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].
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
Describes the line decorations for an [$Figures/outline].
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
A rectangular box.
Figure box(FProperty props…)
Figure box(Figure inner, FProperty props…)
Draw a rectangular box using the properties props.
An optional nested figure inner may be placed inside the box.
Lets start with a box b0 of given (minimal) dimensions:
[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]##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 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
b0contains boxb1. -
The dimensions of
b1are determined by shrinking to 80% of the dimensions ofb0.
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]##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]##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]##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]##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]##Error: Name fillColor 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##
[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
An interactive push button.
Figure button(str label, void () vcallback, FProperty props…)
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.
[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##
Clicking the button will increment the value of n.
Unfortunately we cannot show an interactive version of the above example here. Try it out in Rascal itself.
checkbox
An interactive checkbox.
Figure checkbox(str text, void(bool state) vcallback, FProperty props…)
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).
[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##
Checking the checkbox will change the variable state and this is reflected in the changed text.
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
An interactive choice.
choice(list[str] choices, void(str s) ccallback, FProperty props…)
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##
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
An interactive combo box.
Figure combo(list[str] choices, void(str s) ccallback, FProperty props…)
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.
[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##
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
A dynamically computed figure.
Figure computeFigure(Figure () computeFig, FProperty props…)
Figure computeFigure(bool() recomp, Figure () computeFig, FProperty props…)
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
An edge in a graph.
Edge edge(str from, str to, FProperty props…)
Applicable properties are:
-
[fromArrow]
-
[toArrow]
See graph.
ellipse
An ellipse.
FProperty ellipse(FProperty props…)
FProperty ellipse(Figure inner, FProperty props)
Draw an ellipse using the sizes given in properties props.
An optional nested figure fig may be placed inside the ellipse.
The fragment
[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]##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]##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:
fswitch
Dynamic selection from a fixed list of figures.
Figure fswitch(int () choice, Figures fs, Fproprty props …)
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
Graph layout.
Figure graph(Figures nodes, list[Edge] edges, FProperty props…)
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.
[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##
[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##
[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##
-
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
Place figures in a grid with cells of equal size.
grid(list[list[Figure]] figs, FProperty props…)
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:
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:
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]##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
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
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
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
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]##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
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]##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:
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]##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:
hcat
Horizontal composition of a list of figures.
Figure hcat(Figures figs, FProperty props…)
Horizontal composition is a special case of [grid]. It is a grid with just one row. See [grid] for more information.
See also [vcat].
[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]##Error: Name fillColor is not in scope##
[red]##Error: Name vshrink is not in scope##
[red]##Error: Name box is not in scope##
[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]##Error: Name vshrink is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name fillColor is not in scope##
[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]##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]##Error: Name vshrink is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name fillColor is not in scope##
[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]##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]##Error: Name vshrink is not in scope##
[red]##Error: Name box is not in scope##
[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]##Error: Name fillColor is not in scope##
[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
Creates a horizontal screen on which things can be projected.
Figure hscreen(Figure inner,FProperty prop…)
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]##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]##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##
[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]##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##
If the inner figure specifies a shrink then the remaining size is used for the screen, otherwise the minimal size is used.
[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]##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##
Alignment and shrinking of projected figures also works.
[red]##Parse error##
[red]##Parse error##
[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##
Also see [vscreen].
hscrollable
Embed a figure in a horizontally scrollable plane.
Figure hscrollable(Figure f, FProperty props …)
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].
[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]##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##
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
Horizontal and vertical composition of a list of figures.
Figure hvcat(Figures figs, FProperty props…)
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.
[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]##Error: Name fillColor 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##
[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 box is not in scope##
[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 size 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(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]##Error: Name fillColor 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##
[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 box is not in scope##
[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 size 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##
[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"]
outline
Outline to summarize file related information.
Figure outline(list[LineDecoration] lineInfo, int maxLine, FProperty props…)
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.
[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##
overlay
Composition of figures by superposition.
Figure overlay(Figures figs, FProperty props…)
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.
[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 shrink is not in scope##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name box 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/o1.png[alt="o1"]
[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 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]##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]##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 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]##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]##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 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]##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]##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:
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]##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:
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:
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:
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:
The [hconnect] and [vconnect] properties can be used to determine where a shape will connect with a figure.
[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]##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]##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]##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:
pack
Dense packing of a list of figures.
Figure pack(Figures figs, FProperty props…)
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.
[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]##Error: Name fillColor 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##
[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 box is not in scope##
[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 size 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##
[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]##Error: Name fillColor 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##
[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 box is not in scope##
[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 size 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(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):
rotate
Rotate a figure.
Figure rotate(num angle, Figure fig)
<warning> Currently doesn’t work! </warning>
Rotate figure fig angle degrees around its anchor point.
Also see Angles.
<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)]));
scale
Scale a figure.
Figure scale(num perc, Figure fig)
Figure scale(num xperc, num yperc, Figure fig)
<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.
<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));
scaleSlider
Interactive slider.
Figure scaleSlider(int() low, int high(), int () selection, void(int) callback)
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. -
highfunction to determine highest value on the scale. -
selection: function to determine currently selected value. -
callback: function called when slider is changed.
We now use the scaleSlider to interactively control the size of a box.
Observe that:
-
the local variable
nis used to record the current size of the box. -
the arguments of
scaleSlideruse or modify the value ofn. -
the last element in the vertical composition uses
computeFigureto compute a new box of sizen.
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##
Moving the slider will change the size of the box.
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
Embed a figure in a scrollable plane.
Figure scrollable(Figure f, FProperty props …)
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.
See also [hscrollable] and [vscrollable].
[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]##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##
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
An invisible space.
Figure space(Figure inner, FProperty props…)
A space is an invisible placeholder and acts like an invisible box.
A space can only be observed indirectly by placing it between two visible figures:
[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]##Error: Name fillColor is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name size is not in scope##
[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##
text
Text.
Figure text(str s, FProperty props…)
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.
[red]##Error: Name render is not in scope##
[red]##Error: Name text is not in scope##
[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##
[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##
[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]##Error: Name fontSize is not in scope##
[red]##Error: Name fontColor is not in scope##
[red]##Error: Name text is not in scope##
[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##
[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##
textfield
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…)
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.
[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##
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
Tree layout.
Figure tree(Figure root, Figures children, FProperty props…)
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.
[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##
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##
[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##
treemap
Treemap layout.
Figure treemap(Figures nodes, FProperty props…)
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.
[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##
vcat
Vertical composition of figures.
Figure vcat(Figures figs, FProperty props…)
This is a special case of [grid]. It is a [grid] with just one column. See [grid] for more information.
See also [hcat].
[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]##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]##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]##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]##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]##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]##Error: Name hshrink is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name fillColor is not in scope##
[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]##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
Vertical projection screen.
Figure vscreen(Figure fig, FProperty props …)
Creates a vertical screen on which things can be projected. Works the same as [hscreen].
vscrollable
Embded a figure in a vertically scrollable plane.
Figure vscrollable(Figure f, FProperty props …)
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].
[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]##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##
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
The model used for user-interaction.
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.
-
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 usesize(int(){ return n;}, wherenis 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
The KeyModifier datatype describes key modifiers in user-interactions.
data KeyModifier =
modCtrl()
| modAlt()
| modShift()
| modCommand();
Describes key modifiers, the keyboards keys Control, Alt, Shift and Command (Super/Windows/Apple key)
2.1.7. Properties
Overview of all visual properties that apply to figures.
-
FProperty -
alias FProperties = list[FProperty]; -
alias computedInt = int(); -
alias computedReal = real(); -
alias computedNum = num(); -
alias computedStr = str(); -
alias computedColor = Color();
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 propertyPin both dimensions to the same valuexy. -
P(num x, num y)sets the value for propertyPto distinct valuesx, respectively,y. -
hP(num x)sets the horizontal value for propertyPtox. -
vP(num y)sets the vertical value for propertyPtoy.
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,strorColor. 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,computedStrorcomputedColor. 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.
Just a few examples to show the spirit:
-
size(10, 20)sets thesizeproperty to 10 (horizontally), respectively 20 (vertically). -
hsize(10)sets thehsizeproperty to the value 10. -
hsize(int(){return 10;})sets thehsizeproperty to the result of executing the argument functionint(){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>
-
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.
-
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
Datatype describing a key on the keyboard.
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);
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
Alignment of figure relative to parent.
FProperty align(num h, num v)
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:
Note that:
-
align(hv)is equivalent tohalign(hv), valign(hv). -
align(h, v)is equivalent tohalign(h), valign(v).
A number of shorthands is provided for common alignment values:
Shorthand |
Corresponds to |
See |
|
:------------ |
:------------------ |
:--------------------- |
|
|
|
[Properties/left] |
|
|
|
[Properties/hcenter] |
|
|
|
[Properties/right] |
|
|
|
[Properties/top] |
|
|
|
[Properties/vcenter] |
|
|
|
[Properties/bottom] |
|
|
|
[Properties/center] |
Also see CompositionModel.
[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]##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##
[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]##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##
area
The desired area for a figure inside a [treemap].
FProperty area(num a)
aspectRatio
The fixed aspect ratio of a figure.
FProperty onClick(void() handler)
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.
[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]##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##
[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]##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##
[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]##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##
bottom
Bottom alignment.
FProperty bottom()
bottom defines bottom alignment.
It sets the vertical alignment to 1.
Note that:
-
bottom()is equivalent tovalign(1.0).
Also see [align], [valign] and CompositionModel.
center
Centered alignment.
FProperty center()
center defines horizontal and vertical centered alignment.
It sets the horizontal and vertical alignment to 0.5.
Note that:
-
center()is equivalent toanchor(0.5, 0.5).
Also see [align] and CompositionModel.
connect
Connection point for figure in an [overlay].
FProperty connect(real h, real v)
Describes where a line connects with this figure. See [hconnect], [vconnect] and [overlay].
endGap
End gap in composition.
FProperty endGap(bool h,bool v)
fillColor
Fill color.
FProperty fillColor(Color c)
FProperty fillColor(str cname)
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.
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name box is not in scope##
[red]##Error: Name fillColor is not in scope##
[red]##Error: Name box 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##
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:
font
Define font to be used for text.
FProperty font(str fname)
Sets the font to be used for text. See fontNames for a list of available fonts.
[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##
[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##
fontBold
Define if text should be rendered bold.
FProperty fontBold(bool b)
See also fontItalic.
fontColor
Define the color to be used for text.
FProperty fontColor(Color c)
FProperty fontColor(str cname)
Sets the color to be used for text:
Set font color c.
Set font color with name cname.
Also see ColorModel.
[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]##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
Defines if text should be rendered italic.
FProperty fontItalic(bool b)
See also fontBold.
fontNames
The available font names.
list[str] fontNames()
Gives a list of names of available fonts.
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]
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]
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]
Error: Name fillColor is not in scope Error: Name box is not in scope Error: Name fillColor is not in scope Error: Name box is not in scope 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]
Error: Name fillColor is not in scope Error: Name box 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 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]
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 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]
Error: Name fillColor is not in scope Error: Name box is not in scope Error: Name size is not in scope 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]
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 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]
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 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]
Error: Name fillColor is not in scope Error: Name box is not in scope Error: Name size is not in scope 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]
Error: Name hshrink 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 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 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]
Error: Name size is not in scope Error: Name lineColor is not in scope Error: Name box is not in scope Error: Name size is not in scope Error: Name lineColor is not in scope Error: Name box is not in scope Error: Name size is not in scope Error: Name lineColor is not in scope Error: Name box is not in scope Error: Name size is not in scope Error: Name lineColor is not in scope Error: Name box is not in scope 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]
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]
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]
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]
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]
Error: Name lineWidth is not in scope Error: Name box is not in scope Error: Name lineWidth is not in scope Error: Name box is not in scope Error: Name lineWidth is not in scope Error: Name box is not in scope Error: Name lineWidth is not in scope Error: Name box is not in scope 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 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]
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]
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]
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]
Error: Name shrink is not in scope Error: Name fillColor is not in scope Error: Name box is not in scope 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]
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]
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 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]
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 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]
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 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]
Error: Name fillColor is not in scope Error: Name box is not in scope Error: Name size 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 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]
Error: Name vshrink is not in scope Error: Name box is not in scope Error: Name fillColor 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}/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]
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: 153605017496 rascal>fac(50); int: 30414093201713378043612608166064768844377641568960512000000000000 rascal>cpuTime() - before; int: 90254743
The code to be measured can also be passed as a function parameter to `cpuTime`: [source,rascal-shell]
rascal>cpuTime( void() { fac(50); } ); int: 304769
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: 1848907702 rascal>fac(50); int: 30414093201713378043612608166064768844377641568960512000000000000 rascal>systemTime() - before; int: 9863231
The code to be measured can also be passed as a function parameter to `systemTime`: [source,rascal-shell]
rascal>systemTime( void() { fac(50); } ); int: 270784
[[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: 152250000000 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":1499089504131,"fac200":1499089504131)
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":152540000000,"fac200":152540000000)
[[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:1114) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RVMonJVM.insnCALLJAVA(RVMonJVM.java:403) 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:790) 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:539) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RVMonJVM.executeRVMProgram(RVMonJVM.java:235) 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:544) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RVMonJVM.executeRVMProgram(RVMonJVM.java:235) 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:798) 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:539) … 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:418) 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:790) … 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:1114) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RVMonJVM.insnCALLJAVA(RVMonJVM.java:403) … 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:1114) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RVMonJVM.insnCALLJAVA(RVMonJVM.java:403) 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:790) 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:539) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RVMonJVM.executeRVMProgram(RVMonJVM.java:235) 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:544) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RVMonJVM.executeRVMProgram(RVMonJVM.java:235) 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:798) 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:539) … 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:418) 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:790) … 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:1114) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RVMonJVM.insnCALLJAVA(RVMonJVM.java:403) … 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:1114) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RVMonJVM.insnCALLJAVA(RVMonJVM.java:403) 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:539) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RVMonJVM.executeRVMProgram(RVMonJVM.java:235) 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:544) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RVMonJVM.executeRVMProgram(RVMonJVM.java:235) 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:418) 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:539) … 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:1114) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RVMonJVM.insnCALLJAVA(RVMonJVM.java:403) … 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:1114) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RVMonJVM.insnCALLJAVA(RVMonJVM.java:403) 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:539) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RVMonJVM.executeRVMProgram(RVMonJVM.java:235) 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:544) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RVMonJVM.executeRVMProgram(RVMonJVM.java:235) 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:418) 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:539) … 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:1114) at org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RVMonJVM.insnCALLJAVA(RVMonJVM.java:403) … 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: -1882458435 rascal>arbInt(); int: -291171395 rascal>arbInt(); int: 1644660168 rascal>arbInt(10); int: 6 rascal>arbInt(10); int: 6 rascal>arbInt(10); int: 7
.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.766881254574376 rascal>arbReal(); real: 0.15482397733720177 rascal>arbReal(); real: 0.08146341351624975
[[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: 1049460242r917586597 rascal>arbRat(); rat: 413518807r111652153 rascal>arbRat(); rat: 2135416057r578847736 rascal>arbRat(10,100); rat: 0r rascal>arbRat(10,100); rat: 1r16 rascal>arbRat(10,100); rat: 0r
[[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>√`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 √`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