Skip to content
Snippets Groups Projects
Commit 7926dea3 authored by Johannes Mey's avatar Johannes Mey
Browse files

initial commit motion grammar test

parents
Branches
No related tags found
No related merge requests found
Showing
with 754 additions and 0 deletions
.gradle/
src/gen
src/gen-res
.idea/
build/
out/
logs/
LICENSE 0 → 100644
BSD 3-Clause License
Copyright (c) 2020, TU Dresden, Software Technology Group
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# Motion Grammar Example
A testbed for a potential *motion grammar*[^1] implementation using JastAdd.
[^1]: Dantam, N., Stilman, M., 2013. The Motion Grammar: Analysis of a Linguistic Method for Robot Control. IEEE Trans. Robot. 29, 704–718. https://doi.org/10.1109/TRO.2013.2239553
plugins {
id "java"
id "application"
id "idea"
id "org.jastadd" version "1.14.5"
}
// General configuration (plugins, settings, dependencies)
group 'de.tudresden.inf.st'
version '0.1'
sourceCompatibility = 11
targetCompatibility = 11
repositories.mavenCentral()
repositories {
maven {
name "gitlab-maven"
url "https://git-st.inf.tu-dresden.de/api/v4/groups/jastadd/-/packages/maven"
}
}
idea.module.generatedSourceDirs += file('src/gen/java')
sourceSets.main.java.srcDir "src/gen/java"
jar.manifest.attributes('Main-Class': 'de.tudresden.inf.st.pnml.Main')
dependencies {
jastadd2 "org.jastadd:jastadd:2.3.5"
implementation group: 'de.tudresden.inf.st', name: 'dumpAstWithPlantuml', version: '0.3.5'
}
// Default run configuration
run {
mainClassName = 'de.tudresden.inf.st.mg.Main'
standardInput = System.in
}
def relastFile = "./src/main/jastadd/MotionGrammar.relast"
// Second phase: RelAst -> JastAdd
task relastToJastAdd(type: JavaExec) {
group = 'Build'
main = "-jar"
args "libs/relast.jar",
"--grammarName=./src/gen/jastadd/MotionGrammar",
"--useJastAddNames",
"--listClass=java.util.ArrayList",
"--jastAddList=JastAddList",
"--resolverHelper",
"--file",
relastFile
inputs.files relastFile
outputs.files file("./src/gen/jastadd/MotionGrammar.ast"), file("./src/gen/jastadd/MotionGrammar.jadd")
}
// Third phase: JastAdd -> Java (using JastAdd Gradle plugin)
jastadd {
configureModuleBuild()
modules {
module("mg") {
java {
basedir "src/"
include "main/**/*.java"
include "gen/**/*.java"
}
jastadd {
basedir "src/"
include "main/jastadd/**/*.ast"
include "main/jastadd/**/*.jadd"
include "main/jastadd/**/*.jrag"
include "gen/jastadd/**/*.ast"
include "gen/jastadd/**/*.jadd"
include "gen/jastadd/**/*.jrag"
}
}
}
cleanGen.doFirst {
delete "src/gen/java/de"
delete "src/gen-res/BuildInfo.properties"
}
module = "mg"
astPackage = 'de.tudresden.inf.st.mg.jastadd.model'
genDir = 'src/gen/java'
buildInfoDir = 'src/gen-res'
// default options are: '--rewrite=cnta', '--safeLazy', '--visitCheck=false', '--cacheCycle=false'
extraJastAddOptions = ['--List=JastAddList'] // '--incremental=param'
}
// Workflow configuration for phases
generateAst.dependsOn relastToJastAdd
//// always run jastadd
//jastadd.outputs.upToDateWhen {false}
jackson_version = 2.9.8
File added
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.4-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
gradlew 0 → 100755
#!/usr/bin/env sh
#
# Copyright 2015 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin or MSYS, switch paths to Windows format before running java
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=`expr $i + 1`
done
case $i in
0) set -- ;;
1) set -- "$args0" ;;
2) set -- "$args0" "$args1" ;;
3) set -- "$args0" "$args1" "$args2" ;;
4) set -- "$args0" "$args1" "$args2" "$args3" ;;
5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=`save "$@"`
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
exec "$JAVACMD" "$@"
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
File added
rootProject.name = 'jastadd-motion-grammar-example'
// Motion Grammar
// generic part
MotionGrammarElement;
// This grammar loads something until it is full, then unloads whatever it has previously loaded.
abstract T : MotionGrammarElement;
T1 : T ::= Load T Unload;
T2 : T ::= Full;
// Tokens
abstract Token : MotionGrammarElement;
Full : Token;
Load : Token;
Unload : Token;
// Environment
World ::= Container;
Container ::= <Capacity:int> <ElementCount:int>;
\ No newline at end of file
aspect SemanticActions {
public void MotionGrammarElement.action(World world) {
System.out.println("performing semantic action for element " + getClass().getSimpleName());
}
public void Load.action(World world) {
System.out.println("performing semantic action for element Load");
System.out.print(" " + world);
world.getContainer().setElementCount(world.getContainer().getElementCount() + 1);
System.out.println(" -> " + world);
}
public void Unload.action(World world) {
System.out.println("performing semantic action for element Unload");
System.out.print(" " + world);
world.getContainer().setElementCount(world.getContainer().getElementCount() - 1);
System.out.println(" -> " + world);
}
}
\ No newline at end of file
aspect Tokens {
}
\ No newline at end of file
aspect JastAddAPIExtension {
/**
* removes the object from the AST, i.e. removes the reference from its parent to the object
*
* Please note that any intrinsic non-containment relations to the object are not removed.
* @return true, if the object had a parent.
*/
public boolean ASTNode.removeSelf() {
if (getParent() == null) {
return false;
} else {
for (int childIndex = 0; childIndex < getParent().numChildren(); childIndex++) {
if (getParent().getChild(childIndex) == this) {
getParent().removeChild(childIndex);
return true;
}
}
}
throw new RuntimeException("unable to remove child, because it was not contained in its parent!");
}
}
aspect World {
public static final int World.MAX_CAPACITY = 10;
public static World World.initialWorld() {
Container c = new Container();
java.util.Random r = new java.util.Random();
c.setCapacity(r.nextInt(MAX_CAPACITY));
c.setElementCount(r.nextInt(c.getCapacity()));
return new World(c);
}
@Override
public String World.toString() {
return print();
}
}
\ No newline at end of file
aspect World {
syn String World.print() = "[World " + getContainer().print() + "]";
syn String Container.print() = "[Container " + getElementCount() + "/" + getCapacity() + "]";
public enum TokenType {UNDEFINED,FULL,LOAD,UNLOAD; }
public static TokenType Token.type() {return TokenType.UNDEFINED; }
public static TokenType Full.type() {return TokenType.FULL; }
public static TokenType Load.type() {return TokenType.LOAD; }
public static TokenType Unload.type() {return TokenType.UNLOAD; }
public java.util.Optional<Full> World.parseFull() {
System.out.print("Trying to parse token <Full>... ");
if (getContainer().getCapacity() <= getContainer().getElementCount()) {
System.out.println("success");
return java.util.Optional.of(new Full());
} else {
System.out.println("failure");
return java.util.Optional.empty();
}
}
public java.util.Optional<Load> World.parseLoad() {
System.out.print("Trying to parse token <Load>... ");
// TODO should we check if loading is possible?
System.out.println("success");
return java.util.Optional.of(new Load());
}
public java.util.Optional<Unload> World.parseUnload() {
System.out.print("Trying to parse token <Unload>... ");
// TODO should we check if unloading is possible?
System.out.println("success");
return java.util.Optional.of(new Unload());
}
}
\ No newline at end of file
package de.tudresden.inf.st.mg;
import de.tudresden.inf.st.mg.jastadd.model.T;
import de.tudresden.inf.st.mg.jastadd.model.World;
import de.tudresden.inf.st.jastadd.dumpAst.ast.Dumper;
import java.io.IOException;
import java.nio.file.Path;
public class Main {
public static void main(String[] args) {
World world = World.initialWorld();
WorldParser parser = new WorldParser(world);
try {
T result = parser.parseT();
Dumper.read(result).dumpAsPNG(Path.of("test.png")).dumpAsSource(Path.of("test.plantuml"));
} catch (WorldParser.ParseException | IOException e) {
e.printStackTrace();
}
}
}
package de.tudresden.inf.st.mg;
import de.tudresden.inf.st.mg.jastadd.model.*;
import java.util.Arrays;
import java.util.Optional;
import java.util.stream.Collectors;
public class WorldParser {
private final World world_;
private Load peekedLoad_ = null;
private Unload peekedUnload_ = null;
private Full peekedFull_ = null;
public WorldParser(World world) {
this.world_ = world;
}
T parseT() throws ParseException {
T result;
// try to parse a T
if (peekFull()) {
result = parseT2();
} else if (peekLoad()) {
result = parseT1();
} else {
throw new ParseException("T", Load.type(), Full.type());
}
// semantic action for T
result.action(world_);
return result;
}
T1 parseT1() throws ParseException {
T1 result = new T1();
result.setLoad(parseLoad());
result.setT(parseT());
result.setUnload(parseUnload());
// semantic action for T1
result.action(world_);
return result;
}
T2 parseT2() throws ParseException {
T2 result = new T2();
result.setFull(parseFull());
// semantic action for T2
result.action(world_);
return result;
}
boolean peekLoad() {
Optional<Load> optional = world_.parseLoad();
optional.ifPresent(value -> peekedLoad_ = value);
return optional.isPresent();
}
Load parseLoad() throws ParseException {
Load result;
if (peekedLoad_ != null) {
result = peekedLoad_;
peekedLoad_ = null; // TODO check if all peeked values are actually parsed afterwards
} else {
Optional<Load> optional = world_.parseLoad();
if (optional.isEmpty()) {
throw new ParseException(Load.type());
}
result = optional.get();
}
// semantic action for Unload
result.action(world_);
return result;
}
boolean peekUnload() {
Optional<Unload> optional = world_.parseUnload();
optional.ifPresent(value -> peekedUnload_ = value);
return optional.isPresent();
}
Unload parseUnload() throws ParseException {
Unload result;
if (peekedUnload_ != null) {
result = peekedUnload_;
peekedUnload_ = null; // TODO check if all peeked values are actually parsed afterwards
} else {
Optional<Unload> optional = world_.parseUnload();
if (optional.isEmpty()) {
throw new ParseException(Unload.type());
}
result = optional.get();
}
// semantic action for Unload
result.action(world_);
return result;
}
boolean peekFull() {
Optional<Full> optional = world_.parseFull();
optional.ifPresent(value -> peekedFull_ = value);
return optional.isPresent();
}
Full parseFull() throws ParseException {
Full result;
if (peekedFull_ != null) {
result = peekedFull_;
peekedFull_ = null; // TODO check if all peeked values are actually parsed afterwards
} else {
Optional<Full> optional = world_.parseFull();
if (optional.isEmpty()) {
throw new ParseException(Full.type());
}
result = optional.get();
}
// semantic action for Unload
result.action(world_);
return result;
}
public static class ParseException extends Exception {
public ParseException(String ruleName, TokenType... expectedTokens) {
super("Unable to parse nonterminal " + ruleName + ". Expected tokens " + Arrays.stream(expectedTokens).map(Enum::toString).collect(Collectors.joining(", ")) + ".");
}
public ParseException(TokenType expectedToken) {
super("Unable to parse token " + expectedToken.name() + ".");
}
}
}
@startuml
scale 1.0
object "T1@2040495657" as node0 {
}
object "T2@824009085" as node2 {
}
node0 *-- node1 : Load
node0 *-- node2 : T
node0 *-- node4 : Unload
node2 *-- node3 : Full
@enduml
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment