diff --git a/.gitignore b/.gitignore index e7ded7918..e24fe0bbb 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,78 @@ target/ -bin/ +classes/ +tools/eclipse/plugins/org.scribble.*/bin/ .classpath .project +.checkstyle .settings/ +.DS_Store +*~ +*.swp +*.bak +*.versionsBackup + +.idea +**/*.iml + +javadoc + + +## +#scribble-demos/scrib + +scribble-demos/scrib/Makefile +scribble-demos/scrib/tutorial/src/tutorial/adder/Adder/ +scribble-demos/scrib/betty16/src/betty16/lec1/httplong/HttpLong/ +scribble-demos/scrib/betty16/src/betty16/lec1/httpshort/HttpShort/ +scribble-demos/scrib/betty16/src/betty16/lec2/adder/Adder/ +scribble-demos/scrib/betty16/src/betty16/lec2/smtp/Smtp/ +scribble-demos/scrib/bettybook/src/bettybook/http/longv/HttpLong/ +scribble-demos/scrib/bettybook/src/bettybook/http/shortv/HttpShort/ +scribble-demos/scrib/bettybook/src/bettybook/math/scrib/Math/ +scribble-demos/scrib/coco/src/coco/fibo/Fibo/ +scribble-demos/scrib/coco/src/coco/smtp/Smtp/ +scribble-demos/scrib/fase16/src/fase16/adder/Adder/ +scribble-demos/scrib/fase16/src/fase16/smtp/Smtp/ +scribble-demos/scrib/fib/src/fib/Fib/ +scribble-demos/scrib/http/src/http/longvers/HttpLong/ +scribble-demos/scrib/http/src/http/shortvers/HttpShort/ +scribble-demos/scrib/loan/src/loan/LoanApplication/ +scribble-demos/scrib/smtp/src/smtp/Smtp/ +scribble-demos/scrib/travel/src/travel/Travel/ +scribble-demos/scrib/tutorial/src/tutorial/adder/Adder/ + + +## +#scribble-test/src/test/scrib + +scribble-test/src/test/scrib/exercise/calculator/EProtocol/ +scribble-test/src/test/scrib/exercise/voting/EProtocol/ + +scribble-test/src/test/scrib/demo/fase17/travel/TravelAgent/ +scribble-test/src/test/scrib/demo/fase17/travel2/TravelAgent2/ +scribble-test/src/test/scrib/demo/highlow/HighLow/ + +scribble-test/src/test/scrib/scratch/scratch1/ +scribble-test/src/test/scrib/scratch/scratch2/ +scribble-test/src/test/scrib/test/foo/Foo/ +scribble-test/src/test/scrib/test/test1/ +scribble-test/src/test/scrib/test/test2/ +scribble-test/src/test/scrib/test/test3/ +scribble-test/src/test/scrib/test/test4/ +scribble-test/src/test/scrib/test/test5/ +scribble-test/src/test/scrib/test/test6/ +scribble-test/src/test/scrib/test/test7/ +scribble-test/src/test/scrib/test/test8/ +scribble-test/src/test/scrib/test/test9/ + +scribble-test/src/test/scrib/test/test2/Test2/ +scribble-test/src/test/scrib/test/test3/Test3/ +scribble-test/src/test/scrib/test/test4/Test4/ +scribble-test/src/test/scrib/test/test5/Test5/ +scribble-test/src/test/scrib/test/test6/Test6/ +scribble-test/src/test/scrib/test/test7/Test7/ + + +bin/scribblec.sh +permissions-fix.sh + diff --git a/.mvn/wrapper/maven-wrapper.jar b/.mvn/wrapper/maven-wrapper.jar new file mode 100644 index 000000000..c6feb8bb6 Binary files /dev/null and b/.mvn/wrapper/maven-wrapper.jar differ diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 000000000..56bb0164e --- /dev/null +++ b/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1 @@ +distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.0/apache-maven-3.5.0-bin.zip \ No newline at end of file diff --git a/.settings.xml b/.settings.xml new file mode 100644 index 000000000..8fbe094c3 --- /dev/null +++ b/.settings.xml @@ -0,0 +1,28 @@ + + + + + sonatype + ${env.SONATYPE_USER} + ${env.SONATYPE_PASSWORD} + + + bintray + ${env.BINTRAY_USER} + ${env.BINTRAY_KEY} + + + jfrog-snapshots + ${env.BINTRAY_USER} + ${env.BINTRAY_KEY} + + + github.com + ${env.GH_USER} + ${env.GH_TOKEN} + + + diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 000000000..0f95eaf29 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,43 @@ +sudo: required +dist: trusty + +language: java +jdk: +- oraclejdk8 + +cache: + directories: + - $HOME/.m2/repository + +before_install: + # allocate commits to CI, not the owner of the deploy key + - git config user.name "scribbleci" + - git config user.email "ci@scribble.org" + + # setup https authentication credentials, used by ./mvnw release:prepare + - git config credential.helper "store --file=.git/credentials" + - echo "https://$GH_TOKEN:@github.com" > .git/credentials + +install: + # Override default travis to use the maven wrapper + - ./mvnw install -DskipTests=true -Dmaven.javadoc.skip=true -B -V + +script: + - ./travis/publish.sh + +branches: + except: + - /^[0-9]/ + +env: + global: + # Ex. travis encrypt -r org/repo GH_TOKEN=XXX-https://github.com/settings/tokens-XXX + - secure: "EZHcIA6vC1eUqj1vMRlsMh+wBkdEejPNIy7ZDpKkf6Ntsv8COTyKbzr/mDWyl8W8BgieiYKvLiCJQpUj8ZNagGTUw8znngW6XQhDZJTuuimuyq9RikK1+owd+BNNybMTIbe21CuKpEwWranbINBJvu/Wi7IHXuqqcClQJ/fDApE=" + # Ex. travis encrypt -r org/repo SONATYPE_USER=your_sonatype_account + - secure: "zD27+IC5mFIMz5lvL+cwjAeXHEdJuAFwl0M6lBr5g5/4IqInPq5bXyVeQI5vSMmKa9xk9tdx4tvRSnIqIvSqrXj0t3yl9b3lXmFFbOTtSem7Mu8MhIdSTcXkPCdt0I/1MUmtJpExQ29BwNZWwiSXeOBngxrgZTpUUhi806JGpME=" + # Ex. travis encrypt -r org/repo SONATYPE_PASSWORD=your_sonatype_password + - secure: "ewf2f+EBpizqXJ9i90ekHbvODH59KKFulMdSko6qhle6E6IsTK5tuWzwSir3lRqTRAiVoJ/F3IR32fkzkMv+KaZCookN8jmFb/OI58x8jzTRz8+pJkSCMWZ+pUgZUZt51D/85pTkw3ftacVQt3oYP4wPIkJdF0c3UArTjOsapso=" + # Ex. travis encrypt -r org/repo BINTRAY_USER=your_github_account + - secure: "Mofhc9/R1c3r1Ve4ZTmIX/gMb737FqvaOrAIjVSaaSW/T/pSqgh8AZu0bndVrQZ4YSpkmZcmhdO8NX0MtrxHBQMddY/DpE2o0G4oAkRUVtYUz7o5rL8Q5xVtQUngzaMrpFPBF2JlAoK+/iJDF839wGuQdiV9koaViOMt61yVRHw=" + # Ex. travis encrypt -r org/repo BINTRAY_KEY=xxx-https://bintray.com/profile/edit-xxx + - secure: "yxiVTp3pD6UPex4G69tbYkXB5QWqQsu4vlUrS/RRaxOW7TWeZRl4hXtqOUwL3AxoZcJFivE4OcqdUlw2IOYVBtrVTngQ/ZAVefdD/ohNPO3+6SdP2uzqdnqAxEi7kJBqaCvUG1uEPdp+S+w5f6VcK0rfxgK+IRUxREhDmCFuCg8=" diff --git a/CHANGES.md b/CHANGES.md new file mode 100644 index 000000000..1feda4399 --- /dev/null +++ b/CHANGES.md @@ -0,0 +1,27 @@ +Scribble 0.4 +--- + +- Updated scribblec script interface: check + + ./scribblec --help + + for new usages. + +- The core tooling has been refactored to support an alternative validation + method. To obtain more details on safety/progress errors, use the -V + command line flag. + + N.B. the -oldwf command line flag allows to use only the well-formedness + from the previous version of the tool. Warning: no guarantees are offered + when validating newer Scribble features using -oldwf. + +- Most Scribble demos that were previously in + + modules/core/src/test/scrib/demo + + have been relocated to + + modules/demos/scrib/ + + Some demo files have also been renamed or repackaged. + \ No newline at end of file diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 000000000..c0132670b --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,14 @@ +Copyright 2012 Scribble 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 + + http://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. + diff --git a/README b/README deleted file mode 100644 index 139597f9c..000000000 --- a/README +++ /dev/null @@ -1,2 +0,0 @@ - - diff --git a/README.md b/README.md new file mode 100644 index 000000000..408b44a3a --- /dev/null +++ b/README.md @@ -0,0 +1,108 @@ +[![Build Status][ci-img]][ci] [![Released Version][maven-img]][maven] + +# Java Tooling for Scribble + +This project provides Java tooling/libraries for the Scribble multi-party +protocol definition language. + + +## Building from source + +First step is to clone this git repository locally. Once available, run the +following maven command to build the project: + + mvn [clean] install + +The distribution will be available from the folder _scribble-dist/target_. The +contents of the zip is: + +- lib jars needed to run the scribble-java tool +- scribblec.sh script for running the command line tool + + +## Command line usage: + +Assuming scribblec.sh has been extracted from the above zip: + +> List command line options. + + ./scribblec.sh --help + +Assuming a Scribble module file Test.scr in the same directory: + +> Check well-formedness of global protocols in module Test.scr. + + ./scribblec.sh Test.scr + +Note: try the -V command line flag to obtain full traces for errors (and other + details). + +> Project local protocol for role "C" of protocol "Proto" in Test.scr + + ./scribblec.sh Test.scr -project Proto C + + +> Print (a dot representation of) the Endpoint FSM for role "C" of protocol + "Proto" in Test.scr + + ./scribblec.sh Test.scr -fsm Proto C + + +> Generate Java Endpoint API for role "C" of protocol "Proto" + in Test.scr + + ./scribblec.sh -d . Test.scr -api Proto C + +Note: omitting the -d argument will print the output to stdout. + + +## Examples: + +> To write a HelloWorld protocol in Test.scr (e.g., for the commands listed above): + + echo 'module Test; global protocol Proto(role C, role S) { Hello() from C to S; }' > Test.scr + + +Further examples can be found in: + + https://github.com/scribble/scribble-java/tree/master/scribble-demos/scrib + +The distribution zip does not include these examples. They can be obtained as +part of the source repository, or separately via the above link. + +> E.g. To generate the Java Endpoint API for role "C" in the "Adder" protocol from the + Scribble-Java tutorial (http://www.scribble.org/docs/scribble-java.html#QUICK) + + ./scribblec.sh scribble-demos/scrib/tutorial/src/tutorial/adder/Adder.scr + -d scribble-demos/scrib/tutorial/src/ -api Adder C + + +## Alternative command line usage: + +To run the Scribble tool directly via java, try + + ./scribblec.sh --verbose [args] + +to see the underlying java command with main class, classpath and other args. + +Or try (from Nick Ng): + + mvn dependency:build-classpath -Dmdep.outputFile=classpath + + java -cp $(cat dist/classpath) org.scribble.cli.CommandLine [args] MyModule.scr + + +## Issue reporting + +Bugs and issues can be reported via the github Issues facility. + +Or email r.z.h.hu1234 [at] herts.ac.uk excluding the 1234. + + + [ci-img]: https://travis-ci.org/scribble/scribble-java.svg?branch=master + [ci]: https://travis-ci.org/scribble/scribble-java + [cov-img]: https://coveralls.io/repos/github/scribble/scribble-java/badge.svg?branch=master + [cov]: https://coveralls.io/github/scribble/scribble-java?branch=master + [maven-img]: https://img.shields.io/maven-central/v/org.scribble/scribble-core.svg?maxAge=2592000 + [maven]: http://search.maven.org/#search%7Cga%7C1%7Cscribble-core + diff --git a/RELEASE.md b/RELEASE.md new file mode 100644 index 000000000..b8775e2e2 --- /dev/null +++ b/RELEASE.md @@ -0,0 +1,18 @@ +# Scribble Release Process + +This repo uses semantic versions. Please keep this in mind when choosing version numbers. + +1. **Alert others you are releasing** + + There should be no commits made to master while the release is in progress (about 10 minutes). Before you start + a release, alert others so that they don't accidentally merge + anything. If they do, and the build fails because of that, you'll have to recreate the release tag described below. + +1. **Push a git tag** + + The tag should be of the format `release-N.M.L`, ex `git tag release-3.7.1; git push origin release-3.7.1`. + +1. **Wait for Travis CI** + + This part is controlled by [`travis/publish.sh`](travis/publish.sh). It creates a bunch of new commits, bumps + the version, publishes artifacts, and syncs to Maven Central. \ No newline at end of file diff --git a/apidocs/pom.xml b/apidocs/pom.xml deleted file mode 100644 index 20141a4ec..000000000 --- a/apidocs/pom.xml +++ /dev/null @@ -1,61 +0,0 @@ - - 4.0.0 - org.scribble - apidocs - pom - 2.1.0-SNAPSHOT - Scribble::APIDocs - - - org.scribble - parent - 2.1.0-SNAPSHOT - - - - - org.scribble.bundles - org.scribble.common - ${scribble.bundles.version} - - - org.scribble.bundles - org.scribble.protocol - ${scribble.bundles.version} - - - org.scribble.bundles - org.scribble.protocol.monitor - ${scribble.bundles.version} - - - - - - - maven-assembly-plugin - 2.2-beta-2 - - - bin - process-resources - - single - - - scribble-core-apidocs-${project.version} - false - - src/main/assembly/bin.xml - - - - - - - - - - diff --git a/apidocs/src/main/assembly/bin.xml b/apidocs/src/main/assembly/bin.xml deleted file mode 100644 index ec255b3ad..000000000 --- a/apidocs/src/main/assembly/bin.xml +++ /dev/null @@ -1,45 +0,0 @@ - - - - - bin - true - - zip - - - - - - ../bundles/org.scribble.common/target/javadoc - /apidocs/common - - - - ../bundles/org.scribble.protocol/target/javadoc - /apidocs/protocol - - - - ../bundles/org.scribble.protocol.monitor/target/javadoc - /apidocs/monitor - - - - - diff --git a/build/pom.xml b/build/pom.xml deleted file mode 100644 index fd8d95297..000000000 --- a/build/pom.xml +++ /dev/null @@ -1,31 +0,0 @@ - - 4.0.0 - org.scribble - build - 2.1.0-SNAPSHOT - jar - Scribble::Build - - - org.scribble - parent - 2.1.0-SNAPSHOT - - - - - - - - - org.apache.maven.plugins - maven-deploy-plugin - - true - - - - - - diff --git a/build/src/main/resources/checkstyle/checkstyle.xml b/build/src/main/resources/checkstyle/checkstyle.xml deleted file mode 100644 index 44e0015b6..000000000 --- a/build/src/main/resources/checkstyle/checkstyle.xml +++ /dev/null @@ -1,218 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/build/src/main/resources/checkstyle/suppressions.xml b/build/src/main/resources/checkstyle/suppressions.xml deleted file mode 100644 index dc2694e1a..000000000 --- a/build/src/main/resources/checkstyle/suppressions.xml +++ /dev/null @@ -1,42 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/build/src/main/resources/findbugs/findbugs-exclude.xml b/build/src/main/resources/findbugs/findbugs-exclude.xml deleted file mode 100644 index 4a85c0fa9..000000000 --- a/build/src/main/resources/findbugs/findbugs-exclude.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/bundles/org.scribble.command/META-INF/MANIFEST.MF b/bundles/org.scribble.command/META-INF/MANIFEST.MF deleted file mode 100644 index 2dcd792b9..000000000 --- a/bundles/org.scribble.command/META-INF/MANIFEST.MF +++ /dev/null @@ -1,27 +0,0 @@ -Bundle-Name: Scribble Command Line -Bundle-Description: A bundle provides command line access to Scribble functionality -Bundle-Vendor: www.scribble.org -Bundle-Version: 2.1.0.SNAPSHOT -Bundle-Activator: org.scribble.command.osgi.Activator -Export-Package: org.scribble.command -Import-Package: org.osgi.framework, - org.scribble.common.logging, - org.scribble.common.resource, - org.scribble.protocol, - org.scribble.protocol.conformance, - org.scribble.protocol.export, - org.scribble.protocol.model, - org.scribble.protocol.monitor, - org.scribble.protocol.monitor.model, - org.scribble.protocol.monitor.util, - org.scribble.protocol.parser, - org.scribble.protocol.projection, - org.scribble.protocol.validation -Bundle-SymbolicName: org.scribble.command -Bundle-RequiredExecutionEnvironment: J2SE-1.5 -Provide-Package: org.scribble.command, - org.scribble.command.conforms, - org.scribble.command.parse, - org.scribble.command.project, - org.scribble.command.simulate, - org.scribble.command.validate diff --git a/bundles/org.scribble.command/build.properties b/bundles/org.scribble.command/build.properties deleted file mode 100644 index 9fc6e0c06..000000000 --- a/bundles/org.scribble.command/build.properties +++ /dev/null @@ -1,12 +0,0 @@ -source.. = src/main/java/ -output.. = bin/ -bin.includes = META-INF/,\ - .,\ - LICENSE.txt -src.includes = .classpath,\ - .project,\ - LICENSE.txt,\ - META-INF/,\ - build.properties,\ - pom.xml,\ - src/ diff --git a/bundles/org.scribble.command/pom.xml b/bundles/org.scribble.command/pom.xml deleted file mode 100644 index 389b5710e..000000000 --- a/bundles/org.scribble.command/pom.xml +++ /dev/null @@ -1,137 +0,0 @@ - - 4.0.0 - org.scribble.bundles - org.scribble.command - jar - 2.1.0-SNAPSHOT - Scribble::Bundles::Command - - - org.scribble - bundles - 2.1.0-SNAPSHOT - - - - - org.osgi - org.osgi.core - ${osgi.version} - - - org.scribble.bundles - org.scribble.common - ${scribble.bundles.version} - - - org.scribble.bundles - org.scribble.protocol - ${scribble.bundles.version} - - - org.scribble.bundles - org.scribble.protocol.parser - ${scribble.bundles.version} - - - org.scribble.bundles - org.scribble.protocol.monitor - ${scribble.bundles.version} - - - junit - junit - test - - - - - ${artifactId}_${scribble.version} - - - - - - - org.apache.maven.plugins - maven-jar-plugin - 2.2 - - - META-INF/MANIFEST.MF - - - - - org.apache.maven.plugins - maven-javadoc-plugin - 2.2 - - true - - - - - - - org.codehaus.mojo - jboss-packaging-maven-plugin - 2.0-beta-1 - true - - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 2.0.2 - - - 1.5 - 1.5 - false - false - - - - - - org.apache.maven.plugins - maven-source-plugin - - - attach-sources - verify - - jar - - - - - - maven-surefire-plugin - - - **/*TestCase.java - **/*Test.java - - - - - - - - - - org.apache.maven.plugins - maven-surefire-report-plugin - - - - - diff --git a/bundles/org.scribble.command/src/main/java/org/scribble/command/Command.java b/bundles/org.scribble.command/src/main/java/org/scribble/command/Command.java deleted file mode 100644 index 3f2683d42..000000000 --- a/bundles/org.scribble.command/src/main/java/org/scribble/command/Command.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright 2009 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.command; - -/** - * This interface represents a command. - * - */ -public interface Command { - - /** - * This method returns the name of the command. - * - * @return The name - */ - public String getName(); - - /** - * This method returns the description. - * - * @return The description - */ - public String getDescription(); - - /** - * This method executes the command with the - * given arguments. - * - * @param args The arguments - * @return Whether the command executed - */ - public boolean execute(String[] args); - -} diff --git a/bundles/org.scribble.command/src/main/java/org/scribble/command/conforms/ConformsCommand.java b/bundles/org.scribble.command/src/main/java/org/scribble/command/conforms/ConformsCommand.java deleted file mode 100644 index ecd8d354f..000000000 --- a/bundles/org.scribble.command/src/main/java/org/scribble/command/conforms/ConformsCommand.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Copyright 2009 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.command.conforms; - -import org.scribble.common.logging.Journal; -import org.scribble.common.resource.Content; -import org.scribble.common.resource.DefaultResourceLocator; -import org.scribble.common.resource.FileContent; -import org.scribble.protocol.DefaultProtocolContext; -import org.scribble.protocol.conformance.LoggingConformanceHandler; -import org.scribble.protocol.conformance.ProtocolConformer; -import org.scribble.protocol.parser.ProtocolParserManager; - -/** - * This class implements the conformance checking command. - * - */ -public class ConformsCommand implements org.scribble.command.Command { - - private Journal _journal=null; - private ProtocolParserManager _protocolParserManager=null; - private ProtocolConformer _conformer=null; - - /** - * Default constructor. - */ - public ConformsCommand() { - } - - /** - * This method sets the journal. - * - * @param journal The journal - */ - public void setJournal(Journal journal) { - _journal = journal; - } - - /** - * This method sets the protocol parser manager. - * - * @param parser The parser manager - */ - public void setProtocolParserManager(ProtocolParserManager parser) { - _protocolParserManager = parser; - } - - /** - * This method sets the protocol conformer. - * - * @param conformer The protocol conformer - */ - public void setConformer(ProtocolConformer conformer) { - _conformer = conformer; - } - - /** - * {@inheritDoc} - */ - public String getName() { - return ("conforms"); - } - - /** - * {@inheritDoc} - */ - public String getDescription() { - return ("Check two Scribble descriptions for conformance"); - } - - /** - * {@inheritDoc} - */ - public boolean execute(String[] args) { - boolean ret=false; - - if (args.length == 2) { - java.io.File f1=new java.io.File(args[0]); - java.io.File f2=new java.io.File(args[1]); - - if (!f1.exists()) { - _journal.error("File not found '"+args[0]+"'", null); - } else if (!f2.exists()) { - _journal.error("File not found '"+args[1]+"'", null); - } else { - try { - Content content1=new FileContent(f1); - - org.scribble.protocol.model.ProtocolModel p1= - _protocolParserManager.parse(new DefaultProtocolContext(_protocolParserManager, - new DefaultResourceLocator(f1.getParentFile())), - content1, _journal); - - Content content2=new FileContent(f2); - - org.scribble.protocol.model.ProtocolModel p2= - _protocolParserManager.parse(new DefaultProtocolContext(_protocolParserManager, - new DefaultResourceLocator(f2.getParentFile())), - content2, _journal); - - if (p1 != null && p2 != null) { - _conformer.conforms(p1, p2, new LoggingConformanceHandler(_journal)); - - ret = true; - } - } catch (Exception e) { - _journal.error("Failed to check conformance of '" - +args[0]+"' against '"+args[1]+"': "+e, null); - e.printStackTrace(); - } - } - } else { - _journal.error("CONFORMS EXPECTING 2 PARAMETERS", null); - } - - return (ret); - } -} diff --git a/bundles/org.scribble.command/src/main/java/org/scribble/command/osgi/Activator.java b/bundles/org.scribble.command/src/main/java/org/scribble/command/osgi/Activator.java deleted file mode 100644 index e512d25cd..000000000 --- a/bundles/org.scribble.command/src/main/java/org/scribble/command/osgi/Activator.java +++ /dev/null @@ -1,495 +0,0 @@ -/* - * Copyright 2009 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.command.osgi; - -import java.util.Properties; - -import org.osgi.framework.BundleActivator; -import org.osgi.framework.BundleContext; -import org.osgi.framework.ServiceEvent; -import org.osgi.framework.ServiceListener; -import org.osgi.framework.ServiceReference; -import org.scribble.command.Command; -import org.scribble.command.conforms.ConformsCommand; -import org.scribble.command.parse.ParseCommand; -import org.scribble.command.project.ProjectCommand; -import org.scribble.command.simulate.SimulateCommand; -import org.scribble.command.validate.ValidateCommand; -import org.scribble.common.logging.Journal; -import org.scribble.protocol.conformance.ProtocolConformer; -import org.scribble.protocol.export.ProtocolExportManager; -import org.scribble.protocol.monitor.ProtocolMonitor; -import org.scribble.protocol.parser.ProtocolParserManager; -import org.scribble.protocol.projection.ProtocolProjector; -import org.scribble.protocol.validation.ProtocolValidationManager; - -/** - * Activator. - * - */ -public class Activator implements BundleActivator { - - /** - * Start the bundle. - * - * @param context The context - * @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext) - */ - public void start(final BundleContext context) { - final Commands commands=new Commands(); - Properties props = new Properties(); - - // Register parse command - commands.setParseCommand(new ParseCommand()); - - context.registerService(Command.class.getName(), - commands.getParseCommand(), props); - - // Register validate command - commands.setValidateCommand(new ValidateCommand()); - - context.registerService(Command.class.getName(), - commands.getValidateCommand(), props); - - // Register validate command - commands.setConformsCommand(new ConformsCommand()); - - context.registerService(Command.class.getName(), - commands.getConformsCommand(), props); - - // Register project command - commands.setProjectCommand(new ProjectCommand()); - - context.registerService(Command.class.getName(), - commands.getProjectCommand(), props); - - // Register simulate command - commands.setSimulateCommand(new SimulateCommand()); - - context.registerService(Command.class.getName(), - commands.getSimulateCommand(), props); - - // Register service listeners to establish dependent - // components - ServiceListener[] sl=new ServiceListener[7]; - - sl[0] = new ServiceListener() { - public void serviceChanged(ServiceEvent ev) { - ServiceReference sr = ev.getServiceReference(); - switch(ev.getType()) { - case ServiceEvent.REGISTERED: - ProtocolValidationManager vm= - (ProtocolValidationManager)context.getService(sr); - commands.setProtocolValidationManager(vm); - break; - case ServiceEvent.UNREGISTERING: - break; - } - } - }; - - sl[1] = new ServiceListener() { - public void serviceChanged(ServiceEvent ev) { - ServiceReference sr = ev.getServiceReference(); - switch(ev.getType()) { - case ServiceEvent.REGISTERED: - Journal journal= - (Journal)context.getService(sr); - commands.setJournal(journal); - break; - case ServiceEvent.UNREGISTERING: - break; - } - } - }; - - sl[2] = new ServiceListener() { - public void serviceChanged(ServiceEvent ev) { - ServiceReference sr = ev.getServiceReference(); - switch(ev.getType()) { - case ServiceEvent.REGISTERED: - ProtocolParserManager pp= - (ProtocolParserManager)context.getService(sr); - commands.setProtocolParserManager(pp); - break; - case ServiceEvent.UNREGISTERING: - break; - } - } - }; - - sl[3] = new ServiceListener() { - public void serviceChanged(ServiceEvent ev) { - ServiceReference sr = ev.getServiceReference(); - switch(ev.getType()) { - case ServiceEvent.REGISTERED: - ProtocolConformer conformer= - (ProtocolConformer)context.getService(sr); - commands.setProtocolConformer(conformer); - break; - case ServiceEvent.UNREGISTERING: - break; - } - } - }; - - sl[4] = new ServiceListener() { - public void serviceChanged(ServiceEvent ev) { - ServiceReference sr = ev.getServiceReference(); - switch(ev.getType()) { - case ServiceEvent.REGISTERED: - ProtocolProjector projector= - (ProtocolProjector)context.getService(sr); - commands.setProtocolProjector(projector); - break; - case ServiceEvent.UNREGISTERING: - break; - } - } - }; - - sl[5] = new ServiceListener() { - public void serviceChanged(ServiceEvent ev) { - ServiceReference sr = ev.getServiceReference(); - switch(ev.getType()) { - case ServiceEvent.REGISTERED: - ProtocolExportManager em= - (ProtocolExportManager)context.getService(sr); - commands.setProtocolExportManager(em); - break; - case ServiceEvent.UNREGISTERING: - break; - } - } - }; - - sl[6] = new ServiceListener() { - public void serviceChanged(ServiceEvent ev) { - ServiceReference sr = ev.getServiceReference(); - switch(ev.getType()) { - case ServiceEvent.REGISTERED: - ProtocolMonitor pm= - (ProtocolMonitor)context.getService(sr); - commands.setProtocolMonitor(pm); - break; - case ServiceEvent.UNREGISTERING: - break; - } - } - }; - - initCommands(context, commands, sl); - } - - /** - * This method initializes the commands. - * - * @param context The context - * @param commands The commands - * @param sl The service listeners - */ - protected void initCommands(BundleContext context, Commands commands, ServiceListener[] sl) { - - String filter1 = "(objectclass=" + ProtocolValidationManager.class.getName() + ")"; - String filter2 = "(objectclass=" + Journal.class.getName() + ")"; - String filter3 = "(objectclass=" + ProtocolParserManager.class.getName() + ")"; - String filter4 = "(objectclass=" + ProtocolConformer.class.getName() + ")"; - String filter5 = "(objectclass=" + ProtocolProjector.class.getName() + ")"; - String filter6 = "(objectclass=" + ProtocolExportManager.class.getName() + ")"; - String filter7 = "(objectclass=" + ProtocolMonitor.class.getName() + ")"; - - - try { - ServiceReference sref=context.getServiceReference(ProtocolValidationManager.class.getName()); - ProtocolValidationManager pvm=null; - - if (sref != null) { - pvm = (ProtocolValidationManager)context.getService(sref); - } - - if (pvm != null) { - commands.setProtocolValidationManager(pvm); - } else { - context.addServiceListener(sl[0], filter1); - } - - sref=context.getServiceReference(Journal.class.getName()); - Journal journal=null; - - if (sref != null) { - journal = (Journal)context.getService(sref); - } - - if (journal != null) { - commands.setJournal(journal); - } else { - context.addServiceListener(sl[1], filter2); - } - - sref=context.getServiceReference(ProtocolParserManager.class.getName()); - ProtocolParserManager pp=null; - - if (sref != null) { - pp = (ProtocolParserManager)context.getService(sref); - } - - if (pp != null) { - commands.setProtocolParserManager(pp); - } else { - context.addServiceListener(sl[2], filter3); - } - - sref=context.getServiceReference(ProtocolConformer.class.getName()); - ProtocolConformer pc=null; - - if (sref != null) { - pc = (ProtocolConformer)context.getService(sref); - } - - if (pc != null) { - commands.setProtocolConformer(pc); - } else { - context.addServiceListener(sl[3], filter4); - } - - sref=context.getServiceReference(ProtocolProjector.class.getName()); - ProtocolProjector ppj=null; - - if (sref != null) { - ppj = (ProtocolProjector)context.getService(sref); - } - - if (ppj != null) { - commands.setProtocolProjector(ppj); - } else { - context.addServiceListener(sl[4], filter5); - } - - sref=context.getServiceReference(ProtocolExportManager.class.getName()); - ProtocolExportManager pem=null; - - if (sref != null) { - pem = (ProtocolExportManager)context.getService(sref); - } - - if (pem != null) { - commands.setProtocolExportManager(pem); - } else { - context.addServiceListener(sl[5], filter6); - } - - sref=context.getServiceReference(ProtocolMonitor.class.getName()); - ProtocolMonitor pm=null; - - if (sref != null) { - pm = (ProtocolMonitor)context.getService(sref); - } - - if (pm != null) { - commands.setProtocolMonitor(pm); - } else { - context.addServiceListener(sl[6], filter7); - } - - } catch (Exception e) { - e.printStackTrace(); - } - } - - /** - * Stop the bundle. - * - * @param context The context - * @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext) - */ - public void stop(BundleContext context) { - } - - /** - * Container class for the commands. - * - */ - protected class Commands { - - private ParseCommand _parseCommand=null; - private ValidateCommand _validateCommand=null; - private ConformsCommand _conformsCommand=null; - private ProjectCommand _projectCommand=null; - private SimulateCommand _simulateCommand=null; - - /** - * This method sets the validation manager. - * - * @param vm The validation manager - */ - public void setProtocolValidationManager(ProtocolValidationManager vm) { - _validateCommand.setValidationManager(vm); - } - - /** - * This method sets the journal. - * - * @param journal The journal - */ - public void setJournal(Journal journal) { - _parseCommand.setJournal(journal); - _validateCommand.setJournal(journal); - _conformsCommand.setJournal(journal); - _projectCommand.setJournal(journal); - _simulateCommand.setJournal(journal); - } - - /** - * This method sets the parser manager. - * - * @param pp Parser manager - */ - public void setProtocolParserManager(ProtocolParserManager pp) { - _parseCommand.setProtocolParserManager(pp); - _validateCommand.setProtocolParserManager(pp); - _conformsCommand.setProtocolParserManager(pp); - _projectCommand.setProtocolParserManager(pp); - _simulateCommand.setProtocolParserManager(pp); - } - - /** - * This method sets the conformer. - * - * @param pc The conformer - */ - public void setProtocolConformer(ProtocolConformer pc) { - _conformsCommand.setConformer(pc); - } - - /** - * This method sets the projector. - * - * @param pp The projector - */ - public void setProtocolProjector(ProtocolProjector pp) { - _projectCommand.setProtocolProjector(pp); - } - - /** - * This method sets the export manager. - * - * @param em The export manager - */ - public void setProtocolExportManager(ProtocolExportManager em) { - _projectCommand.setProtocolExportManager(em); - _simulateCommand.setProtocolExportManager(em); - } - - /** - * This method sets the protocol monitor. - * - * @param pm The protocol monitor - */ - public void setProtocolMonitor(ProtocolMonitor pm) { - _simulateCommand.setProtocolMonitor(pm); - } - - /** - * This method sets the parser command. - * - * @param command The parser command - */ - public void setParseCommand(ParseCommand command) { - _parseCommand = command; - } - - /** - * This method gets the parser command. - * - * @return The parser command - */ - public ParseCommand getParseCommand() { - return (_parseCommand); - } - - /** - * This method sets the validation command. - * - * @param command The validation command - */ - public void setValidateCommand(ValidateCommand command) { - _validateCommand = command; - } - - /** - * This method gets the validation command. - * - * @return The validation command - */ - public ValidateCommand getValidateCommand() { - return (_validateCommand); - } - - /** - * This method sets the conformance command. - * - * @param command The conformance command - */ - public void setConformsCommand(ConformsCommand command) { - _conformsCommand = command; - } - - /** - * This method gets the conformance command. - * - * @return The conformance command - */ - public ConformsCommand getConformsCommand() { - return (_conformsCommand); - } - - /** - * This method sets the projection command. - * - * @param command The projection command - */ - public void setProjectCommand(ProjectCommand command) { - _projectCommand = command; - } - - /** - * This method gets the projection command. - * - * @return The projection command - */ - public ProjectCommand getProjectCommand() { - return (_projectCommand); - } - - /** - * This method sets the simulate command. - * - * @param command The simulate command - */ - public void setSimulateCommand(SimulateCommand command) { - _simulateCommand = command; - } - - /** - * This method gets the simulate command. - * - * @return The simulate command - */ - public SimulateCommand getSimulateCommand() { - return (_simulateCommand); - } - } -} diff --git a/bundles/org.scribble.command/src/main/java/org/scribble/command/parse/ParseCommand.java b/bundles/org.scribble.command/src/main/java/org/scribble/command/parse/ParseCommand.java deleted file mode 100644 index fc81cf3e4..000000000 --- a/bundles/org.scribble.command/src/main/java/org/scribble/command/parse/ParseCommand.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright 2009 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.command.parse; - -import org.scribble.common.logging.Journal; -import org.scribble.common.resource.Content; -import org.scribble.common.resource.FileContent; -import org.scribble.protocol.model.ProtocolModel; -import org.scribble.protocol.parser.ProtocolParserManager; - -/** - * This class implements the parse command. - * - */ -public class ParseCommand implements org.scribble.command.Command { - - private Journal _journal=null; - private ProtocolParserManager _protocolParserManager=null; - - /** - * Default constructor. - */ - public ParseCommand() { - } - - /** - * This method sets the journal. - * - * @param journal The journal - */ - public void setJournal(Journal journal) { - _journal = journal; - } - - /** - * This method sets the protocol parser manager. - * - * @param parser The parser manager - */ - public void setProtocolParserManager(ProtocolParserManager parser) { - _protocolParserManager = parser; - } - - /** - * {@inheritDoc} - */ - public String getName() { - return ("parse"); - } - - /** - * {@inheritDoc} - */ - public String getDescription() { - return ("Parse a Scribble description"); - } - - /** - * {@inheritDoc} - */ - public boolean execute(String[] args) { - boolean ret=false; - - if (args.length == 1) { - _journal.info("PARSE "+args[0], null); - - java.io.File f=new java.io.File(args[0]); - - if (!f.exists()) { - _journal.error("File not found '"+args[0]+"'", null); - } else { - // TODO: Check if protocol - try { - Content content=new FileContent(f); - - ProtocolModel pm=_protocolParserManager.parse(null, - content, _journal); - - if (pm == null) { - _journal.error("Protocol Model is null", null); - } - - ret = true; - } catch (Exception e) { - _journal.error("Failed to parse file '"+args[0]+"'", null); - } - } - } else { - _journal.error("Parser expects 1 parameter", null); - } - - return (ret); - } -} diff --git a/bundles/org.scribble.command/src/main/java/org/scribble/command/project/ProjectCommand.java b/bundles/org.scribble.command/src/main/java/org/scribble/command/project/ProjectCommand.java deleted file mode 100644 index 06a667ada..000000000 --- a/bundles/org.scribble.command/src/main/java/org/scribble/command/project/ProjectCommand.java +++ /dev/null @@ -1,160 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.command.project; - -import org.scribble.common.logging.Journal; -import org.scribble.common.resource.Content; -import org.scribble.common.resource.DefaultResourceLocator; -import org.scribble.common.resource.FileContent; -import org.scribble.protocol.DefaultProtocolContext; -import org.scribble.protocol.ProtocolContext; -import org.scribble.protocol.export.ProtocolExportManager; -import org.scribble.protocol.export.ProtocolExporter; -import org.scribble.protocol.model.Role; -import org.scribble.protocol.model.ProtocolModel; -import org.scribble.protocol.parser.ProtocolParserManager; -import org.scribble.protocol.projection.ProtocolProjector; - -/** - * This class implements the projection command. - * - */ -public class ProjectCommand implements org.scribble.command.Command { - - private Journal _journal=null; - private ProtocolParserManager _protocolParserManager=null; - private ProtocolProjector _protocolProjector=null; - private ProtocolExportManager _protocolExportManager=null; - - /** - * Default constructor. - */ - public ProjectCommand() { - } - - /** - * This method sets the journal. - * - * @param journal The journal - */ - public void setJournal(Journal journal) { - _journal = journal; - } - - /** - * This method sets the protocol parser manager. - * - * @param parser The parser manager - */ - public void setProtocolParserManager(ProtocolParserManager parser) { - _protocolParserManager = parser; - } - - /** - * This method sets the protocol projector. - * - * @param projector The protocol projector - */ - public void setProtocolProjector(ProtocolProjector projector) { - _protocolProjector = projector; - } - - /** - * This method sets the export manager. - * - * @param exportManager The export manager - */ - public void setProtocolExportManager(ProtocolExportManager exportManager) { - _protocolExportManager = exportManager; - } - - /** - * {@inheritDoc} - */ - public String getName() { - return ("project"); - } - - /** - * {@inheritDoc} - */ - public String getDescription() { - return ("Project a global protocol description to a role's local model"); - } - - /** - * {@inheritDoc} - */ - public boolean execute(String[] args) { - boolean ret=false; - - if (args.length == 2) { - _journal.info("PROJECT "+args[0]+" for role "+args[1], null); - - java.io.File f=new java.io.File(args[0]); - - if (!f.exists()) { - _journal.error("File not found '"+args[0]+"'", null); - } else { - ProtocolModel model=null; - - try { - Content content=new FileContent(f); - - model = _protocolParserManager.parse(new DefaultProtocolContext(_protocolParserManager, - new DefaultResourceLocator(f.getParentFile())), content, _journal); - - } catch (Exception e) { - _journal.error("Failed to parse file '"+args[0]+"'", null); - } - - if (model != null) { - // TODO: Need to check if model has been parsed - - // TODO: Need to validate that role is defined in global model - Role role=new Role(args[1]); - - try { - ProtocolContext context=new DefaultProtocolContext(_protocolParserManager, - new DefaultResourceLocator(f.getParentFile())); - - ProtocolModel projection=_protocolProjector.project(context, - model, role, _journal); - - if (projection != null) { - // Get text exporter - ProtocolExporter exporter=_protocolExportManager.getExporter("txt"); - - if (exporter != null) { - exporter.export(projection, _journal, System.out); - - ret = true; - } else { - _journal.error("Unable to find text exporter", null); - } - } - } catch (Exception e) { - e.printStackTrace(); - } - } - } - } else { - _journal.error("Projection expects 2 parameters", null); - } - - return (ret); - } -} diff --git a/bundles/org.scribble.command/src/main/java/org/scribble/command/simulate/Event.java b/bundles/org.scribble.command/src/main/java/org/scribble/command/simulate/Event.java deleted file mode 100644 index 8250ec5d8..000000000 --- a/bundles/org.scribble.command/src/main/java/org/scribble/command/simulate/Event.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.command.simulate; - -import org.scribble.protocol.monitor.Session; -import org.scribble.protocol.monitor.MonitorContext; -import org.scribble.protocol.monitor.Result; -import org.scribble.protocol.monitor.model.Description; -import org.scribble.protocol.monitor.ProtocolMonitor; - -/** - * This is the abstract base class for all simulation events. - * - */ -public abstract class Event { - - /** - * Default constructor. - */ - public Event() { - } - - /** - * This method sets the colum and value of the event record from the csv file. - * - * @param col The column - * @param val The value - */ - public abstract void setColumn(int col, String val); - - /** - * This method validates the event using the supplied protocol monitor, - * monitor context, protocol and session details. - * - * @param monitor The monitor - * @param context The context - * @param protocol The protocol - * @param conv The conversation/session - * @return The validation result - */ - public abstract Result validate(ProtocolMonitor monitor, MonitorContext context, - Description protocol, Session conv); -} diff --git a/bundles/org.scribble.command/src/main/java/org/scribble/command/simulate/EventProcessor.java b/bundles/org.scribble.command/src/main/java/org/scribble/command/simulate/EventProcessor.java deleted file mode 100644 index ffe188c06..000000000 --- a/bundles/org.scribble.command/src/main/java/org/scribble/command/simulate/EventProcessor.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.command.simulate; - -/** - * This class processes events from a csv based text stream to make them available - * to a simulator. - * - */ -public class EventProcessor { - - private java.util.List _events=new java.util.Vector(); - - /** - * Default constructor. - */ - public EventProcessor() { - } - - /** - * This method initializes the event list from the supplied input stream. - * - * @param events The input stream for the csv formatted events - * @throws Exception Failed to initialize event list - */ - public void initialize(java.io.InputStream events) throws Exception { - byte[] b=new byte[events.available()]; - - events.read(b); - - String buf=new String(b); - - String[] lines=buf.split("[\r\n]"); - - for (int i=0; i < lines.length; i++) { - String line=lines[i].trim(); - - if (line.length() > 0) { - String[] cols=line.split(","); - Event evt=null; - - for (int j=0; j < cols.length; j++) { - - if (j == 0) { - if (cols[j].equals("send")) { - evt = new SendMessage(); - } else if (cols[j].equals("receive")) { - evt = new ReceiveMessage(); - } else { - System.err.println("Unknown event type '"+cols[j]+"'"); - } - } else if (evt != null) { - evt.setColumn(j, cols[j]); - } - } - - if (evt != null) { - _events.add(evt); - } - } - } - } - - /** - * This method returns the list of events. - * - * @return The events - */ - public java.util.List getEvents() { - return (_events); - } -} diff --git a/bundles/org.scribble.command/src/main/java/org/scribble/command/simulate/ReceiveMessage.java b/bundles/org.scribble.command/src/main/java/org/scribble/command/simulate/ReceiveMessage.java deleted file mode 100644 index 541067cbc..000000000 --- a/bundles/org.scribble.command/src/main/java/org/scribble/command/simulate/ReceiveMessage.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.command.simulate; - -import org.scribble.protocol.monitor.DefaultMessage; -import org.scribble.protocol.monitor.Message; -import org.scribble.protocol.monitor.MonitorContext; -import org.scribble.protocol.monitor.ProtocolMonitor; -import org.scribble.protocol.monitor.Result; -import org.scribble.protocol.monitor.Session; -import org.scribble.protocol.monitor.model.Description; - -/** - * This class represents receiving a message. - * - */ -public class ReceiveMessage extends Event { - - private DefaultMessage _message=new DefaultMessage(); - - /** - * Default constructor. - */ - public ReceiveMessage() { - } - - @Override - public Result validate(ProtocolMonitor monitor, MonitorContext context, - Description protocol, Session conv) { - return (monitor.messageReceived(context, protocol, conv, _message)); - } - - @Override - public void setColumn(int col, String val) { - - if (col == 1) { - int pos=val.indexOf('('); - - if (pos == -1) { - _message.getTypes().add(val); - } else { - String op=val.substring(0, pos); - - _message.setOperator(op); - - int end=val.indexOf(')', pos); - - String mesgType=val.substring(pos+1, end); - - _message.getTypes().add(mesgType); - } - } - } - - /** - * This method returns the message. - * - * @return The message - */ - public Message getMessage() { - return (_message); - } - - @Override - public String toString() { - return ("Receive "+_message); - } -} diff --git a/bundles/org.scribble.command/src/main/java/org/scribble/command/simulate/SendMessage.java b/bundles/org.scribble.command/src/main/java/org/scribble/command/simulate/SendMessage.java deleted file mode 100644 index b8db3fa37..000000000 --- a/bundles/org.scribble.command/src/main/java/org/scribble/command/simulate/SendMessage.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.command.simulate; - -import org.scribble.protocol.monitor.DefaultMessage; -import org.scribble.protocol.monitor.Message; -import org.scribble.protocol.monitor.MonitorContext; -import org.scribble.protocol.monitor.ProtocolMonitor; -import org.scribble.protocol.monitor.Result; -import org.scribble.protocol.monitor.Session; -import org.scribble.protocol.monitor.model.Description; - -/** - * This class represents a send message. - * - */ -public class SendMessage extends Event { - - private DefaultMessage _message=new DefaultMessage(); - - /** - * Default constructor. - */ - public SendMessage() { - } - - @Override - public Result validate(ProtocolMonitor monitor, MonitorContext context, Description protocol, - Session conv) { - return (monitor.messageSent(context, protocol, conv, _message)); - } - - @Override - public void setColumn(int col, String val) { - - if (col == 1) { - int pos=val.indexOf('('); - - if (pos == -1) { - _message.getTypes().add(val); - } else { - String op=val.substring(0, pos); - - _message.setOperator(op); - - int end=val.indexOf(')', pos); - - String mesgType=val.substring(pos+1, end); - - _message.getTypes().add(mesgType); - } - } - } - - /** - * This method returns the message. - * - * @return The message - */ - public Message getMessage() { - return (_message); - } - - @Override - public String toString() { - return ("Send "+_message); - } -} diff --git a/bundles/org.scribble.command/src/main/java/org/scribble/command/simulate/SimulateCommand.java b/bundles/org.scribble.command/src/main/java/org/scribble/command/simulate/SimulateCommand.java deleted file mode 100644 index 195fcde2c..000000000 --- a/bundles/org.scribble.command/src/main/java/org/scribble/command/simulate/SimulateCommand.java +++ /dev/null @@ -1,212 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.command.simulate; - -import java.io.ByteArrayOutputStream; -import java.util.logging.Level; -import java.util.logging.Logger; - -import org.scribble.common.logging.Journal; -import org.scribble.common.resource.Content; -import org.scribble.common.resource.DefaultResourceLocator; -import org.scribble.common.resource.FileContent; -import org.scribble.protocol.DefaultProtocolContext; -import org.scribble.protocol.export.ProtocolExportManager; -import org.scribble.protocol.monitor.DefaultMonitorContext; -import org.scribble.protocol.monitor.DefaultSession; -import org.scribble.protocol.monitor.ProtocolMonitor; -import org.scribble.protocol.monitor.Session; -import org.scribble.protocol.parser.ProtocolParserManager; - -/** - * This class implements the simulation command. - * - */ -public class SimulateCommand implements org.scribble.command.Command { - - private ProtocolMonitor _protocolMonitor=null; - private ProtocolExportManager _protocolExportManager=null; - private Journal _journal=null; - private ProtocolParserManager _protocolParserManager=null; - - private final static Logger LOG=Logger.getLogger(SimulateCommand.class.getName()); - - /** - * Default constructor. - */ - public SimulateCommand() { - } - - /** - * This method sets the protocol monitor. - * - * @param pm The protocol monitor - */ - public void setProtocolMonitor(ProtocolMonitor pm) { - _protocolMonitor = pm; - } - - /** - * This method sets the journal. - * - * @param journal The journal - */ - public void setJournal(Journal journal) { - _journal = journal; - } - - /** - * This method sets the protocol parser manager. - * - * @param parser The parser manager - */ - public void setProtocolParserManager(ProtocolParserManager parser) { - _protocolParserManager = parser; - } - - /** - * This method sets the export manager. - * - * @param exportManager The export manager - */ - public void setProtocolExportManager(ProtocolExportManager exportManager) { - _protocolExportManager = exportManager; - } - - /** - * {@inheritDoc} - */ - public String getName() { - return ("simulate"); - } - - /** - * {@inheritDoc} - */ - public String getDescription() { - return ("Simulate a Scribble endpoint description against a list of events"); - } - - /** - * {@inheritDoc} - */ - public boolean execute(String[] args) { - boolean ret=false; - - if (args.length == 2) { - _journal.info("SIMULATE "+args[0]+" "+args[1], null); - - java.io.File f1=new java.io.File(args[0]); - java.io.File f2=new java.io.File(args[1]); - - if (!f1.exists()) { - _journal.error("File not found '"+args[0]+"'", null); - } else if (!f2.exists()) { - _journal.error("File not found '"+args[1]+"'", null); - } else { - // TODO: Check if protocol - try { - Content content=new FileContent(f1); - - org.scribble.protocol.model.ProtocolModel model= - _protocolParserManager.parse(new DefaultProtocolContext(_protocolParserManager, - new DefaultResourceLocator(f1.getParentFile())), - content, _journal); - - if (model != null) { - - if (model.getProtocol().getLocatedRole() != null) { - - simulate(model, f2); - - ret = true; - } else { - _journal.error("Protocol is not located at a role - " - +"only located protocols can be simulated", null); - } - } else { - _journal.error("Protocol model not retrieved", null); - } - - } catch (Exception e) { - _journal.error("Failed to simulate file '"+args[0]+"'", null); - e.printStackTrace(); - } - } - } else { - System.err.println("Simulation expects 2 parameters"); - } - - return (ret); - } - - /** - * This method simulates the protocol model against the specified event file. - * - * @param model The protocol model - * @param eventFile The event file - */ - public void simulate(org.scribble.protocol.model.ProtocolModel model, java.io.File eventFile) { - // Generate internal representation for monitor - org.scribble.protocol.export.ProtocolExporter exporter= - _protocolExportManager.getExporter("monitor"); - - if (exporter != null) { - ByteArrayOutputStream os=new ByteArrayOutputStream(); - - try { - exporter.export(model, _journal, os); - - java.io.InputStream prtis=new java.io.ByteArrayInputStream(os.toByteArray()); - - org.scribble.protocol.monitor.model.Description protocol= - org.scribble.protocol.monitor.util.MonitorModelUtil.deserialize(prtis); - - prtis.close(); - - if (LOG.isLoggable(Level.FINE)) { - LOG.fine("Protocol = "+protocol); - } - - DefaultMonitorContext context=new DefaultMonitorContext(); - - Session conv=_protocolMonitor.createSession(context, protocol, DefaultSession.class); - - java.io.InputStream is=new java.io.FileInputStream(eventFile); - - EventProcessor eventProcessor=new EventProcessor(); - - eventProcessor.initialize(is); - - is.close(); - - for (Event event : eventProcessor.getEvents()) { - if (event.validate(_protocolMonitor, context, protocol, conv).isValid()) { - _journal.info("Validated "+event, null); - } else { - _journal.error(event.toString(), null); - } - } - - } catch (Exception e) { - e.printStackTrace(); - _journal.error("Failed to simulate process model: "+e, null); - } - } else { - _journal.error("Failed to export protocol model to monitoring representation", null); - } - } -} diff --git a/bundles/org.scribble.command/src/main/java/org/scribble/command/validate/ValidateCommand.java b/bundles/org.scribble.command/src/main/java/org/scribble/command/validate/ValidateCommand.java deleted file mode 100644 index f479f796a..000000000 --- a/bundles/org.scribble.command/src/main/java/org/scribble/command/validate/ValidateCommand.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Copyright 2009 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.command.validate; - -import org.scribble.common.logging.Journal; -import org.scribble.common.resource.Content; -import org.scribble.common.resource.DefaultResourceLocator; -import org.scribble.common.resource.FileContent; -import org.scribble.protocol.DefaultProtocolContext; -import org.scribble.protocol.parser.ProtocolParserManager; -import org.scribble.protocol.validation.ProtocolValidationManager; - -/** - * This class implements the validation command. - * - */ -public class ValidateCommand implements org.scribble.command.Command { - - private ProtocolValidationManager _validationManager=null; - private Journal _journal=null; - private ProtocolParserManager _protocolParserManager=null; - - /** - * Default constructor. - */ - public ValidateCommand() { - } - - /** - * This method sets the validation manager. - * - * @param vm The validation manager - */ - public void setValidationManager(ProtocolValidationManager vm) { - _validationManager = vm; - } - - /** - * This method sets the journal. - * - * @param journal The journal - */ - public void setJournal(Journal journal) { - _journal = journal; - } - - /** - * This method sets the protocol parser manager. - * - * @param parser The parser manager - */ - public void setProtocolParserManager(ProtocolParserManager parser) { - _protocolParserManager = parser; - } - - /** - * {@inheritDoc} - */ - public String getName() { - return ("validate"); - } - - /** - * {@inheritDoc} - */ - public String getDescription() { - return ("Validate a Scribble description"); - } - - /** - * {@inheritDoc} - */ - public boolean execute(String[] args) { - boolean ret=false; - - if (args.length == 1) { - _journal.info("PARSE "+args[0], null); - - java.io.File f=new java.io.File(args[0]); - - if (!f.exists()) { - _journal.error("File not found '"+args[0]+"'", null); - } else { - // TODO: Check if protocol - try { - Content content=new FileContent(f); - - DefaultProtocolContext context=new DefaultProtocolContext(_protocolParserManager, - new DefaultResourceLocator(f.getParentFile())); - - org.scribble.protocol.model.ProtocolModel model= - _protocolParserManager.parse(context, - content, _journal); - - if (model != null) { - _journal.info("VALIDATE "+args[0], null); - - _validationManager.validate(context, model, _journal); - - ret = true; - } else { - _journal.error("Protocol model is null", null); - } - - } catch (Exception e) { - _journal.error("Failed to validate file '"+args[0]+"'", null); - } - } - } else { - System.err.println("Validation expecting 1 parameter"); - } - - return (ret); - } -} diff --git a/bundles/org.scribble.command/src/test/java/org/scribble/command/simulate/EventProcessorTest.java b/bundles/org.scribble.command/src/test/java/org/scribble/command/simulate/EventProcessorTest.java deleted file mode 100644 index aa1109984..000000000 --- a/bundles/org.scribble.command/src/test/java/org/scribble/command/simulate/EventProcessorTest.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.command.simulate; - -import static org.junit.Assert.*; - -public class EventProcessorTest { - - @org.junit.Test - public void testMonitorSendReceiveMessage() { - String str="send,Order\r\nreceive,Confirmation\r\n"; - - java.io.ByteArrayInputStream bais=new java.io.ByteArrayInputStream(str.getBytes()); - - EventProcessor ep=new EventProcessor(); - - try { - ep.initialize(bais); - bais.close(); - } catch (Exception e) { - fail("Failed to initialize event processor: "+e); - } - - java.util.List events=ep.getEvents(); - - if (events.size() != 2) { - fail("Should only be 2 events"); - } - - if ((events.get(0) instanceof SendMessage) == false) { - fail("First event should be send message"); - } - - SendMessage evt0=(SendMessage)events.get(0); - - if (evt0.getMessage().getOperator() != null) { - fail("Operator should not be set"); - } - - if (evt0.getMessage().getTypes().size() != 1) { - fail("Should be only 1 type"); - } - - if (evt0.getMessage().getTypes().contains("Order") == false) { - fail("Parameter type should be Order"); - } - - if ((events.get(1) instanceof ReceiveMessage) == false) { - fail("Second event should be receive message"); - } - - ReceiveMessage evt1=(ReceiveMessage)events.get(1); - - if (evt1.getMessage().getOperator() != null) { - fail("Operator should not be set"); - } - - if (evt1.getMessage().getTypes().size() != 1) { - fail("Should only be 1 type"); - } - - if (evt1.getMessage().getTypes().contains("Confirmation") == false) { - fail("Parameter type should be Confirmation"); - } - } - - @org.junit.Test - public void testMonitorSendReceiveMessageWithOperator() { - String str="send,op1(Order)\r\nreceive,op2(Confirmation)\r\n"; - - java.io.ByteArrayInputStream bais=new java.io.ByteArrayInputStream(str.getBytes()); - - EventProcessor ep=new EventProcessor(); - - try { - ep.initialize(bais); - bais.close(); - } catch (Exception e) { - fail("Failed to initialize event processor: "+e); - } - - java.util.List events=ep.getEvents(); - - if (events.size() != 2) { - fail("Should only be 2 events"); - } - - if ((events.get(0) instanceof SendMessage) == false) { - fail("First event should be send message"); - } - - SendMessage evt0=(SendMessage)events.get(0); - - if (evt0.getMessage().getOperator().equals("op1") == false) { - fail("Operator should be op1"); - } - - if (evt0.getMessage().getTypes().size() != 1) { - fail("Should be only 1 type"); - } - - if (evt0.getMessage().getTypes().contains("Order") == false) { - fail("Parameter type should be Order"); - } - - if ((events.get(1) instanceof ReceiveMessage) == false) { - fail("Second event should be receive message"); - } - - ReceiveMessage evt1=(ReceiveMessage)events.get(1); - - if (evt1.getMessage().getOperator().equals("op2") == false) { - fail("Operator should be op2"); - } - - if (evt1.getMessage().getTypes().size() != 1) { - fail("Should be only 1 type"); - } - - if (evt1.getMessage().getTypes().contains("Confirmation") == false) { - fail("Parameter type should be Confirmation"); - } - } - -} diff --git a/bundles/org.scribble.common/META-INF/MANIFEST.MF b/bundles/org.scribble.common/META-INF/MANIFEST.MF deleted file mode 100644 index 02f388247..000000000 --- a/bundles/org.scribble.common/META-INF/MANIFEST.MF +++ /dev/null @@ -1,12 +0,0 @@ -Manifest-Version: 1.0 -Bundle-ManifestVersion: 2 -Bundle-Name: Scribble Common -Bundle-SymbolicName: org.scribble.common -Bundle-Version: 2.1.0.SNAPSHOT -Bundle-Activator: org.scribble.common.osgi.Activator -Bundle-Vendor: www.scribble.org -Import-Package: org.osgi.framework -Export-Package: org.scribble.common.logging, - org.scribble.common.model, - org.scribble.common.resource -Bundle-RequiredExecutionEnvironment: JavaSE-1.6 diff --git a/bundles/org.scribble.common/build.properties b/bundles/org.scribble.common/build.properties deleted file mode 100644 index 9fc6e0c06..000000000 --- a/bundles/org.scribble.common/build.properties +++ /dev/null @@ -1,12 +0,0 @@ -source.. = src/main/java/ -output.. = bin/ -bin.includes = META-INF/,\ - .,\ - LICENSE.txt -src.includes = .classpath,\ - .project,\ - LICENSE.txt,\ - META-INF/,\ - build.properties,\ - pom.xml,\ - src/ diff --git a/bundles/org.scribble.common/pom.xml b/bundles/org.scribble.common/pom.xml deleted file mode 100644 index 727b56223..000000000 --- a/bundles/org.scribble.common/pom.xml +++ /dev/null @@ -1,75 +0,0 @@ - - 4.0.0 - org.scribble.bundles - org.scribble.common - 2.1.0-SNAPSHOT - jar - Scribble::Bundles::Common - - - org.scribble - bundles - 2.1.0-SNAPSHOT - - - - - org.osgi - org.osgi.core - ${osgi.version} - - - junit - junit - test - - - - - - - maven-javadoc-plugin - - - generate-javadoc - package - - jar - - - - - org.jboss.apiviz.APIviz - - org.jboss.apiviz - apiviz - 1.2.4.GA - - true - false - - -d ${project.build.directory}/javadoc - -charset UTF-8 - -docencoding UTF-8 - -version - -author - -breakiterator - -windowtitle "${project.name} ${project.version} API Reference" - -doctitle "${project.name} ${project.version} API Reference" - -bottom "Copyright © ${project.inceptionYear}-Present ${project.organization.name}. All Rights Reserved." - -link http://java.sun.com/javase/6/docs/api/ - -sourceclasspath ${project.build.outputDirectory} - - UTF-8 - en_US - - org.scribble.common.logging - org.scribble.common.model - org.scribble.common.resource - - - - - - diff --git a/bundles/org.scribble.common/src/main/java/org/scribble/common/logging/CachedJournal.java b/bundles/org.scribble.common/src/main/java/org/scribble/common/logging/CachedJournal.java deleted file mode 100644 index 729a59f60..000000000 --- a/bundles/org.scribble.common/src/main/java/org/scribble/common/logging/CachedJournal.java +++ /dev/null @@ -1,194 +0,0 @@ -/* - * Copyright 2009 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.common.logging; - -import java.util.Map; - -/** - * This class provides an implementation of the journal that - * caches reported issues. - * - */ -public class CachedJournal implements Journal { - - private java.util.List _issues=new java.util.Vector(); - private boolean _errors=false; - private boolean _warnings=false; - - /** - * This method records an error issue. - * - * @param issue The issue text - * @param props The optional properties associated with the issue - */ - public void error(String issue, Map props) { - _issues.add(new IssueDetails(IssueType.Error, issue, props)); - _errors = true; - } - - /** - * This method records an information issue. - * - * @param issue The issue text - * @param props The optional properties associated with the issue - */ - public void info(String issue, Map props) { - _issues.add(new IssueDetails(IssueType.Info, issue, props)); - } - - /** - * This method records a warning issue. - * - * @param issue The issue text - * @param props The optional properties associated with the issue - */ - public void warning(String issue, Map props) { - _issues.add(new IssueDetails(IssueType.Warning, issue, props)); - _warnings = true; - } - - /** - * This method returns the list of issues that have been reported to this - * journal. - * - * @return The list of issues - */ - public java.util.List getIssues() { - return (_issues); - } - - /** - * This method determines whether any errors have been reported. - * - * @return Whether errors have been reported - */ - public boolean hasErrors() { - return (_errors); - } - - /** - * This method determines whether any warnings have been reported. - * - * @return Whether warnings have been reported - */ - public boolean hasWarnings() { - return (_warnings); - } - - /** - * This method applies any cached issues to the supplied logger. - * - * @param logger The logger - */ - public void apply(Journal logger) { - - } - - /** - * This method applies any cached issues to the supplied logger. - * - * @param prefix The optional message prefix - * @param logger The logger - */ - public void apply(Journal logger, String prefix) { - - if (prefix == null) { - prefix = ""; - } - - for (IssueDetails id : _issues) { - if (id.getIssueType() == IssueType.Error) { - logger.error(prefix+id.getMessage(), id.getProperties()); - } else if (id.getIssueType() == IssueType.Info) { - logger.info(prefix+id.getMessage(), id.getProperties()); - } else if (id.getIssueType() == IssueType.Warning) { - logger.warning(prefix+id.getMessage(), id.getProperties()); - } - } - } - - /** - * This enum represents the type of issue. - * - */ - public enum IssueType { - /** - * Error issue type. - */ - Error, - /** - * Information issue type. - */ - Info, - /** - * Warning issue type. - */ - Warning - } - - /** - * This class represents the issue details. - * - */ - public class IssueDetails { - - private IssueType _type=IssueType.Info; - private String _message=null; - private Map _properties=null; - - /** - * Constructor for the issue details. - * - * @param type The issue type - * @param mesg The message - * @param props The properties - */ - public IssueDetails(IssueType type, String mesg, - Map props) { - _type = type; - _message = mesg; - _properties = props; - } - - /** - * This method returns the issue type. - * - * @return The issue type - */ - public IssueType getIssueType() { - return (_type); - } - - /** - * This method returns the message. - * - * @return The message - */ - public String getMessage() { - return (_message); - } - - /** - * This method returns the properties. - * - * @return The properties - */ - public Map getProperties() { - return (_properties); - } - } -} diff --git a/bundles/org.scribble.common/src/main/java/org/scribble/common/logging/ConsoleJournal.java b/bundles/org.scribble.common/src/main/java/org/scribble/common/logging/ConsoleJournal.java deleted file mode 100644 index 5d244afe2..000000000 --- a/bundles/org.scribble.common/src/main/java/org/scribble/common/logging/ConsoleJournal.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright 2009 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.common.logging; - -/** - * This class provides an implementation of the journal that - * reports issues to the console. - * - */ -public class ConsoleJournal implements Journal { - - private static final String NO_DETAILS=""; - - /** - * This method records an error issue. - * - * @param issue The issue text - * @param props The optional properties associated with the issue - */ - public void error(String issue, java.util.Map props) { - System.out.println("ERROR: "+errorDetails(props)+issue); - } - - /** - * This method records a warning issue. - * - * @param issue The issue text - * @param props The optional properties associated with the issue - */ - public void warning(String issue, java.util.Map props) { - System.out.println("WARN: "+errorDetails(props)+issue); - } - - /** - * This method records an information issue. - * - * @param issue The issue text - * @param props The optional properties associated with the issue - */ - public void info(String issue, java.util.Map props) { - System.out.println("INFO: "+errorDetails(props)+issue); - } - - private String errorDetails(java.util.Map props) { - String ret=NO_DETAILS; - - if (props != null && props.containsKey(Journal.START_LINE)) { - ret = "[line "+props.get(Journal.START_LINE)+"] "; - } - - return (ret); - } -} diff --git a/bundles/org.scribble.common/src/main/java/org/scribble/common/logging/Journal.java b/bundles/org.scribble.common/src/main/java/org/scribble/common/logging/Journal.java deleted file mode 100644 index 5a9360713..000000000 --- a/bundles/org.scribble.common/src/main/java/org/scribble/common/logging/Journal.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright 2009 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.common.logging; - -/** - * This interface represents the component used by other scribble modules - * to record issues. - * - */ -public interface Journal { - - /** - * The start line in the document at which the issue has been detected. - */ - public static final String START_LINE = "start.line"; - - /** - * The start column in the document at which the issue has been detected. - */ - public static final String START_COLUMN = "start.column"; - - /** - * The end line in the document at which the issue has been detected. - */ - public static final String END_LINE = "end.line"; - - /** - * The end column in the document at which the issue has been detected. - */ - public static final String END_COLUMN = "end.column"; - - /** - * The start position in the document at which the issue has been detected. - */ - public static final String START_POSITION = "position.start"; - - /** - * The end position in the document at which the issue has been detected. - */ - public static final String END_POSITION = "position.end"; - - /** - * The optional resource URL associated with the issue. - */ - public static final String RESOURCE_URL = "resource.url"; - - /** - * This method records an error issue. - * - * @param issue The issue text - * @param props The optional properties associated with the issue - */ - public void error(String issue, java.util.Map props); - - /** - * This method records a warning issue. - * - * @param issue The issue text - * @param props The optional properties associated with the issue - */ - public void warning(String issue, java.util.Map props); - - /** - * This method records an information issue. - * - * @param issue The issue text - * @param props The optional properties associated with the issue - */ - public void info(String issue, java.util.Map props); - -} diff --git a/bundles/org.scribble.common/src/main/java/org/scribble/common/model/Annotation.java b/bundles/org.scribble.common/src/main/java/org/scribble/common/model/Annotation.java deleted file mode 100644 index 056d8defd..000000000 --- a/bundles/org.scribble.common/src/main/java/org/scribble/common/model/Annotation.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright 2009-11 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.common.model; - -/** - * This interface represents an annotation associated with a protocol - * model object. - * - */ -public interface Annotation { - - /** - * Optional id for the annotation. If specified, it must be - * unique within the scope of the protocol model in which - * it is defined. - * - * @return The unique annotation id, or null if undefined - */ - public String getId(); - - /** - * This method generates a text based representation of annotation, - * that would be exported between [[ and ]] delimitors in the - * text based scribble representation. - * - * @return The textual representation of the annotation - */ - public String toString(); - -} diff --git a/bundles/org.scribble.common/src/main/java/org/scribble/common/model/DefaultAnnotation.java b/bundles/org.scribble.common/src/main/java/org/scribble/common/model/DefaultAnnotation.java deleted file mode 100644 index 0141cd782..000000000 --- a/bundles/org.scribble.common/src/main/java/org/scribble/common/model/DefaultAnnotation.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright 2009-11 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.common.model; - -/** - * This class represents the default implementation of the annotation - * interface. - * - */ -public class DefaultAnnotation implements Annotation { - - private String _annotation=null; - private String _id=null; - - /** - * This is the constructor, initialized with the - * annotation text. - * - * @param text The text - */ - public DefaultAnnotation(String text) { - _annotation = text; - } - - /** - * This is the constructor, initialized with the - * optional id and annotation text. - * - * @param id The optional id - * @param text The text - */ - public DefaultAnnotation(String id, String text) { - _id = id; - _annotation = text; - } - - /** - * Optional id for the annotation. If specified, it must be - * unique within the scope of the protocol model in which - * it is defined. - * - * @return The unique annotation id, or null if undefined - */ - public String getId() { - return (_id); - } - - /** - * This method sets the annotation. - * - * @param annotation The annotation - */ - public void setAnnotation(String annotation) { - _annotation = annotation; - } - - /** - * This method returns the textual representation - * of the annotation. - * - * @return The annotation text - */ - public String toString() { - return (_annotation); - } -} diff --git a/bundles/org.scribble.common/src/main/java/org/scribble/common/osgi/Activator.java b/bundles/org.scribble.common/src/main/java/org/scribble/common/osgi/Activator.java deleted file mode 100644 index 1fc55b53e..000000000 --- a/bundles/org.scribble.common/src/main/java/org/scribble/common/osgi/Activator.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright 2009 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.common.osgi; - -import org.osgi.framework.BundleActivator; -import org.osgi.framework.BundleContext; - -/** - * This class provides the OSGi activator. - * - */ -public class Activator implements BundleActivator { - - /** - * Start the bundle. - * - * @param context The context - * @throws Exception Failed to start - * @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext) - */ - public void start(BundleContext context) throws Exception { - } - - /** - * Stop the bundle. - * - * @param context The context - * @throws Exception Failed to stop - * @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext) - */ - public void stop(BundleContext context) throws Exception { - } - -} diff --git a/bundles/org.scribble.common/src/main/java/org/scribble/common/resource/ByteArrayContent.java b/bundles/org.scribble.common/src/main/java/org/scribble/common/resource/ByteArrayContent.java deleted file mode 100644 index 6c589e5e1..000000000 --- a/bundles/org.scribble.common/src/main/java/org/scribble/common/resource/ByteArrayContent.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright 2009-11 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.common.resource; - -import javax.xml.namespace.QName; - -/** - * This class represents byte array content to be used by the Scribble tools. - * - */ -public class ByteArrayContent implements Content { - - private byte[] _array=null; - private String _name=null; - - /** - * This construct is initialized with the byte array. - * - * @param array The byte array - */ - public ByteArrayContent(byte[] array) { - _array = array; - } - - /** - * This construct is initialized with the byte array. - * - * @param name The name - * @param array The byte array - */ - public ByteArrayContent(String name, byte[] array) { - _name = name; - _array = array; - } - - /** - * This method returns the content name if available. - * - * @return The optional content name - */ - public String getName() { - return (_name); - } - - /** - * This method returns the input stream for accessing the content. - * - * @return The input stream - * @throws java.io.IOException Failed to get input stream - */ - public java.io.InputStream getInputStream() throws java.io.IOException { - return (new java.io.ByteArrayInputStream(_array)); - } - - /** - * This method determines whether the content has an extension - * of the specified type. - * - * @param ext The extension - * @return Whether the content has the specified extension - */ - public boolean hasExtension(String ext) { - if (_name == null) { - throw new UnsupportedOperationException(); - } - - return (_name.endsWith("."+ext)); - } - - /** - * This method determines whether the content is an XSD type of - * the value specified. - * - * @param xsdType The XSD type name - * @return Whether the content is an XSD type of the specified name - */ - public boolean isXSDType(QName xsdType) { - // TODO: Implement method - throw new UnsupportedOperationException(); - } - - /** - * This method determines whether the content is an XSD element of - * the value specified. - * - * @param xsdElem The XSD element name - * @return Whether the content is an XSD element of the specified name - */ - public boolean isXSDElement(QName xsdElem) { - // TODO: Implement method - throw new UnsupportedOperationException(); - } - -} diff --git a/bundles/org.scribble.common/src/main/java/org/scribble/common/resource/Content.java b/bundles/org.scribble.common/src/main/java/org/scribble/common/resource/Content.java deleted file mode 100644 index 3f857e90e..000000000 --- a/bundles/org.scribble.common/src/main/java/org/scribble/common/resource/Content.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright 2009-11 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.common.resource; - -import javax.xml.namespace.QName; - -/** - * This interface represents content to be used by the Scribble tools. - * - */ -public interface Content { - - /** - * This method returns the content name if available. - * - * @return The optional content name - */ - public String getName(); - - /** - * This method returns the input stream for accessing the content. - * - * @return The input stream - * @throws java.io.IOException Failed to get input stream - */ - public java.io.InputStream getInputStream() throws java.io.IOException; - - /** - * This method determines whether the content has an extension - * of the specified type. - * - * @param ext The extension - * @return Whether the content has the specified extension - */ - public boolean hasExtension(String ext); - - /** - * This method determines whether the content is an XSD type of - * the value specified. - * - * @param xsdType The XSD type name - * @return Whether the content is an XSD type of the specified name - */ - public boolean isXSDType(QName xsdType); - - /** - * This method determines whether the content is an XSD element of - * the value specified. - * - * @param xsdElem The XSD element name - * @return Whether the content is an XSD element of the specified name - */ - public boolean isXSDElement(QName xsdElem); - -} diff --git a/bundles/org.scribble.common/src/main/java/org/scribble/common/resource/DefaultResourceLocator.java b/bundles/org.scribble.common/src/main/java/org/scribble/common/resource/DefaultResourceLocator.java deleted file mode 100644 index 9c278bead..000000000 --- a/bundles/org.scribble.common/src/main/java/org/scribble/common/resource/DefaultResourceLocator.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright 2010 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.common.resource; - -import java.net.URI; - -/** - * This class represents a default implement of the resource locator - * interface, that can be used to load artifacts relative to a base - * location. - * - */ -public class DefaultResourceLocator implements ResourceLocator { - - private java.io.File _baseDir=null; - - /** - * This constructor initializes the default resource locator - * with the location of the base directory from which the - * relative file paths should be derived. - * - * @param baseDir The base directory - */ - public DefaultResourceLocator(java.io.File baseDir) { - _baseDir = baseDir; - } - - /** - * This method can be used to retrieve the URI of a resource which - * is located at the specified URI, potentially relative to a resource - * that is being processed. - * - * @param uri The relative URI of the resource to load - * @return The URI, or null if not found - * @throws Exception Failed to get resource URI - */ - public java.net.URI getResourceURI(String uri) throws Exception { - java.net.URI ret=null; - java.io.File file=new java.io.File(_baseDir, uri); - - if (!file.exists()) { - ret = new URI(uri); - } else { - ret = file.toURI(); - } - - return (ret); - } - -} diff --git a/bundles/org.scribble.common/src/main/java/org/scribble/common/resource/FileContent.java b/bundles/org.scribble.common/src/main/java/org/scribble/common/resource/FileContent.java deleted file mode 100644 index 9e2a80216..000000000 --- a/bundles/org.scribble.common/src/main/java/org/scribble/common/resource/FileContent.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright 2009-11 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.common.resource; - -import javax.xml.namespace.QName; - -/** - * This class represents file content to be used by the Scribble tools. - * - */ -public class FileContent implements Content { - - private java.io.File _file=null; - - /** - * This construct is initialized with the file. - * - * @param file The file - */ - public FileContent(java.io.File file) { - _file = file; - } - - /** - * This method returns the content name if available. - * - * @return The optional content name - */ - public String getName() { - return (_file.getName()); - } - - /** - * This method returns the input stream for accessing the content. - * - * @return The input stream - * @throws java.io.IOException Failed to get input stream - */ - public java.io.InputStream getInputStream() throws java.io.IOException { - return (new java.io.FileInputStream(_file)); - } - - /** - * This method determines whether the content has an extension - * of the specified type. - * - * @param ext The extension - * @return Whether the content has the specified extension - */ - public boolean hasExtension(String ext) { - int index=_file.getName().lastIndexOf('.'); - String sourceType=null; - - if (index != -1) { - sourceType = _file.getName().substring(index+1); - } - - return (sourceType.equals(ext)); - } - - /** - * This method determines whether the content is an XSD type of - * the value specified. - * - * @param xsdType The XSD type name - * @return Whether the content is an XSD type of the specified name - */ - public boolean isXSDType(QName xsdType) { - // TODO: Implement method - throw new UnsupportedOperationException(); - } - - /** - * This method determines whether the content is an XSD element of - * the value specified. - * - * @param xsdElem The XSD element name - * @return Whether the content is an XSD element of the specified name - */ - public boolean isXSDElement(QName xsdElem) { - // TODO: Implement method - throw new UnsupportedOperationException(); - } - -} diff --git a/bundles/org.scribble.common/src/main/java/org/scribble/common/resource/ResourceContent.java b/bundles/org.scribble.common/src/main/java/org/scribble/common/resource/ResourceContent.java deleted file mode 100644 index 928f124ce..000000000 --- a/bundles/org.scribble.common/src/main/java/org/scribble/common/resource/ResourceContent.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Copyright 2009-11 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.common.resource; - -import javax.xml.namespace.QName; - -/** - * This class represents resource content to be used by the Scribble tools. - * - */ -public class ResourceContent implements Content { - - private java.net.URI _uri=null; - - /** - * This construct is initialized with the resource URI. - * - * @param uri The uri - */ - public ResourceContent(java.net.URI uri) { - _uri = uri; - } - - /** - * This method returns the content name if available. - * - * @return The optional content name - */ - public String getName() { - try { - return (_uri.toURL().getFile()); - } catch (Exception e) { - return (null); - } - } - - /** - * This method returns the input stream for accessing the content. - * - * @return The input stream - * @throws java.io.IOException Failed to get input stream - */ - public java.io.InputStream getInputStream() throws java.io.IOException { - return (_uri.toURL().openStream()); - } - - /** - * This method determines whether the content has an extension - * of the specified type. - * - * @param ext The extension - * @return Whether the content has the specified extension - */ - public boolean hasExtension(String ext) { - int index=getName().lastIndexOf('.'); - String sourceType=null; - - if (index != -1) { - sourceType = getName().substring(index+1); - } - - return (sourceType.equals(ext)); - } - - /** - * This method determines whether the content is an XSD type of - * the value specified. - * - * @param xsdType The XSD type name - * @return Whether the content is an XSD type of the specified name - */ - public boolean isXSDType(QName xsdType) { - // TODO: Implement method - throw new UnsupportedOperationException(); - } - - /** - * This method determines whether the content is an XSD element of - * the value specified. - * - * @param xsdElem The XSD element name - * @return Whether the content is an XSD element of the specified name - */ - public boolean isXSDElement(QName xsdElem) { - // TODO: Implement method - throw new UnsupportedOperationException(); - } - -} diff --git a/bundles/org.scribble.common/src/main/java/org/scribble/common/resource/ResourceLocator.java b/bundles/org.scribble.common/src/main/java/org/scribble/common/resource/ResourceLocator.java deleted file mode 100644 index da801b644..000000000 --- a/bundles/org.scribble.common/src/main/java/org/scribble/common/resource/ResourceLocator.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright 2010 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.common.resource; - -/** - * This interface represents a resource locator that can be used to - * load artifacts relative to another resource being processed. - * - */ -public interface ResourceLocator { - - /** - * This method can be used to retrieve the URI of a resource which - * is located at the specified URI, potentially relative to a resource - * that is being processed. - * - * @param uri The relative URI of the resource to load - * @return The URI, or null if not found - * @throws Exception Failed to obtain URI - */ - public java.net.URI getResourceURI(String uri) throws Exception; - -} diff --git a/bundles/org.scribble.common/src/test/java/org/scribble/common/CommonAllTests.java b/bundles/org.scribble.common/src/test/java/org/scribble/common/CommonAllTests.java deleted file mode 100644 index b6639660b..000000000 --- a/bundles/org.scribble.common/src/test/java/org/scribble/common/CommonAllTests.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.common; - -import org.scribble.common.logging.CachedJournalTest; - -import junit.framework.Test; -import junit.framework.TestSuite; - -public class CommonAllTests { - - public static Test suite() { - TestSuite suite = new TestSuite("Test for org.scribble.common"); - //$JUnit-BEGIN$ - suite.addTestSuite(CachedJournalTest.class); - //$JUnit-END$ - return suite; - } - -} diff --git a/bundles/org.scribble.common/src/test/java/org/scribble/common/logging/CachedJournalTest.java b/bundles/org.scribble.common/src/test/java/org/scribble/common/logging/CachedJournalTest.java deleted file mode 100644 index 57e4a3d0a..000000000 --- a/bundles/org.scribble.common/src/test/java/org/scribble/common/logging/CachedJournalTest.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.common.logging; - -import junit.framework.TestCase; - -//import static org.junit.Assert.*; - -public class CachedJournalTest extends TestCase { - - private static final String ISSUE_VALUE1 = "IssueValue1"; - private static final String ISSUE_KEY1 = "IssueKey1"; - private static final String TEST_ISSUE = "TestIssue"; - - //@org.junit.Test - public void testGetIssues() { - CachedJournal journal=new CachedJournal(); - - java.util.Map props=new java.util.HashMap(); - props.put(ISSUE_KEY1, ISSUE_VALUE1); - - journal.error(TEST_ISSUE, props); - - java.util.List details=journal.getIssues(); - - if (details.size() != 1) { - fail("Should be one entry"); - } - - CachedJournal.IssueDetails d=details.get(0); - - if (d.getMessage().equals(TEST_ISSUE) == false) { - fail("Message not correct"); - } - - if (d.getIssueType() != CachedJournal.IssueType.Error) { - fail("Issue type not an error"); - } - - if (d.getProperties() != props) { - fail("Properties not the same"); - } - } -} diff --git a/bundles/org.scribble.common/src/test/java/org/scribble/common/logging/TestJournal.java b/bundles/org.scribble.common/src/test/java/org/scribble/common/logging/TestJournal.java deleted file mode 100644 index 4a22bd54a..000000000 --- a/bundles/org.scribble.common/src/test/java/org/scribble/common/logging/TestJournal.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright 2009 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.common.logging; - -import java.util.Map; - -import org.scribble.common.logging.Journal; - -//import static org.junit.Assert.*; - -@org.junit.Ignore -public class TestJournal implements Journal { - - public void debug(String issue, Map props) { - } - - public void error(String issue, Map props) { - m_errors.add(issue); - } - - public int getErrorCount() { - return (m_errors.size()); - } - - public void verifyErrors(String[] errors) { - java.util.List logged=new java.util.Vector(m_errors); - - for (int i=0; i < errors.length; i++) { - int ind=logged.indexOf(errors[i]); - - if (ind == -1) { - //fail("Expected message '"+errors[i]+"' did not occur"); - throw new RuntimeException("Expected message '"+errors[i]+"' did not occur"); - } else { - logged.remove(ind); - } - } - - if (logged.size() > 0) { - //fail("Unexpected errors occurred: "+logged); - throw new RuntimeException("Unexpected errors occurred: "+logged); - } - } - - public void info(String issue, Map props) { - } - - public void trace(String issue, Map props) { - } - - public void warning(String issue, Map props) { - } - - private java.util.List m_errors=new java.util.Vector(); -} diff --git a/bundles/org.scribble.protocol.conformance/META-INF/MANIFEST.MF b/bundles/org.scribble.protocol.conformance/META-INF/MANIFEST.MF deleted file mode 100644 index 1db13270f..000000000 --- a/bundles/org.scribble.protocol.conformance/META-INF/MANIFEST.MF +++ /dev/null @@ -1,16 +0,0 @@ -Manifest-Version: 1.0 -Bundle-ManifestVersion: 2 -Bundle-Name: Scribble Protocol Conformance -Bundle-SymbolicName: org.scribble.protocol.conformance;singleton:=true -Bundle-Version: 2.1.0.SNAPSHOT -Bundle-Vendor: www.scribble.org -Import-Package: org.osgi.framework;version="1.3.0", - org.scribble.common.logging, - org.scribble.protocol, - org.scribble.protocol.conformance, - org.scribble.protocol.model, - org.scribble.protocol.util -Export-Package: org.scribble.protocol.conformance.impl -Bundle-RequiredExecutionEnvironment: JavaSE-1.6 -Bundle-ActivationPolicy: lazy -Bundle-Activator: org.scribble.protocol.conformance.osgi.Activator diff --git a/bundles/org.scribble.protocol.conformance/build.properties b/bundles/org.scribble.protocol.conformance/build.properties deleted file mode 100644 index df02314e5..000000000 --- a/bundles/org.scribble.protocol.conformance/build.properties +++ /dev/null @@ -1,13 +0,0 @@ -source.. = src/main/java/,\ - src/main/resources/ -output.. = bin/ -bin.includes = META-INF/,\ - .,\ - LICENSE.txt -src.includes = .classpath,\ - .project,\ - LICENSE.txt,\ - META-INF/,\ - build.properties,\ - pom.xml,\ - src/ diff --git a/bundles/org.scribble.protocol.conformance/pom.xml b/bundles/org.scribble.protocol.conformance/pom.xml deleted file mode 100644 index ba93c4c80..000000000 --- a/bundles/org.scribble.protocol.conformance/pom.xml +++ /dev/null @@ -1,39 +0,0 @@ - - 4.0.0 - org.scribble.bundles - org.scribble.protocol.conformance - jar - 2.1.0-SNAPSHOT - Scribble::Bundles::ProtocolConformance - - - org.scribble - bundles - 2.1.0-SNAPSHOT - - - - - org.scribble.bundles - org.scribble.common - ${scribble.bundles.version} - - - org.scribble.bundles - org.scribble.protocol - ${scribble.bundles.version} - - - org.osgi - org.osgi.core - ${osgi.version} - - - junit - junit - test - - - - diff --git a/bundles/org.scribble.protocol.conformance/src/main/java/org/scribble/protocol/conformance/impl/ProtocolConformerImpl.java b/bundles/org.scribble.protocol.conformance/src/main/java/org/scribble/protocol/conformance/impl/ProtocolConformerImpl.java deleted file mode 100644 index aaef6638c..000000000 --- a/bundles/org.scribble.protocol.conformance/src/main/java/org/scribble/protocol/conformance/impl/ProtocolConformerImpl.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright 2009-11 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.conformance.impl; - -import org.scribble.protocol.conformance.ConformanceHandler; -import org.scribble.protocol.conformance.ProtocolConformer; -import org.scribble.protocol.model.ProtocolModel; - -/** - * This class provides the implementation of the protocol conformer. - * - */ -public class ProtocolConformerImpl implements ProtocolConformer { - - /** - * {@inheritDoc} - */ - public void conforms(ProtocolModel model, ProtocolModel ref, - ConformanceHandler handler) { - - // Normalise the models - model = ProtocolNormalizer.normalize(model); - ref = ProtocolNormalizer.normalize(ref); - - // Compare the protocols - //compare(model.getProtocol(), ref.getProtocol(), handler); - } - -} diff --git a/bundles/org.scribble.protocol.conformance/src/main/java/org/scribble/protocol/conformance/impl/ProtocolNormalizer.java b/bundles/org.scribble.protocol.conformance/src/main/java/org/scribble/protocol/conformance/impl/ProtocolNormalizer.java deleted file mode 100644 index 415fd4769..000000000 --- a/bundles/org.scribble.protocol.conformance/src/main/java/org/scribble/protocol/conformance/impl/ProtocolNormalizer.java +++ /dev/null @@ -1,212 +0,0 @@ -/* - * Copyright 2009-11 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.conformance.impl; - -import java.util.Collections; -import java.util.Comparator; -import java.util.logging.Logger; - -import org.scribble.protocol.model.Activity; -import org.scribble.protocol.model.Block; -import org.scribble.protocol.model.Choice; -import org.scribble.protocol.model.DirectedChoice; -import org.scribble.protocol.model.Do; -import org.scribble.protocol.model.Interrupt; -import org.scribble.protocol.model.ModelObject; -import org.scribble.protocol.model.OnMessage; -import org.scribble.protocol.model.Parallel; -import org.scribble.protocol.model.Protocol; -import org.scribble.protocol.model.ProtocolModel; -import org.scribble.protocol.model.Run; -import org.scribble.protocol.model.Unordered; -import org.scribble.protocol.model.DefaultVisitor; - -/** - * This class provides protocol normalisation functionality. - * - */ -public final class ProtocolNormalizer { - - private static final Logger LOG=Logger.getLogger(ProtocolNormalizer.class.getName()); - - /** - * Private constructor. - */ - private ProtocolNormalizer() { - } - - /** - * This method normalises the supplied protocol model. - * - * @param pm The protocol model - * @return The normalised model - */ - public static ProtocolModel normalize(ProtocolModel pm) { - pm.visit(new NormalizingVisitor()); - - return (pm); - } - - /** - * This class visits the protocol to perform the normalisation. - * - */ - private static class NormalizingVisitor extends DefaultVisitor { - -/* Don't reorder for now - issue is receives from same role should retain their order, - * and also original positions need to be preserved from reporting purposes - @Override - public boolean start(Block elem) { - - // Check for multiple consecutive receives, and order them - java.util.List receives=new java.util.Vector(); - - for (int i=0; i < elem.size(); i++) { - Activity act=elem.get(i); - - if (act instanceof Interaction && - ((Interaction)act).getToRoles().size() == 0) { - receives.add((Interaction)act); - } else { - if (receives.size() > 1) { - // Need to check ordering - reorderReceives(elem, i-receives.size(), receives); - } - - receives.clear(); - } - } - - if (receives.size() > 1) { - // Need to check ordering - reorderReceives(elem, elem.size()-receives.size(), receives); - } - - return true; - } - - protected void reorderReceives(Block elem, int index, java.util.List receives) { - Collections.sort(receives, new Comparator() { - public int compare(Interaction arg0, Interaction arg1) { - return (arg0.getMessageSignature().toString().compareTo( - arg1.getMessageSignature().toString())); - } - }); - - for (int i=0; i < receives.size(); i++) { - elem.getContents().set(index+i, receives.get(i)); - } - } -*/ - - @Override - public boolean start(Choice elem) { - - // Sort paths based on textual description for now - Collections.sort(elem.getPaths(), new Comparator() { - public int compare(Block arg0, Block arg1) { - return (arg0.toString().compareTo( - arg1.toString())); - } - }); - - return true; - } - - @Override - public boolean start(DirectedChoice elem) { - // Sort paths based on textual description for now - Collections.sort(elem.getOnMessages(), new Comparator() { - public int compare(OnMessage arg0, OnMessage arg1) { - return (arg0.getMessageSignature().toString().compareTo( - arg1.getMessageSignature().toString())); - } - }); - - return true; - } - - @Override - public boolean start(Parallel elem) { - // Sort paths based on textual description for now - Collections.sort(elem.getPaths(), new Comparator() { - public int compare(Block arg0, Block arg1) { - return (arg0.toString().compareTo( - arg1.toString())); - } - }); - return true; - } - - @Override - public boolean start(Protocol elem) { - // TODO Auto-generated method stub - return true; - } - - @Override - public boolean start(Unordered elem) { - // Replace with a parallel construct - Parallel p=new Parallel(); - p.derivedFrom(elem); - - for (int i=elem.getBlock().size()-1; i >= 0; i--) { - Activity act=elem.getBlock().getContents().remove(i); - - Block b=new Block(); - b.add(act); - - p.getPaths().add(0, b); - } - - start(p); - - ModelObject parent=elem.getParent(); - if (parent instanceof Block) { - int pos=((Block)parent).indexOf(elem); - if (pos == -1) { - LOG.severe("Could not find unordered construct in parent block"); - } else { - ((Block)parent).getContents().set(pos, p); - } - } else { - LOG.severe("Unordered construct's parent was not a block"); - } - - return true; - } - - @Override - public boolean start(Do elem) { - // Sort paths based on textual description for now - Collections.sort(elem.getInterrupts(), new Comparator() { - public int compare(Interrupt arg0, Interrupt arg1) { - return (arg0.toString().compareTo( - arg1.toString())); - } - }); - return true; - } - - @Override - public void accept(Run elem) { - // TODO: Need to expand the 'run' protocol (if nested), only - // leaving run construct if external protocol, or would result - // in recursive definition - - } - } -} diff --git a/bundles/org.scribble.protocol.conformance/src/main/java/org/scribble/protocol/conformance/impl/rules/ConformanceRule.java b/bundles/org.scribble.protocol.conformance/src/main/java/org/scribble/protocol/conformance/impl/rules/ConformanceRule.java deleted file mode 100644 index 974e8f81f..000000000 --- a/bundles/org.scribble.protocol.conformance/src/main/java/org/scribble/protocol/conformance/impl/rules/ConformanceRule.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright 2009-11 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.conformance.impl.rules; - -import org.scribble.protocol.conformance.ConformanceHandler; - -/** - * This interface represents a conformance rule. - * - * @param The model type being conformance checked - */ -public interface ConformanceRule { - - /** - * This method checks the conformance of two model objects - * of the same type. - * - * @param model The model object - * @param ref The reference object - * @param handler Report conformance issues - * @return Whether the model and reference objects conform - */ - public boolean conforms(T model, T ref, ConformanceHandler handler); - -} diff --git a/bundles/org.scribble.protocol.conformance/src/main/java/org/scribble/protocol/conformance/impl/rules/ConformanceRuleManager.java b/bundles/org.scribble.protocol.conformance/src/main/java/org/scribble/protocol/conformance/impl/rules/ConformanceRuleManager.java deleted file mode 100644 index dae05b204..000000000 --- a/bundles/org.scribble.protocol.conformance/src/main/java/org/scribble/protocol/conformance/impl/rules/ConformanceRuleManager.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright 2009-11 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.conformance.impl.rules; - -import org.scribble.protocol.conformance.ConformanceHandler; -import org.scribble.protocol.model.Interaction; -import org.scribble.protocol.model.ModelObject; - -/** - * Manager for conformance rules. - * - */ -public final class ConformanceRuleManager { - - private final static java.util.Map, ConformanceRule> RULES= - new java.util.HashMap, ConformanceRule>(); - - static { - RULES.put(Interaction.class, new InteractionConformanceRule()); - } - - /** - * Private constructor. - */ - private ConformanceRuleManager() { - } - - /** - * This method determines whether a rule exists for the supplied - * model object. - * - * @param modelObject The model object - * @return Whether a rule exists - */ - public static boolean hasRule(ModelObject modelObject) { - return (RULES.containsKey(modelObject.getClass())); - } - - /** - * This method determines whether the supplied model and - * reference components conform. - * - * @param model The model object - * @param ref The reference object - * @param handler Handler for reporting conformance issues - * @return Whether they conform - * - * @param Model component type - */ - public static boolean conforms(T model, T ref, ConformanceHandler handler) { - boolean ret=false; - - @SuppressWarnings({ "unchecked" }) - ConformanceRule rule=(ConformanceRule)RULES.get(model.getClass()); - - if (rule != null) { - ret = rule.conforms(model, ref, handler); - } - - return (ret); - } -} diff --git a/bundles/org.scribble.protocol.conformance/src/main/java/org/scribble/protocol/conformance/impl/rules/InteractionConformanceRule.java b/bundles/org.scribble.protocol.conformance/src/main/java/org/scribble/protocol/conformance/impl/rules/InteractionConformanceRule.java deleted file mode 100644 index 7f266891a..000000000 --- a/bundles/org.scribble.protocol.conformance/src/main/java/org/scribble/protocol/conformance/impl/rules/InteractionConformanceRule.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright 2009-11 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.conformance.impl.rules; - -import java.util.Collections; - -import org.scribble.protocol.conformance.ConformanceHandler; -import org.scribble.protocol.model.Interaction; - -/** - * This class defines the interaction conformance rule. - * - */ -public class InteractionConformanceRule implements ConformanceRule { - - /** - * {@inheritDoc} - */ - public boolean conforms(Interaction model, Interaction ref, ConformanceHandler handler) { - boolean ret=false; - - if (model.getMessageSignature().equals(ref.getMessageSignature())) { - - // TODO: NEED TO HANDLE ROLE MAPPING! - - // Check roles - if ((model.getFromRole() == null || ref.getFromRole() == null - || model.getFromRole().equals(ref.getFromRole()) - && (model.getToRoles().size() == 0 - || ref.getToRoles().size() == 0 - || !Collections.disjoint(model.getToRoles(), ref.getToRoles())))) { - ret = true; - } - } - - return (ret); - } - -} diff --git a/bundles/org.scribble.protocol.conformance/src/main/java/org/scribble/protocol/conformance/osgi/Activator.java b/bundles/org.scribble.protocol.conformance/src/main/java/org/scribble/protocol/conformance/osgi/Activator.java deleted file mode 100644 index ec5773265..000000000 --- a/bundles/org.scribble.protocol.conformance/src/main/java/org/scribble/protocol/conformance/osgi/Activator.java +++ /dev/null @@ -1,40 +0,0 @@ -package org.scribble.protocol.conformance.osgi; - -import java.util.Properties; - -import org.osgi.framework.BundleActivator; -import org.osgi.framework.BundleContext; -import org.scribble.protocol.conformance.ProtocolConformer; -import org.scribble.protocol.conformance.impl.ProtocolConformerImpl; - -/** - * The activator. - * - */ -public class Activator implements BundleActivator { - - /** - * Start the bundle. - * @param context The context - * @throws Exception Failed to start - * @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext) - */ - public void start(BundleContext context) throws Exception { - Properties props = new Properties(); - - ProtocolConformer pp=new ProtocolConformerImpl(); - - context.registerService(ProtocolConformer.class.getName(), - pp, props); - } - - /** - * Stop the bundle. - * @param context The context - * @throws Exception Failed to stop - * @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext) - */ - public void stop(BundleContext context) throws Exception { - } - -} diff --git a/bundles/org.scribble.protocol.conformance/src/main/resources/OSGI-INF/protocol-conformance.xml b/bundles/org.scribble.protocol.conformance/src/main/resources/OSGI-INF/protocol-conformance.xml deleted file mode 100644 index 7ea901cd3..000000000 --- a/bundles/org.scribble.protocol.conformance/src/main/resources/OSGI-INF/protocol-conformance.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/bundles/org.scribble.protocol.conformance/src/main/resources/org/scribble/protocol/conformance/impl/Messages.properties b/bundles/org.scribble.protocol.conformance/src/main/resources/org/scribble/protocol/conformance/impl/Messages.properties deleted file mode 100644 index 3c7757a8e..000000000 --- a/bundles/org.scribble.protocol.conformance/src/main/resources/org/scribble/protocol/conformance/impl/Messages.properties +++ /dev/null @@ -1,16 +0,0 @@ -#/* -# * Copyright 2009-11 Scribble.org -# * -# * 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 -# * -# * http://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. -# * -# */ diff --git a/bundles/org.scribble.protocol.conformance/src/test/java/org/scribble/protocol/conformance/impl/ProtocolNormalizerTest.java b/bundles/org.scribble.protocol.conformance/src/test/java/org/scribble/protocol/conformance/impl/ProtocolNormalizerTest.java deleted file mode 100644 index 37b6691d0..000000000 --- a/bundles/org.scribble.protocol.conformance/src/test/java/org/scribble/protocol/conformance/impl/ProtocolNormalizerTest.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright 2009-11 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.conformance.impl; - -import static org.junit.Assert.*; - -import org.junit.Test; -import org.scribble.protocol.model.*; - -public class ProtocolNormalizerTest { - - @Test - public void testReorderChoicePaths() { - - ProtocolModel pm=new ProtocolModel(); - - Protocol p=new Protocol(); - pm.setProtocol(p); - - Role roleA=new Role("A"); - Role roleB=new Role("B"); - - Choice c=new Choice(); - p.getBlock().add(c); - - Block b1=new Block(); - - Interaction i1=new Interaction(); - i1.setMessageSignature(new MessageSignature(new TypeReference("M1"))); - i1.setFromRole(roleA); - b1.add(i1); - - Block b2=new Block(); - - Interaction i2=new Interaction(); - i2.setMessageSignature(new MessageSignature(new TypeReference("M2"))); - i2.setFromRole(roleB); - b2.add(i2); - - c.getPaths().add(b2); - c.getPaths().add(b1); - - ProtocolModel result=ProtocolNormalizer.normalize(pm); - - Choice c2=(Choice)result.getProtocol().getBlock().get(0); - - if (c2.getPaths().get(0).equals(b1) == false) { - fail("First block not expected"); - } - - if (c2.getPaths().get(1).equals(b2) == false) { - fail("Second block not expected"); - } - } - -} diff --git a/bundles/org.scribble.protocol.conformance/src/test/java/org/scribble/protocol/conformance/impl/rules/InteractionConformanceRuleTest.java b/bundles/org.scribble.protocol.conformance/src/test/java/org/scribble/protocol/conformance/impl/rules/InteractionConformanceRuleTest.java deleted file mode 100644 index c800d1aa6..000000000 --- a/bundles/org.scribble.protocol.conformance/src/test/java/org/scribble/protocol/conformance/impl/rules/InteractionConformanceRuleTest.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright 2009-11 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.conformance.impl.rules; - -import static org.junit.Assert.*; - -import org.junit.Test; -import org.scribble.protocol.model.*; - -public class InteractionConformanceRuleTest { - - @Test - public void testValidInteraction() { - InteractionConformanceRule rule=new InteractionConformanceRule(); - - Interaction model=new Interaction(); - model.setMessageSignature(new MessageSignature(new TypeReference("A"))); - model.setFromRole(new Role("A")); - - Interaction ref=new Interaction(); - ref.setMessageSignature(new MessageSignature(new TypeReference("A"))); - ref.setFromRole(new Role("A")); - - if (rule.conforms(model, ref, null) == false) { - fail("Should not fail"); - } - } - - - @Test - public void testInvalidInteraction() { - InteractionConformanceRule rule=new InteractionConformanceRule(); - - Interaction model=new Interaction(); - model.setMessageSignature(new MessageSignature(new TypeReference("A"))); - model.setFromRole(new Role("A")); - - Interaction ref=new Interaction(); - ref.setMessageSignature(new MessageSignature(new TypeReference("A"))); - ref.setFromRole(new Role("B")); - - if (rule.conforms(model, ref, null) == true) { - fail("Should fail"); - } - } -} diff --git a/bundles/org.scribble.protocol.export.monitor/LICENSE.txt b/bundles/org.scribble.protocol.export.monitor/LICENSE.txt deleted file mode 100644 index 29f81d812..000000000 --- a/bundles/org.scribble.protocol.export.monitor/LICENSE.txt +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - 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 - - http://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. diff --git a/bundles/org.scribble.protocol.export.monitor/META-INF/MANIFEST.MF b/bundles/org.scribble.protocol.export.monitor/META-INF/MANIFEST.MF deleted file mode 100644 index 8265f4f4b..000000000 --- a/bundles/org.scribble.protocol.export.monitor/META-INF/MANIFEST.MF +++ /dev/null @@ -1,14 +0,0 @@ -Manifest-Version: 1.0 -Bundle-ManifestVersion: 2 -Bundle-Name: Scribble Protocol Export Monitor -Bundle-SymbolicName: org.scribble.protocol.export.monitor -Bundle-Version: 2.1.0.SNAPSHOT -Bundle-Activator: org.scribble.protocol.export.monitor.osgi.Activator -Bundle-Vendor: www.scribble.org -Bundle-RequiredExecutionEnvironment: JavaSE-1.6 -Import-Package: org.osgi.framework;version="1.3.0" -Require-Bundle: org.scribble.protocol, - org.scribble.common, - org.scribble.protocol.monitor -Bundle-ClassPath: . -Export-Package: org.scribble.protocol.export.monitor diff --git a/bundles/org.scribble.protocol.export.monitor/build.properties b/bundles/org.scribble.protocol.export.monitor/build.properties deleted file mode 100644 index 5ead1c4d5..000000000 --- a/bundles/org.scribble.protocol.export.monitor/build.properties +++ /dev/null @@ -1,13 +0,0 @@ -source.. = src/main/java/ -output.. = bin/ -bin.includes = META-INF/,\ - .,\ - src/main/resources/,\ - LICENSE.txt -src.includes = src/,\ - META-INF/,\ - .classpath,\ - .project,\ - build.properties,\ - pom.xml,\ - LICENSE.txt diff --git a/bundles/org.scribble.protocol.export.monitor/pom.xml b/bundles/org.scribble.protocol.export.monitor/pom.xml deleted file mode 100644 index 5bba3f341..000000000 --- a/bundles/org.scribble.protocol.export.monitor/pom.xml +++ /dev/null @@ -1,44 +0,0 @@ - - 4.0.0 - org.scribble.bundles - org.scribble.protocol.export.monitor - jar - 2.1.0-SNAPSHOT - Scribble::Bundles::ProtocolExportMonitor - - - org.scribble - bundles - 2.1.0-SNAPSHOT - - - - - org.scribble.bundles - org.scribble.common - ${scribble.bundles.version} - - - org.scribble.bundles - org.scribble.protocol - ${scribble.bundles.version} - - - org.scribble.bundles - org.scribble.protocol.monitor - ${scribble.bundles.version} - - - org.osgi - org.osgi.core - ${osgi.version} - - - junit - junit - test - - - - diff --git a/bundles/org.scribble.protocol.export.monitor/src/main/java/org/scribble/protocol/export/monitor/MonitorExportVisitor.java b/bundles/org.scribble.protocol.export.monitor/src/main/java/org/scribble/protocol/export/monitor/MonitorExportVisitor.java deleted file mode 100644 index 012f6b105..000000000 --- a/bundles/org.scribble.protocol.export.monitor/src/main/java/org/scribble/protocol/export/monitor/MonitorExportVisitor.java +++ /dev/null @@ -1,1049 +0,0 @@ -/* - * Copyright 2009-12 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.export.monitor; - -import java.util.UUID; -import java.util.logging.Logger; - -import org.scribble.common.logging.Journal; -import org.scribble.protocol.model.Activity; -import org.scribble.protocol.model.Block; -import org.scribble.protocol.model.CustomActivity; -import org.scribble.protocol.model.DefaultVisitor; -import org.scribble.protocol.model.DirectedChoice; -import org.scribble.protocol.model.Interaction; -import org.scribble.protocol.model.Interrupt; -import org.scribble.protocol.model.Introduces; -import org.scribble.protocol.model.MessageSignature; -import org.scribble.protocol.model.ModelObject; -import org.scribble.protocol.model.ProtocolImportList; -import org.scribble.protocol.model.RecBlock; -import org.scribble.protocol.model.Recursion; -import org.scribble.protocol.model.Repeat; -import org.scribble.protocol.model.Role; -import org.scribble.protocol.model.TypeImport; -import org.scribble.protocol.model.TypeImportList; -import org.scribble.protocol.model.TypeReference; -import org.scribble.protocol.model.Unordered; -import org.scribble.protocol.monitor.model.Call; -import org.scribble.protocol.monitor.model.Decision; -import org.scribble.protocol.monitor.model.Description; -import org.scribble.protocol.monitor.model.MessageNode; -import org.scribble.protocol.monitor.model.MessageType; -import org.scribble.protocol.monitor.model.Node; -import org.scribble.protocol.monitor.model.Path; -import org.scribble.protocol.monitor.model.ReceiveMessage; -import org.scribble.protocol.monitor.model.Scope; -import org.scribble.protocol.monitor.model.SendMessage; -import org.scribble.protocol.util.RunUtil; -import org.scribble.protocol.util.TypesUtil; - -/** - * This class provides the visitor for traversing the model to export - * to the monitor description. - * - */ -public class MonitorExportVisitor extends DefaultVisitor { - - private static Logger LOG=Logger.getLogger(MonitorExportVisitor.class.getName()); - - private Journal _journal=null; - - // This list defines the nodes used to create the final representation of the - // state machine - private java.util.List _nodes= - new java.util.Vector(); - - private java.util.Map> _choicePaths= - new java.util.HashMap>(); - - private java.util.Map> _parallelPaths= - new java.util.HashMap>(); - - private java.util.Map _recurPosition= - new java.util.HashMap(); - - // This list represents a cache of nodes that are awaiting their 'nextIndex' field - // to be set - private java.util.List _pendingNextIndex= - new java.util.Vector(); - - // This map contains a reference from an activity, to other relevant information required - // later (e.g. nodes, etc). - private java.util.Map _nodeMap= - new java.util.HashMap(); - - private java.util.Map> _nodeCache= - new java.util.HashMap>(); - - /** - * This method sets the journal. - * - * @param journal The journal - */ - public void setJournal(Journal journal) { - _journal = journal; - } - - /** - * This method returns the list of nodes. - * - * @return The list of nodes - */ - protected java.util.List getNodes() { - return(_nodes); - } - - /** - * This method returns the pending next index list. - * - * @return The pending next index list - */ - protected java.util.List getPendingNextIndex() { - return (_pendingNextIndex); - } - - /** - * This method indicates the start of a - * block. - * - * @param elem The block - * @return Whether to process the contents - */ - public boolean start(Block elem) { - startActivity(elem); - - return (true); - } - - /** - * This method processes the start of an activity. - * - * @param act The activity - */ - protected void startActivity(Activity act) { - - // Check if activity is block and parent is parallel - if ((act instanceof Block && act.getParent() instanceof org.scribble.protocol.model.Parallel) - || (act.getParent() instanceof Block - && act.getParent().getParent() instanceof Unordered)) { - - // Create path node - Path path=new Path(); - - org.scribble.protocol.monitor.model.Parallel node=getParallelNode(act); - - java.util.List pathBuilderList= - _parallelPaths.get(node); - - if (pathBuilderList == null) { - pathBuilderList = new java.util.Vector(); - _parallelPaths.put(node, pathBuilderList); - } - - pathBuilderList.add(path); - - _pendingNextIndex.add(path); - - // Create annotations - for (org.scribble.common.model.Annotation pma : act.getAnnotations()) { - org.scribble.protocol.monitor.model.Annotation pmma= - new org.scribble.protocol.monitor.model.Annotation(); - - if (pma.getId() != null) { - pmma.setId(pma.getId()); - } else { - pmma.setId(UUID.randomUUID().toString()); - } - pmma.setValue(pma.toString()); - - path.getAnnotation().add(pmma); - } - - } else if (act instanceof Block && act.getParent() instanceof org.scribble.protocol.model.Choice) { - - // Create path node - Path path=new Path(); - - // Define id associated with the choice label - //path.setId(ChoiceUtil.getLabel(elem.getMessageSignature())); - - org.scribble.protocol.monitor.model.Choice choiceBuilder= - (org.scribble.protocol.monitor.model.Choice)_nodeMap.get(act.getParent()); - - java.util.List pathBuilderList= - _choicePaths.get(choiceBuilder); - - if (pathBuilderList == null) { - pathBuilderList = new java.util.Vector(); - _choicePaths.put(choiceBuilder, pathBuilderList); - } - - pathBuilderList.add(path); - - _pendingNextIndex.add(path); - - // Create annotations - for (org.scribble.common.model.Annotation pma : act.getAnnotations()) { - org.scribble.protocol.monitor.model.Annotation pmma= - new org.scribble.protocol.monitor.model.Annotation(); - - if (pma.getId() != null) { - pmma.setId(pma.getId()); - } else { - pmma.setId(UUID.randomUUID().toString()); - } - pmma.setValue(pma.toString()); - - path.getAnnotation().add(pmma); - } - } - - // Ignore blocks when establishing the next index of preceding - // activities. We only want 'nextIndex' fields to be updated to - // point to concrete activities. - if (!(act instanceof Block)) { - establishNextIndex(); - } - } - - /** - * This method processes the end of an activity. - * - * @param act The activity - */ - protected void endActivity(Activity act) { - - if (act.getParent() instanceof org.scribble.protocol.model.Choice) { - java.util.List cache=getCache(act.getParent()); - - cache.addAll(_pendingNextIndex); - } - - // Check if block associated with a parallel or an activity in an - // unordered construct - if (act.getParent() instanceof org.scribble.protocol.model.Choice - || act.getParent() instanceof org.scribble.protocol.model.Parallel - || (act.getParent() instanceof Block - && act.getParent().getParent() instanceof Unordered)) { - - // Make sure pending 'nextIndex' nodes do not get - // set - they just need to result in the trail - // for that context being completed so that the - // parent context is reactivated (once all other - // paths have equally finished) - _pendingNextIndex.clear(); - } - } - - /** - * This method returns a parallel node (if appropriate) for the supplied - * activity node. - * - * @param act The activity - * @return The parallel node or null if not relevant - */ - protected org.scribble.protocol.monitor.model.Parallel getParallelNode(Activity act) { - org.scribble.protocol.monitor.model.Parallel ret=null; - - if (act instanceof Block && act.getParent() instanceof org.scribble.protocol.model.Parallel) { - ret = (org.scribble.protocol.monitor.model.Parallel)_nodeMap.get(act.getParent()); - } else if (act.getParent() instanceof Block - && act.getParent().getParent() instanceof Unordered) { - ret = (org.scribble.protocol.monitor.model.Parallel)_nodeMap.get(act.getParent().getParent()); - } - - return (ret); - } - - /** - * This method indicates the end of a - * block. - * - * @param elem The block - */ - public void end(Block elem) { - - endActivity(elem); - - /* - // Check if block associated with a parallel - if (elem.getParent() instanceof Parallel) { - - // Make sure pending 'nextIndex' nodes do not get - // set - they just need to result in the trail - // for that context being completed so that the - // parent context is reactivated (once all other - // paths have equally finished) - m_pendingNextIndex.clear(); - } - */ - } - - /** - * This method visits an import component. - * - * @param elem The import - */ - public void accept(TypeImportList elem) { - } - - /** - * This method visits an import component. - * - * @param elem The import - */ - public void accept(ProtocolImportList elem) { - } - - /** - * This method visits the introduces construct. - * - * @param elem The introduces construct - */ - public void accept(Introduces elem) { - } - - /** - * This method visits an interaction component. - * - * @param elem The interaction - */ - public void accept(Interaction elem) { - startActivity(elem); - - createInteraction(elem.getMessageSignature(), elem.getFromRole(), elem.getToRoles(), - elem.getAnnotations()); - - endActivity(elem); - } - - /** - * This method creates an interaction node. - * - * @param ms The message signature - * @param fromRole The from role - * @param toRoles The to roles - * @param annotations The annotations - */ - protected void createInteraction(MessageSignature ms, Role fromRole, - java.util.List toRoles, - java.util.List annotations) { - - // TODO: Think about how best to set the next index. Can only do this - // if the next node is within the same scope. If (for example) the - // last node in a nested-protocol, which happens to be called from - // multiple locations, then we need to create a sub-conversation - // context with the positions - and when the trail ends, it should - // complete the sub-conversation context, causing the parent - // context to be notified with the appropriate continuation point. - - MessageNode node=null; - - if (toRoles.size() > 0) { - node = new SendMessage(); - } else { - node = new ReceiveMessage(); - } - - if (ms.getOperation() != null) { - node.setOperator(ms.getOperation()); - } - - for (TypeReference tref : ms.getTypeReferences()) { - String type=tref.getName(); - - // Get type import associated with the reference - TypeImport ti=TypesUtil.getTypeImport(tref); - - if (ti != null && ti.getDataType() != null) { - type = ti.getDataType().getDetails(); - - } else if (TypesUtil.isConcreteTypesDefined(tref.getModel())) { - // Check if any concrete types have bene defined - // If so, report failure to resolve concrete type - _journal.error("Concrete type not found for '" - +type+"'", tref.getProperties()); - } - - MessageType mt=new MessageType(); - mt.setValue(type); - node.getMessageType().add(mt); - } - - // Export annotations - createAnnotations(node, annotations); - - _nodes.add(node); - - _pendingNextIndex.add(node); - } - - /** - * This method creates annotations on the supplied node. - * - * @param node The node - * @param annotations The annotations - */ - protected void createAnnotations(Node node, - java.util.List annotations) { - - for (org.scribble.common.model.Annotation pma : annotations) { - org.scribble.protocol.monitor.model.Annotation pmma= - new org.scribble.protocol.monitor.model.Annotation(); - - if (pma.getId() != null) { - pmma.setId(pma.getId()); - } else { - pmma.setId(UUID.randomUUID().toString()); - } - pmma.setValue(pma.toString()); - - node.getAnnotation().add(pmma); - } - } - - /** - * This method returns the current node index. - * - * @return The index - */ - protected int getCurrentIndex() { - return (_nodes.size()); - } - - /** - * This method establishes the next index. - */ - protected void establishNextIndex() { - // Establish next index association with this node - establishNextIndex(getCurrentIndex()); - } - - /** - * This method establishes the next index. - * - * @param pos The position - */ - protected void establishNextIndex(int pos) { - for (Object b : _pendingNextIndex) { - - if (b instanceof Node) { - ((Node)b).setNextIndex(pos); - } else if (b instanceof Path) { - ((Path)b).setNextIndex(pos); - } - } - - _pendingNextIndex.clear(); - } - - /** - * This method indicates the start of a - * protocol. - * - * @param elem The protocol - * @return Whether to process the contents - */ - @Override - public boolean start(org.scribble.protocol.model.Protocol elem) { - // Clear pending next index - _pendingNextIndex.clear(); - - // Cache the current node position associated with the protocol - _nodeMap.put(elem, new Integer(_nodes.size())); - - return (true); - } - - /** - * This method indicates the end of a - * protocol. - * - * @param elem The protocol - */ - @Override - public void end(org.scribble.protocol.model.Protocol elem) { - // Clear pending next index - _pendingNextIndex.clear(); - - // Check if position has moved, and if so, load the nodes associated - // with the run activities for this protocol - Integer pos=(Integer)_nodeMap.get(elem); - - if (pos != null && pos.intValue() < _nodes.size()) { - - java.util.List objs=_nodeCache.get(elem); - - for (int i=0; objs != null && i < objs.size(); i++) { - if (objs.get(i) instanceof Decision) { - ((Decision)objs.get(i)).setInnerIndex(pos.intValue()); - } else if (objs.get(i) instanceof Scope) { - ((Scope)objs.get(i)).setInnerIndex(pos.intValue()); - } - } - } - } - - /** - * This method indicates the start of a - * choice. - * - * @param elem The choice - * @return Whether to process the contents - */ - public boolean start(org.scribble.protocol.model.Choice elem) { - - startActivity(elem); - - org.scribble.protocol.monitor.model.Choice node= - new org.scribble.protocol.monitor.model.Choice(); - - _nodes.add(node); - - // Cache the node associated with the choice - _nodeMap.put(elem, node); - - return (true); - } - - /** - * This method indicates the end of a - * choice. - * - * @param elem The choice - */ - public void end(org.scribble.protocol.model.Choice elem) { - - java.util.List cache=getCache(elem); - - _pendingNextIndex.addAll(cache); - - endActivity(elem); - } - - /** - * This method indicates the start of a - * directed choice. - * - * @param elem The choice - * @return Whether to process the contents - */ - public boolean start(org.scribble.protocol.model.DirectedChoice elem) { - - startActivity(elem); - - org.scribble.protocol.monitor.model.Choice node= - new org.scribble.protocol.monitor.model.Choice(); - - _nodes.add(node); - - // Cache the node associated with the choice - _nodeMap.put(elem, node); - - return (true); - } - - /** - * This method indicates the end of a - * directed choice. - * - * @param elem The choice - */ - public void end(org.scribble.protocol.model.DirectedChoice elem) { - - java.util.List cache=getCache(elem); - - _pendingNextIndex.addAll(cache); - - endActivity(elem); - } - - /** - * This method indicates the start of a - * directed choice. - * - * @param elem The choice - * @return Whether to process the contents - */ - public boolean start(org.scribble.protocol.model.OnMessage elem) { - - DirectedChoice dc=(DirectedChoice)elem.getParent(); - - // Create path node - Path path=new Path(); - - // Define id associated with the choice label - //path.setId(ChoiceUtil.getLabel(elem.getMessageSignature())); - - org.scribble.protocol.monitor.model.Choice choiceBuilder= - (org.scribble.protocol.monitor.model.Choice)_nodeMap.get(elem.getParent()); - - java.util.List pathBuilderList= - _choicePaths.get(choiceBuilder); - - if (pathBuilderList == null) { - pathBuilderList = new java.util.Vector(); - _choicePaths.put(choiceBuilder, pathBuilderList); - } - - pathBuilderList.add(path); - - _pendingNextIndex.add(path); - - // Create annotations - for (org.scribble.common.model.Annotation pma : elem.getAnnotations()) { - org.scribble.protocol.monitor.model.Annotation pmma= - new org.scribble.protocol.monitor.model.Annotation(); - - if (pma.getId() != null) { - pmma.setId(pma.getId()); - } else { - pmma.setId(UUID.randomUUID().toString()); - } - pmma.setValue(pma.toString()); - - path.getAnnotation().add(pmma); - } - - establishNextIndex(); - - // Create interaction associated with message signature - createInteraction(elem.getMessageSignature(), dc.getFromRole(), dc.getToRoles(), - elem.getAnnotations()); - - return (true); - } - - /** - * This method indicates the end of a - * directed choice. - * - * @param elem The choice - */ - public void end(org.scribble.protocol.model.OnMessage elem) { - // Transfer outstanding nodes in 'pendingNextIndex' to the - // cache associated with the choice - java.util.List cache=getCache(elem.getParent()); - - cache.addAll(_pendingNextIndex); - - _pendingNextIndex.clear(); - } - - /** - * This method retrieves a cache of objects associated with - * the supplied model object. - * - * @param elem The model object - * @return The list of cached objects - */ - protected java.util.List getCache(ModelObject elem) { - java.util.List ret=_nodeCache.get(elem); - - if (ret == null) { - ret = new java.util.Vector(); - _nodeCache.put(elem, ret); - } - - return (ret); - } - - /** - * This method visits a run component. - * - * @param elem The run - */ - public void accept(org.scribble.protocol.model.Run elem) { - - startActivity(elem); - - org.scribble.protocol.monitor.model.Scope node= - new org.scribble.protocol.monitor.model.Scope(); - - _nodes.add(node); - - // Cache the node associated with the run - _nodeMap.put(elem, node); - - // Check if calling a local protocol - org.scribble.protocol.model.Protocol inner= - RunUtil.getInnerProtocol(elem.getEnclosingProtocol(), elem.getProtocolReference()); - - if (inner != null) { - java.util.List cache=_nodeCache.get(inner); - - if (cache == null) { - cache = new java.util.Vector(); - _nodeCache.put(inner, cache); - } - - cache.add(node); - } - - /* - if (elem.isInline()) { - m_pendingNextIndex.add(node); - } - */ - - //Node node= - // (Node)m_nodeMap.get(elem); - - /* - if (elem.isInline()) { - m_pendingNextIndex.clear(); - - if (node instanceof Scope) { - ((Scope)node).setInnerIndex(m_nodes.indexOf(node)+1); - } - } - */ - - _pendingNextIndex.add(node); - - endActivity(elem); - } - - /** - * This method indicates the start of a - * parallel. - * - * @param elem The parallel - * @return Whether to process the contents - */ - public boolean start(org.scribble.protocol.model.Parallel elem) { - - startActivity(elem); - - org.scribble.protocol.monitor.model.Parallel node= - new org.scribble.protocol.monitor.model.Parallel(); - - _nodes.add(node); - - // Cache the node associated with the parallel - _nodeMap.put(elem, node); - - return (true); - } - - /** - * This method indicates the end of a - * parallel. - * - * @param elem The parallel - */ - public void end(org.scribble.protocol.model.Parallel elem) { - Node node= - (Node)_nodeMap.get(elem); - - _pendingNextIndex.add(node); - - endActivity(elem); - } - - /** - * This method indicates the start of a - * Unordered. - * - * @param elem The Unordered - * @return Whether to process the contents - */ - public boolean start(Unordered elem) { - - startActivity(elem); - - org.scribble.protocol.monitor.model.Parallel node= - new org.scribble.protocol.monitor.model.Parallel(); - - _nodes.add(node); - - // Cache the node associated with the parallel - _nodeMap.put(elem, node); - - return (true); - } - - /** - * This method indicates the end of a - * Unordered. - * - * @param elem The Unordered - */ - public void end(Unordered elem) { - Node node= - (Node)_nodeMap.get(elem); - - _pendingNextIndex.add(node); - - endActivity(elem); - } - - /** - * This method indicates the start of a - * repeat. - * - * @param elem The repeat - * @return Whether to process the contents - */ - public boolean start(Repeat elem) { - - startActivity(elem); - - Decision node=new Decision(); - - _nodes.add(node); - - // Cache the node associated with the choice - _nodeMap.put(elem, node); - - return (true); - } - - /** - * This method indicates the end of a - * repeat. - * - * @param elem The repeat - */ - public void end(Repeat elem) { - Node node= - (Node)_nodeMap.get(elem); - - // Set the current 'pending next index' entries to the - // repeat node - establishNextIndex(_nodes.indexOf(node)); - - if (node instanceof Decision) { - ((Decision)node).setInnerIndex(_nodes.indexOf(node)+1); - } - - _pendingNextIndex.add(node); - - endActivity(elem); - } - - /** - * This method visits a recursion component. - * - * @param elem The recursion - */ - public void accept(Recursion elem) { - - startActivity(elem); - - Call node=new Call(); - - if (_recurPosition.containsKey(elem.getLabel())) { - //establishNextIndex(m_recurPosition.get(elem.getLabel())); - - node.setCallIndex(_recurPosition.get(elem.getLabel())); - } else { - LOG.severe("Unable to find recursion label '"+elem.getLabel()+"'"); - } - - _nodes.add(node); - - _pendingNextIndex.add(node); - - // TODO: Not sure how this should be handled when in unordered construct?? - endActivity(elem); - } - - /** - * This method indicates the start of a - * labelled block. - * - * @param elem The labelled block - * @return Whether to process the contents - */ - public boolean start(RecBlock elem) { - - startActivity(elem); - - // Register current node against labelled block label - _recurPosition.put(elem.getLabel(), _nodes.size()); - - org.scribble.protocol.monitor.model.Scope node= - new org.scribble.protocol.monitor.model.Scope(); - - _nodes.add(node); - - // Cache the node associated with the run - _nodeMap.put(elem, node); - - _pendingNextIndex.add(node); - - return (true); - } - - /** - * This method indicates the end of a - * labelled block. - * - * @param elem The labelled block - */ - public void end(RecBlock elem) { - Node node= - (Node)_nodeMap.get(elem); - - _pendingNextIndex.clear(); - - if (node instanceof Scope) { - ((Scope)node).setInnerIndex(_nodes.indexOf(node)+1); - } - - _pendingNextIndex.add(node); - - endActivity(elem); - } - - /** - * This method indicates the start of a - * try escape. - * - * @param elem The try escape - * @return Whether to process the contents - */ - public boolean start(org.scribble.protocol.model.Do elem) { - - startActivity(elem); - - org.scribble.protocol.monitor.model.Do node= - new org.scribble.protocol.monitor.model.Do(); - - _nodes.add(node); - - // Cache the node associated with the try - _nodeMap.put(elem, node); - - return (true); - } - - /** - * This method indicates the end of a - * try escape. - * - * @param elem The try escape - */ - public void end(org.scribble.protocol.model.Do elem) { - Node node= - (Node)_nodeMap.get(elem); - - _pendingNextIndex.clear(); - - if (node instanceof Scope) { - ((Scope)node).setInnerIndex(_nodes.indexOf(node)+1); - } - - _pendingNextIndex.add(node); - - endActivity(elem); - } - - /** - * This method indicates the start of a - * try escape. - * - * @param elem The try escape - * @return Whether to process the contents - */ - public boolean start(Interrupt elem) { - org.scribble.protocol.monitor.model.Do node= - (org.scribble.protocol.monitor.model.Do)_nodeMap.get(elem.getParent()); - - _pendingNextIndex.clear(); - - Path path=new Path(); - path.setNextIndex(getCurrentIndex()); - - node.getPath().add(path); - - // Create annotations - for (org.scribble.common.model.Annotation pma : elem.getAnnotations()) { - org.scribble.protocol.monitor.model.Annotation pmma= - new org.scribble.protocol.monitor.model.Annotation(); - - if (pma.getId() != null) { - pmma.setId(pma.getId()); - } else { - pmma.setId(UUID.randomUUID().toString()); - } - pmma.setValue(pma.toString()); - - path.getAnnotation().add(pmma); - } - - return (true); - } - - /** - * This method indicates the end of a - * try escape. - * - * @param elem The try escape - */ - public void end(Interrupt elem) { - // End of catch block scope, so clear the 'pending next index' nodes - _pendingNextIndex.clear(); - } - - /** - * This method visits a custom activity component. - * - * @param elem The custom activity - */ - public void accept(CustomActivity elem) { - } - - /** - * This method returns the protocol description exported from the visited ProtocolModel. - * - * @return The protocol description - */ - public org.scribble.protocol.monitor.model.Description getDescription() { - Description ret=new Description(); - - // Initialise the choice paths. This is done here, rather than in the - // endWhen or endChoice, as the nextIndex on a when path may not be - // initialised until outside the choice. - for (org.scribble.protocol.monitor.model.Choice choice : _choicePaths.keySet()) { - java.util.List pathBuilders=_choicePaths.get(choice); - - for (Path pathBuilder : pathBuilders) { - choice.getPath().add(pathBuilder); - } - } - _choicePaths.clear(); // Need to clear to make sure subsequent calls to getDescription() don't process again - - // Same reason as for choice - for (org.scribble.protocol.monitor.model.Parallel parallel : _parallelPaths.keySet()) { - java.util.List pathBuilders=_parallelPaths.get(parallel); - - for (Path pathBuilder : pathBuilders) { - parallel.getPath().add(pathBuilder); - } - } - _parallelPaths.clear(); // Need to clear to make sure subsequent calls to getDescription() don't process again - - for (Node b : _nodes) { - ret.getNode().add(b); - } - - return (ret); - } -} diff --git a/bundles/org.scribble.protocol.export.monitor/src/main/java/org/scribble/protocol/export/monitor/MonitorProtocolExporter.java b/bundles/org.scribble.protocol.export.monitor/src/main/java/org/scribble/protocol/export/monitor/MonitorProtocolExporter.java deleted file mode 100644 index 6570f5301..000000000 --- a/bundles/org.scribble.protocol.export.monitor/src/main/java/org/scribble/protocol/export/monitor/MonitorProtocolExporter.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.export.monitor; - -import java.util.logging.Level; -import java.util.logging.Logger; - -import org.scribble.common.logging.Journal; -import org.scribble.protocol.export.ProtocolExporter; -import org.scribble.protocol.model.ProtocolModel; -import org.scribble.protocol.monitor.model.Description; -import org.scribble.protocol.monitor.util.MonitorModelUtil; - -/** - * This implementation of the protocol exporter interface generates - * the internal monitoring description for a protocol. - * - */ -public class MonitorProtocolExporter implements ProtocolExporter { - - /** - * Monitor export id. - */ - public static final String MONITOR_ID = "monitor"; - - private final static Logger LOG=Logger.getLogger(MonitorProtocolExporter.class.getName()); - - private MonitorExportVisitor _visitor=new MonitorExportVisitor(); - - /** - * This method returns the id of the exporter. - * - * @return The exporter id - */ - public String getId() { - return (MONITOR_ID); - } - - /** - * This method returns the name of the exporter for use in - * user based selectors. - * - * @return The name of the exporter - */ - public String getName() { - return ("Monitor"); - } - - /** - * This method sets the monitor export visitor. - * - * @param mev The monitor export visitor - */ - public void setMonitorExportVisitor(MonitorExportVisitor mev) { - _visitor = mev; - } - - /** - * This method exports the supplied protocol model, in the implementation - * specific format, to the specified output stream. If any issues occur - * during the export process, they will be reported to the journal. - * - * @param model The protocol model to be exported - * @param journal The journal - * @param os The output stream - */ - public void export(ProtocolModel model, Journal journal, java.io.OutputStream os) { - Description desc=generateDescription(model, journal); - - try { - MonitorModelUtil.serialize(desc, os); - } catch (Exception e) { - LOG.log(Level.SEVERE, "Failed to export protocol to monitor description", e); - journal.error("Export failed due to exception: "+e, null); - } - } - - /** - * This method generates the protocol model's monitoring description. - * - * @param model The protocol model - * @param journal The journal for reporting errors - * @return The monitoring description - */ - public Description generateDescription(ProtocolModel model, Journal journal) { - _visitor.setJournal(journal); - - model.visit(_visitor); - - Description desc=_visitor.getDescription(); - - return (desc); - } - -} diff --git a/bundles/org.scribble.protocol.export.monitor/src/main/java/org/scribble/protocol/export/monitor/osgi/Activator.java b/bundles/org.scribble.protocol.export.monitor/src/main/java/org/scribble/protocol/export/monitor/osgi/Activator.java deleted file mode 100644 index d4a0796d0..000000000 --- a/bundles/org.scribble.protocol.export.monitor/src/main/java/org/scribble/protocol/export/monitor/osgi/Activator.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.export.monitor.osgi; - -import java.util.Properties; - -import org.osgi.framework.BundleActivator; -import org.osgi.framework.BundleContext; -import org.scribble.protocol.export.ProtocolExporter; -import org.scribble.protocol.export.monitor.MonitorProtocolExporter; - -/** - * The activator. - * - */ -public class Activator implements BundleActivator { - - /** - * Start the bundle. - * @param context The context - * @exception Exception Failed to start - * @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext) - */ - public void start(BundleContext context) throws Exception { - Properties props = new Properties(); - - context.registerService(ProtocolExporter.class.getName(), - new MonitorProtocolExporter(), props); - } - - /** - * Stop the bundle. - * @param context The context - * @exception Exception Failed to stop - * @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext) - */ - public void stop(BundleContext context) throws Exception { - } - -} diff --git a/bundles/org.scribble.protocol.export.monitor/src/test/java/org/scribble/protocol/export/monitor/MonitorProtocolExporterTest.java b/bundles/org.scribble.protocol.export.monitor/src/test/java/org/scribble/protocol/export/monitor/MonitorProtocolExporterTest.java deleted file mode 100644 index 0231949c9..000000000 --- a/bundles/org.scribble.protocol.export.monitor/src/test/java/org/scribble/protocol/export/monitor/MonitorProtocolExporterTest.java +++ /dev/null @@ -1,1692 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.export.monitor; - -import static org.junit.Assert.*; - -import java.io.ByteArrayOutputStream; - -import org.scribble.common.logging.CachedJournal; -import org.scribble.protocol.model.*; -import org.scribble.protocol.monitor.util.MonitorModelUtil; - -public class MonitorProtocolExporterTest { - - private static final String SUBPROTOCOL = "subprotocol"; - private static final String ORDER = "Order"; - private static final String ORDER_TYPE = "Order"; - - @org.junit.Test - public void testSimpleInteraction() { - - ProtocolModel pm=new ProtocolModel(); - - TypeImportList imp1=new TypeImportList(); - TypeImport t1=new TypeImport(); - t1.setName(ORDER_TYPE); - imp1.getTypeImports().add(t1); - pm.getImports().add(imp1); - - Role p1=new Role(); - p1.setName("p1"); - - Role p2=new Role(); - p2.setName("p2"); - - Protocol p=new Protocol(); - p.setLocatedRole(p1); - pm.setProtocol(p); - - Interaction i1=new Interaction(); - MessageSignature ms1=new MessageSignature(); - ms1.setOperation("op1"); - TypeReference tref1=new TypeReference(); - tref1.setName(ORDER); - ms1.getTypeReferences().add(tref1); - - i1.setMessageSignature(ms1); - i1.getToRoles().add(p2); - - p.getBlock().add(i1); - - MonitorProtocolExporter exporter=new MonitorProtocolExporter(); - - CachedJournal journal=new CachedJournal(); - ByteArrayOutputStream os=new ByteArrayOutputStream(); - - exporter.export(pm, journal, os); - - if (journal.getIssues().size() > 0) { - fail("Export should not have raised any issues"); - } - - org.scribble.protocol.monitor.model.Description pd=null; - - try { - pd = org.scribble.protocol.monitor.util.MonitorModelUtil.deserialize(new java.io.ByteArrayInputStream(os.toByteArray())); - } catch (Exception e) { - e.printStackTrace(); - fail("Failed to parse protocol monitor description: "+e); - } - - validateMonitor(pd, "SimpleInteraction"); - } - - @org.junit.Test - public void testSimpleInteractionWithAnnotation() { - - ProtocolModel pm=new ProtocolModel(); - - TypeImportList imp1=new TypeImportList(); - TypeImport t1=new TypeImport(); - t1.setName(ORDER_TYPE); - imp1.getTypeImports().add(t1); - pm.getImports().add(imp1); - - Role p1=new Role(); - p1.setName("p1"); - - Role p2=new Role(); - p2.setName("p2"); - - Protocol p=new Protocol(); - p.setLocatedRole(p1); - pm.setProtocol(p); - - Interaction i1=new Interaction(); - MessageSignature ms1=new MessageSignature(); - ms1.setOperation("op1"); - TypeReference tref1=new TypeReference(); - tref1.setName(ORDER); - ms1.getTypeReferences().add(tref1); - - i1.setMessageSignature(ms1); - i1.getToRoles().add(p2); - - org.scribble.common.model.Annotation a1= - new org.scribble.common.model.DefaultAnnotation("a1", " My Annotation "); - i1.getAnnotations().add(a1); - - p.getBlock().add(i1); - - MonitorProtocolExporter exporter=new MonitorProtocolExporter(); - - CachedJournal journal=new CachedJournal(); - ByteArrayOutputStream os=new ByteArrayOutputStream(); - - exporter.export(pm, journal, os); - - if (journal.getIssues().size() > 0) { - fail("Export should not have raised any issues"); - } - - org.scribble.protocol.monitor.model.Description pd=null; - - try { - pd = org.scribble.protocol.monitor.util.MonitorModelUtil.deserialize(new java.io.ByteArrayInputStream(os.toByteArray())); - } catch (Exception e) { - e.printStackTrace(); - fail("Failed to parse protocol monitor description: "+e); - } - - validateMonitor(pd, "SimpleInteractionWithAnnotation"); - } - - @org.junit.Test - public void testSimpleSequence() { - - ProtocolModel pm=new ProtocolModel(); - - Role p1=new Role(); - p1.setName("p1"); - - Role p2=new Role(); - p2.setName("p2"); - - Protocol p=new Protocol(); - p.setLocatedRole(p1); - pm.setProtocol(p); - - Interaction i1=new Interaction(); - MessageSignature ms1=new MessageSignature(); - ms1.setOperation("op1"); - i1.setMessageSignature(ms1); - i1.getToRoles().add(p2); - - p.getBlock().add(i1); - - Interaction i2=new Interaction(); - MessageSignature ms2=new MessageSignature(); - ms2.setOperation("op2"); - i2.setMessageSignature(ms2); - i2.setFromRole(p2); - - p.getBlock().add(i2); - - MonitorProtocolExporter exporter=new MonitorProtocolExporter(); - - CachedJournal journal=new CachedJournal(); - ByteArrayOutputStream os=new ByteArrayOutputStream(); - - exporter.export(pm, journal, os); - - if (journal.getIssues().size() > 0) { - fail("Export should not have raised any issues"); - } - - org.scribble.protocol.monitor.model.Description pd=null; - - try { - pd = org.scribble.protocol.monitor.util.MonitorModelUtil.deserialize(new java.io.ByteArrayInputStream(os.toByteArray())); - } catch (Exception e) { - e.printStackTrace(); - fail("Failed to parse protocol monitor description: "+e); - } - - if (pd.getNode().size() != 2) { - fail("Expected 2 nodes: "+pd.getNode().size()); - } - - org.scribble.protocol.monitor.model.Node pn1=pd.getNode().get(0); - org.scribble.protocol.monitor.model.Node pn2=pd.getNode().get(1); - - if (pn1.getNextIndex() != 1) { - fail("Node 1 next index incorrect"); - } - - if ((pn1 instanceof org.scribble.protocol.monitor.model.SendMessage) == false) { - fail("Node 1 wrong node type"); - } - - if (pn2.getNextIndex() != -1) { - fail("Node 2 next index incorrect"); - } - - if ((pn2 instanceof org.scribble.protocol.monitor.model.ReceiveMessage) == false) { - fail("Node 2 wrong node type"); - } - } - - @org.junit.Test - public void testSimpleChoiceFollowedByInteraction() { - - ProtocolModel pm=new ProtocolModel(); - - Role p1=new Role(); - p1.setName("p1"); - - Role p2=new Role(); - p2.setName("p2"); - - Protocol p=new Protocol(); - p.setLocatedRole(p1); - pm.setProtocol(p); - - Interaction i1=new Interaction(); - MessageSignature ms1=new MessageSignature(); - ms1.setOperation("op1"); - i1.setMessageSignature(ms1); - i1.getToRoles().add(p2); - - p.getBlock().add(i1); - - Choice c1=new Choice(); - c1.setRole(p2); - - p.getBlock().add(c1); - - Block wb1=new Block(); - - Interaction iwb1=new Interaction(); - - MessageSignature ms2=new MessageSignature(); - ms2.setOperation("op2"); - - TypeReference tr2=new TypeReference(); - tr2.setName("M2"); - ms2.getTypeReferences().add(tr2); - - iwb1.setMessageSignature(ms2); - iwb1.setFromRole(p2); - - wb1.add(iwb1); - - Interaction i3=new Interaction(); - MessageSignature ms3=new MessageSignature(); - ms3.setOperation("op3"); - i3.setMessageSignature(ms3); - i3.getToRoles().add(p2); - - wb1.add(i3); - - c1.getPaths().add(wb1); - - Block wb2=new Block(); - - Interaction iwb2=new Interaction(); - - MessageSignature ms4=new MessageSignature(); - ms4.setOperation("op4"); - iwb2.setMessageSignature(ms4); - - iwb2.setFromRole(p2); - wb2.add(iwb2); - - Interaction i5=new Interaction(); - MessageSignature ms5=new MessageSignature(); - ms5.setOperation("op5"); - i5.setMessageSignature(ms5); - i5.getToRoles().add(p2); - - wb2.add(i5); - - c1.getPaths().add(wb2); - - Interaction i6=new Interaction(); - MessageSignature ms6=new MessageSignature(); - ms6.setOperation("op6"); - i6.setMessageSignature(ms6); - i6.setFromRole(p2); - - p.getBlock().add(i6); - - MonitorProtocolExporter exporter=new MonitorProtocolExporter(); - - CachedJournal journal=new CachedJournal(); - ByteArrayOutputStream os=new ByteArrayOutputStream(); - - exporter.export(pm, journal, os); - - if (journal.getIssues().size() > 0) { - fail("Export should not have raised any issues"); - } - - org.scribble.protocol.monitor.model.Description pd=null; - - try { - pd = org.scribble.protocol.monitor.util.MonitorModelUtil.deserialize(new java.io.ByteArrayInputStream(os.toByteArray())); - } catch (Exception e) { - e.printStackTrace(); - fail("Failed to parse protocol monitor description: "+e); - } - - validateMonitor(pd, "SimpleChoiceFollowedByInteraction"); - } - - @org.junit.Test - public void testSimpleDirectedChoiceFollowedByInteraction() { - - ProtocolModel pm=new ProtocolModel(); - - Role p1=new Role(); - p1.setName("p1"); - - Role p2=new Role(); - p2.setName("p2"); - - Protocol p=new Protocol(); - p.setLocatedRole(p1); - pm.setProtocol(p); - - Interaction i1=new Interaction(); - MessageSignature ms1=new MessageSignature(); - ms1.setOperation("op1"); - i1.setMessageSignature(ms1); - i1.getToRoles().add(p2); - - p.getBlock().add(i1); - - DirectedChoice c1=new DirectedChoice(); - c1.setFromRole(p2); - - p.getBlock().add(c1); - - OnMessage wb1=new OnMessage(); - - MessageSignature ms2=new MessageSignature(); - ms2.setOperation("op2"); - - TypeReference tr2=new TypeReference(); - tr2.setName("M2"); - ms2.getTypeReferences().add(tr2); - - wb1.setMessageSignature(ms2); - - Interaction i3=new Interaction(); - MessageSignature ms3=new MessageSignature(); - ms3.setOperation("op3"); - i3.setMessageSignature(ms3); - i3.getToRoles().add(p2); - - wb1.getBlock().add(i3); - - c1.getOnMessages().add(wb1); - - OnMessage wb2=new OnMessage(); - - MessageSignature ms4=new MessageSignature(); - ms4.setOperation("op4"); - wb2.setMessageSignature(ms4); - - Interaction i5=new Interaction(); - MessageSignature ms5=new MessageSignature(); - ms5.setOperation("op5"); - i5.setMessageSignature(ms5); - i5.getToRoles().add(p2); - - wb2.getBlock().add(i5); - - c1.getOnMessages().add(wb2); - - Interaction i6=new Interaction(); - MessageSignature ms6=new MessageSignature(); - ms6.setOperation("op6"); - i6.setMessageSignature(ms6); - i6.setFromRole(p2); - - p.getBlock().add(i6); - - MonitorProtocolExporter exporter=new MonitorProtocolExporter(); - - CachedJournal journal=new CachedJournal(); - ByteArrayOutputStream os=new ByteArrayOutputStream(); - - exporter.export(pm, journal, os); - - if (journal.getIssues().size() > 0) { - fail("Export should not have raised any issues"); - } - - org.scribble.protocol.monitor.model.Description pd=null; - - try { - pd = org.scribble.protocol.monitor.util.MonitorModelUtil.deserialize(new java.io.ByteArrayInputStream(os.toByteArray())); - } catch (Exception e) { - e.printStackTrace(); - fail("Failed to parse protocol monitor description: "+e); - } - - validateMonitor(pd, "SimpleDirectedChoiceFollowedByInteraction"); - } - - @org.junit.Test - public void testSimpleChoiceFollowedByInteractionWithAnnotation() { - - ProtocolModel pm=new ProtocolModel(); - - Role p1=new Role(); - p1.setName("p1"); - - Role p2=new Role(); - p2.setName("p2"); - - Protocol p=new Protocol(); - p.setLocatedRole(p1); - pm.setProtocol(p); - - Interaction i1=new Interaction(); - MessageSignature ms1=new MessageSignature(); - ms1.setOperation("op1"); - i1.setMessageSignature(ms1); - i1.getToRoles().add(p2); - - p.getBlock().add(i1); - - Choice c1=new Choice(); - c1.setRole(p2); - - p.getBlock().add(c1); - - Block wb1=new Block(); - - Interaction iwb1=new Interaction(); - - org.scribble.common.model.Annotation a0= - new org.scribble.common.model.DefaultAnnotation("a0", " My Annotation0 "); - iwb1.getAnnotations().add(a0); - - MessageSignature ms2=new MessageSignature(); - ms2.setOperation("op2"); - - TypeReference tr2=new TypeReference(); - tr2.setName("M2"); - ms2.getTypeReferences().add(tr2); - - iwb1.setMessageSignature(ms2); - iwb1.setFromRole(p2); - wb1.add(iwb1); - - Interaction i3=new Interaction(); - MessageSignature ms3=new MessageSignature(); - ms3.setOperation("op3"); - i3.setMessageSignature(ms3); - i3.getToRoles().add(p2); - - wb1.add(i3); - - org.scribble.common.model.Annotation a1= - new org.scribble.common.model.DefaultAnnotation("a1", " My Annotation "); - wb1.getAnnotations().add(a1); - - c1.getPaths().add(wb1); - - Block wb2=new Block(); - - Interaction iwb2=new Interaction(); - - MessageSignature ms4=new MessageSignature(); - ms4.setOperation("op4"); - iwb2.setMessageSignature(ms4); - - iwb2.setFromRole(p2); - wb2.add(iwb2); - - Interaction i5=new Interaction(); - MessageSignature ms5=new MessageSignature(); - ms5.setOperation("op5"); - i5.setMessageSignature(ms5); - i5.getToRoles().add(p2); - - wb2.add(i5); - - org.scribble.common.model.Annotation a2= - new org.scribble.common.model.DefaultAnnotation("a2", " My Annotation2 "); - wb2.getAnnotations().add(a2); - - c1.getPaths().add(wb2); - - Interaction i6=new Interaction(); - MessageSignature ms6=new MessageSignature(); - ms6.setOperation("op6"); - i6.setMessageSignature(ms6); - i6.setFromRole(p2); - - p.getBlock().add(i6); - - MonitorProtocolExporter exporter=new MonitorProtocolExporter(); - - CachedJournal journal=new CachedJournal(); - ByteArrayOutputStream os=new ByteArrayOutputStream(); - - exporter.export(pm, journal, os); - - if (journal.getIssues().size() > 0) { - fail("Export should not have raised any issues"); - } - - org.scribble.protocol.monitor.model.Description pd=null; - - try { - pd = org.scribble.protocol.monitor.util.MonitorModelUtil.deserialize(new java.io.ByteArrayInputStream(os.toByteArray())); - } catch (Exception e) { - e.printStackTrace(); - fail("Failed to parse protocol monitor description: "+e); - } - - validateMonitor(pd, "SimpleChoiceFollowedByInteractionWithAnnotation"); - } - - @org.junit.Test - public void testSimpleChoiceFollowedByNoActivity() { - - ProtocolModel pm=new ProtocolModel(); - - Role p1=new Role(); - p1.setName("p1"); - - Role p2=new Role(); - p2.setName("p2"); - - Protocol p=new Protocol(); - p.setLocatedRole(p1); - pm.setProtocol(p); - - Interaction i1=new Interaction(); - MessageSignature ms1=new MessageSignature(); - ms1.setOperation("op1"); - i1.setMessageSignature(ms1); - i1.getToRoles().add(p2); - - p.getBlock().add(i1); - - Choice c1=new Choice(); - c1.setRole(p2); - - p.getBlock().add(c1); - - Block wb1=new Block(); - - Interaction iwb1=new Interaction(); - - MessageSignature ms2=new MessageSignature(); - ms2.setOperation("op2"); - - TypeReference tr2=new TypeReference(); - tr2.setName("M2"); - ms2.getTypeReferences().add(tr2); - - iwb1.setMessageSignature(ms2); - iwb1.setFromRole(p2); - - wb1.add(iwb1); - - Interaction i3=new Interaction(); - MessageSignature ms3=new MessageSignature(); - ms3.setOperation("op3"); - i3.setMessageSignature(ms3); - i3.getToRoles().add(p2); - - wb1.add(i3); - - c1.getPaths().add(wb1); - - Block wb2=new Block(); - - Interaction iwb2=new Interaction(); - - MessageSignature ms4=new MessageSignature(); - ms4.setOperation("op4"); - iwb2.setMessageSignature(ms4); - - iwb2.setFromRole(p2); - wb2.add(iwb2); - - Interaction i5=new Interaction(); - MessageSignature ms5=new MessageSignature(); - ms5.setOperation("op5"); - i5.setMessageSignature(ms5); - i5.getToRoles().add(p2); - - wb2.add(i5); - - c1.getPaths().add(wb2); - - MonitorProtocolExporter exporter=new MonitorProtocolExporter(); - - CachedJournal journal=new CachedJournal(); - ByteArrayOutputStream os=new ByteArrayOutputStream(); - - exporter.export(pm, journal, os); - - if (journal.getIssues().size() > 0) { - fail("Export should not have raised any issues"); - } - - org.scribble.protocol.monitor.model.Description pd=null; - - try { - pd = org.scribble.protocol.monitor.util.MonitorModelUtil.deserialize(new java.io.ByteArrayInputStream(os.toByteArray())); - } catch (Exception e) { - e.printStackTrace(); - fail("Failed to parse protocol monitor description: "+e); - } - - validateMonitor(pd, "SimpleChoiceFollowedByNoActivity"); - } - - @org.junit.Test - public void testSimpleDirectedChoiceFollowedByNoActivity() { - - ProtocolModel pm=new ProtocolModel(); - - Role p1=new Role(); - p1.setName("p1"); - - Role p2=new Role(); - p2.setName("p2"); - - Protocol p=new Protocol(); - p.setLocatedRole(p1); - pm.setProtocol(p); - - Interaction i1=new Interaction(); - MessageSignature ms1=new MessageSignature(); - ms1.setOperation("op1"); - i1.setMessageSignature(ms1); - i1.getToRoles().add(p2); - - p.getBlock().add(i1); - - DirectedChoice c1=new DirectedChoice(); - c1.setFromRole(p2); - - p.getBlock().add(c1); - - OnMessage wb1=new OnMessage(); - - MessageSignature ms2=new MessageSignature(); - ms2.setOperation("op2"); - - TypeReference tr2=new TypeReference(); - tr2.setName("M2"); - ms2.getTypeReferences().add(tr2); - - wb1.setMessageSignature(ms2); - - Interaction i3=new Interaction(); - MessageSignature ms3=new MessageSignature(); - ms3.setOperation("op3"); - i3.setMessageSignature(ms3); - i3.getToRoles().add(p2); - - wb1.getBlock().add(i3); - - c1.getOnMessages().add(wb1); - - OnMessage wb2=new OnMessage(); - - MessageSignature ms4=new MessageSignature(); - ms4.setOperation("op4"); - wb2.setMessageSignature(ms4); - - Interaction i5=new Interaction(); - MessageSignature ms5=new MessageSignature(); - ms5.setOperation("op5"); - i5.setMessageSignature(ms5); - i5.getToRoles().add(p2); - - wb2.getBlock().add(i5); - - c1.getOnMessages().add(wb2); - - MonitorProtocolExporter exporter=new MonitorProtocolExporter(); - - CachedJournal journal=new CachedJournal(); - ByteArrayOutputStream os=new ByteArrayOutputStream(); - - exporter.export(pm, journal, os); - - if (journal.getIssues().size() > 0) { - fail("Export should not have raised any issues"); - } - - org.scribble.protocol.monitor.model.Description pd=null; - - try { - pd = org.scribble.protocol.monitor.util.MonitorModelUtil.deserialize(new java.io.ByteArrayInputStream(os.toByteArray())); - } catch (Exception e) { - e.printStackTrace(); - fail("Failed to parse protocol monitor description: "+e); - } - - validateMonitor(pd, "SimpleDirectedChoiceFollowedByNoActivity"); - } - - @org.junit.Test - public void testSimpleChoiceWithEmptyPathFollowedByInteraction() { - - ProtocolModel pm=new ProtocolModel(); - - Role p1=new Role(); - p1.setName("p1"); - - Role p2=new Role(); - p2.setName("p2"); - - Protocol p=new Protocol(); - p.setLocatedRole(p1); - pm.setProtocol(p); - - Interaction i1=new Interaction(); - MessageSignature ms1=new MessageSignature(); - ms1.setOperation("op1"); - i1.setMessageSignature(ms1); - i1.getToRoles().add(p2); - - p.getBlock().add(i1); - - Choice c1=new Choice(); - c1.setRole(p2); - - p.getBlock().add(c1); - - Block wb1=new Block(); - - Interaction iwb1=new Interaction(); - - MessageSignature ms2=new MessageSignature(); - ms2.setOperation("op2"); - - TypeReference tr2=new TypeReference(); - tr2.setName("M2"); - ms2.getTypeReferences().add(tr2); - - iwb1.setMessageSignature(ms2); - iwb1.setFromRole(p2); - wb1.add(iwb1); - - Interaction i3=new Interaction(); - MessageSignature ms3=new MessageSignature(); - ms3.setOperation("op3"); - i3.setMessageSignature(ms3); - i3.getToRoles().add(p2); - - wb1.add(i3); - - c1.getPaths().add(wb1); - - Block wb2=new Block(); - - c1.getPaths().add(wb2); - - Interaction iwb2=new Interaction(); - - MessageSignature ms4=new MessageSignature(); - ms4.setOperation("op4"); - - TypeReference tr4=new TypeReference(); - tr4.setName("M4"); - ms4.getTypeReferences().add(tr4); - - iwb2.setMessageSignature(ms4); - iwb2.setFromRole(p2); - p.getBlock().add(iwb2); - - MonitorProtocolExporter exporter=new MonitorProtocolExporter(); - - CachedJournal journal=new CachedJournal(); - ByteArrayOutputStream os=new ByteArrayOutputStream(); - - exporter.export(pm, journal, os); - - if (journal.getIssues().size() > 0) { - fail("Export should not have raised any issues"); - } - - org.scribble.protocol.monitor.model.Description pd=null; - - try { - pd = org.scribble.protocol.monitor.util.MonitorModelUtil.deserialize(new java.io.ByteArrayInputStream(os.toByteArray())); - } catch (Exception e) { - e.printStackTrace(); - fail("Failed to parse protocol monitor description: "+e); - } - - validateMonitor(pd, "SimpleChoiceWithEmptyPathFollowedByInteraction"); - } - - @org.junit.Test - public void testSimpleRepeatFollowedByInteraction() { - - ProtocolModel pm=new ProtocolModel(); - - Role p1=new Role(); - p1.setName("p1"); - - Role p2=new Role(); - p2.setName("p2"); - - Protocol p=new Protocol(); - p.setLocatedRole(p1); - pm.setProtocol(p); - - Interaction i1=new Interaction(); - MessageSignature ms1=new MessageSignature(); - ms1.setOperation("op1"); - i1.setMessageSignature(ms1); - i1.getToRoles().add(p2); - - p.getBlock().add(i1); - - Repeat r1=new Repeat(); - r1.getRoles().add(p2); - - p.getBlock().add(r1); - - Interaction i3=new Interaction(); - MessageSignature ms3=new MessageSignature(); - ms3.setOperation("op3"); - i3.setMessageSignature(ms3); - i3.setFromRole(p2); - - r1.getBlock().add(i3); - - Interaction i6=new Interaction(); - MessageSignature ms6=new MessageSignature(); - ms6.setOperation("op6"); - i6.setMessageSignature(ms6); - i6.setFromRole(p2); - - p.getBlock().add(i6); - - MonitorProtocolExporter exporter=new MonitorProtocolExporter(); - - CachedJournal journal=new CachedJournal(); - ByteArrayOutputStream os=new ByteArrayOutputStream(); - - exporter.export(pm, journal, os); - - if (journal.getIssues().size() > 0) { - fail("Export should not have raised any issues"); - } - - org.scribble.protocol.monitor.model.Description pd=null; - - try { - pd = org.scribble.protocol.monitor.util.MonitorModelUtil.deserialize(new java.io.ByteArrayInputStream(os.toByteArray())); - } catch (Exception e) { - e.printStackTrace(); - fail("Failed to parse protocol monitor description: "+e); - } - - validateMonitor(pd, "SimpleRepeatFollowedByInteraction"); - } - - @org.junit.Test - public void testSimpleRepeatFollowedByNoActivity() { - - ProtocolModel pm=new ProtocolModel(); - - Role p1=new Role(); - p1.setName("p1"); - - Role p2=new Role(); - p2.setName("p2"); - - Protocol p=new Protocol(); - p.setLocatedRole(p1); - pm.setProtocol(p); - - Interaction i1=new Interaction(); - MessageSignature ms1=new MessageSignature(); - ms1.setOperation("op1"); - i1.setMessageSignature(ms1); - i1.getToRoles().add(p2); - - p.getBlock().add(i1); - - Repeat r1=new Repeat(); - r1.getRoles().add(p2); - - p.getBlock().add(r1); - - Interaction i3=new Interaction(); - MessageSignature ms3=new MessageSignature(); - ms3.setOperation("op3"); - i3.setMessageSignature(ms3); - i3.setFromRole(p2); - - r1.getBlock().add(i3); - - MonitorProtocolExporter exporter=new MonitorProtocolExporter(); - - CachedJournal journal=new CachedJournal(); - ByteArrayOutputStream os=new ByteArrayOutputStream(); - - exporter.export(pm, journal, os); - - if (journal.getIssues().size() > 0) { - fail("Export should not have raised any issues"); - } - - org.scribble.protocol.monitor.model.Description pd=null; - - try { - pd = org.scribble.protocol.monitor.util.MonitorModelUtil.deserialize(new java.io.ByteArrayInputStream(os.toByteArray())); - } catch (Exception e) { - e.printStackTrace(); - fail("Failed to parse protocol monitor description: "+e); - } - - validateMonitor(pd, "SimpleRepeatFollowedByNoActivity"); - } - - @org.junit.Test - public void testSimpleRunFollowedByInteraction() { - ProtocolModel pm=new ProtocolModel(); - - Role p1=new Role(); - p1.setName("p1"); - - Role p2=new Role(); - p2.setName("p2"); - - Protocol p=new Protocol(); - p.setLocatedRole(p1); - pm.setProtocol(p); - - Interaction i1=new Interaction(); - MessageSignature ms1=new MessageSignature(); - ms1.setOperation("op1"); - i1.setMessageSignature(ms1); - i1.getToRoles().add(p2); - - p.getBlock().add(i1); - - Run r1=new Run(); - ProtocolReference pref=new ProtocolReference(); - pref.setName(SUBPROTOCOL); - pref.setRole(p1); - r1.setProtocolReference(pref); - - p.getBlock().add(r1); - - Interaction i6=new Interaction(); - MessageSignature ms6=new MessageSignature(); - ms6.setOperation("op6"); - i6.setMessageSignature(ms6); - i6.setFromRole(p2); - - p.getBlock().add(i6); - - Protocol subp=new Protocol(); - subp.setName(SUBPROTOCOL); - subp.setLocatedRole(p1); - p.getNestedProtocols().add(subp); - - Interaction i3=new Interaction(); - MessageSignature ms3=new MessageSignature(); - ms3.setOperation("op3"); - i3.setMessageSignature(ms3); - i3.setFromRole(p2); - - subp.getBlock().add(i3); - - MonitorProtocolExporter exporter=new MonitorProtocolExporter(); - - CachedJournal journal=new CachedJournal(); - ByteArrayOutputStream os=new ByteArrayOutputStream(); - - exporter.export(pm, journal, os); - - if (journal.getIssues().size() > 0) { - fail("Export should not have raised any issues"); - } - - org.scribble.protocol.monitor.model.Description pd=null; - - try { - pd = org.scribble.protocol.monitor.util.MonitorModelUtil.deserialize(new java.io.ByteArrayInputStream(os.toByteArray())); - } catch (Exception e) { - e.printStackTrace(); - fail("Failed to parse protocol monitor description: "+e); - } - - validateMonitor(pd, "SimpleRunFollowedByInteraction"); - } - - @org.junit.Test - public void testSimpleRunFollowedByNoActivity() { - ProtocolModel pm=new ProtocolModel(); - - Role p1=new Role(); - p1.setName("p1"); - - Role p2=new Role(); - p2.setName("p2"); - - Protocol p=new Protocol(); - p.setLocatedRole(p1); - pm.setProtocol(p); - - Interaction i1=new Interaction(); - MessageSignature ms1=new MessageSignature(); - ms1.setOperation("op1"); - i1.setMessageSignature(ms1); - i1.getToRoles().add(p2); - - p.getBlock().add(i1); - - Run r1=new Run(); - ProtocolReference pref=new ProtocolReference(); - pref.setName(SUBPROTOCOL); - pref.setRole(p1); - r1.setProtocolReference(pref); - - p.getBlock().add(r1); - - Protocol subp=new Protocol(); - subp.setName(SUBPROTOCOL); - subp.setLocatedRole(p1); - p.getNestedProtocols().add(subp); - - Interaction i3=new Interaction(); - MessageSignature ms3=new MessageSignature(); - ms3.setOperation("op3"); - i3.setMessageSignature(ms3); - i3.setFromRole(p2); - - subp.getBlock().add(i3); - - MonitorProtocolExporter exporter=new MonitorProtocolExporter(); - - CachedJournal journal=new CachedJournal(); - ByteArrayOutputStream os=new ByteArrayOutputStream(); - - exporter.export(pm, journal, os); - - if (journal.getIssues().size() > 0) { - fail("Export should not have raised any issues"); - } - - org.scribble.protocol.monitor.model.Description pd=null; - - try { - pd = org.scribble.protocol.monitor.util.MonitorModelUtil.deserialize(new java.io.ByteArrayInputStream(os.toByteArray())); - } catch (Exception e) { - e.printStackTrace(); - fail("Failed to parse protocol monitor description: "+e); - } - - validateMonitor(pd, "SimpleRunFollowedByNoActivity"); - } - - @org.junit.Test - public void testSimpleRecursionFollowedByInteraction() { - ProtocolModel pm=new ProtocolModel(); - - Role p1=new Role(); - p1.setName("p1"); - - Role p2=new Role(); - p2.setName("p2"); - - Protocol p=new Protocol(); - p.setLocatedRole(p1); - pm.setProtocol(p); - - Interaction i1=new Interaction(); - MessageSignature ms1=new MessageSignature(); - ms1.setOperation("op1"); - i1.setMessageSignature(ms1); - i1.getToRoles().add(p2); - - p.getBlock().add(i1); - - RecBlock r1=new RecBlock(); - r1.setLabel("transaction"); - - p.getBlock().add(r1); - - Choice c1=new Choice(); - c1.setRole(p2); - - r1.getBlock().add(c1); - - Block wb1=new Block(); - - Interaction iwb1=new Interaction(); - - MessageSignature ms2=new MessageSignature(); - ms2.setOperation("op2"); - - TypeReference tr2=new TypeReference(); - tr2.setName("M2"); - ms2.getTypeReferences().add(tr2); - - iwb1.setMessageSignature(ms2); - iwb1.setFromRole(p2); - wb1.add(iwb1); - - Interaction i3=new Interaction(); - MessageSignature ms3=new MessageSignature(); - ms3.setOperation("op3"); - i3.setMessageSignature(ms3); - i3.getToRoles().add(p2); - - wb1.add(i3); - - c1.getPaths().add(wb1); - - Block wb2=new Block(); - - Interaction iwb2=new Interaction(); - - MessageSignature ms4=new MessageSignature(); - ms4.setOperation("op4"); - iwb2.setMessageSignature(ms4); - - iwb2.setFromRole(p2); - wb2.add(iwb2); - - Recursion rec=new Recursion(); - rec.setLabel("transaction"); - - wb2.add(rec); - - c1.getPaths().add(wb2); - - Interaction i6=new Interaction(); - MessageSignature ms6=new MessageSignature(); - ms6.setOperation("op6"); - i6.setMessageSignature(ms6); - i6.setFromRole(p2); - - p.getBlock().add(i6); - - MonitorProtocolExporter exporter=new MonitorProtocolExporter(); - - CachedJournal journal=new CachedJournal(); - ByteArrayOutputStream os=new ByteArrayOutputStream(); - - exporter.export(pm, journal, os); - - if (journal.getIssues().size() > 0) { - fail("Export should not have raised any issues"); - } - - org.scribble.protocol.monitor.model.Description pd=null; - - try { - pd = org.scribble.protocol.monitor.util.MonitorModelUtil.deserialize(new java.io.ByteArrayInputStream(os.toByteArray())); - } catch (Exception e) { - e.printStackTrace(); - fail("Failed to parse protocol monitor description: "+e); - } - - validateMonitor(pd, "SimpleRecursionFollowedByInteraction"); - } - - - @org.junit.Test - public void testSimpleRecursionWithInnerInteractionFollowedByInteraction() { - ProtocolModel pm=new ProtocolModel(); - - Role p1=new Role(); - p1.setName("p1"); - - Role p2=new Role(); - p2.setName("p2"); - - Protocol p=new Protocol(); - p.setLocatedRole(p1); - pm.setProtocol(p); - - Interaction i1=new Interaction(); - MessageSignature ms1=new MessageSignature(); - ms1.setOperation("op1"); - i1.setMessageSignature(ms1); - i1.getToRoles().add(p2); - - p.getBlock().add(i1); - - RecBlock r1=new RecBlock(); - r1.setLabel("transaction"); - - p.getBlock().add(r1); - - Choice c1=new Choice(); - c1.setRole(p2); - - r1.getBlock().add(c1); - - Block wb1=new Block(); - - Interaction iwb1=new Interaction(); - - MessageSignature ms2=new MessageSignature(); - ms2.setOperation("op2"); - - TypeReference tr2=new TypeReference(); - tr2.setName("M2"); - ms2.getTypeReferences().add(tr2); - - iwb1.setMessageSignature(ms2); - iwb1.setFromRole(p2); - wb1.add(iwb1); - - Interaction i3=new Interaction(); - MessageSignature ms3=new MessageSignature(); - ms3.setOperation("op3"); - i3.setMessageSignature(ms3); - i3.getToRoles().add(p2); - - wb1.add(i3); - - c1.getPaths().add(wb1); - - Block wb2=new Block(); - - Interaction iwb2=new Interaction(); - - MessageSignature ms4=new MessageSignature(); - ms4.setOperation("op4"); - iwb2.setMessageSignature(ms4); - iwb2.setFromRole(p2); - - wb2.add(iwb2); - - Recursion rec=new Recursion(); - rec.setLabel("transaction"); - - wb2.add(rec); - - Interaction i5=new Interaction(); - MessageSignature ms5=new MessageSignature(); - ms5.setOperation("op5"); - i5.setMessageSignature(ms5); - i5.getToRoles().add(p2); - - wb2.add(i5); - - c1.getPaths().add(wb2); - - Interaction i6=new Interaction(); - MessageSignature ms6=new MessageSignature(); - ms6.setOperation("op6"); - i6.setMessageSignature(ms6); - i6.setFromRole(p2); - - p.getBlock().add(i6); - - MonitorProtocolExporter exporter=new MonitorProtocolExporter(); - - CachedJournal journal=new CachedJournal(); - ByteArrayOutputStream os=new ByteArrayOutputStream(); - - exporter.export(pm, journal, os); - - if (journal.getIssues().size() > 0) { - fail("Export should not have raised any issues"); - } - - org.scribble.protocol.monitor.model.Description pd=null; - - try { - pd = org.scribble.protocol.monitor.util.MonitorModelUtil.deserialize(new java.io.ByteArrayInputStream(os.toByteArray())); - } catch (Exception e) { - e.printStackTrace(); - fail("Failed to parse protocol monitor description: "+e); - } - - validateMonitor(pd, "SimpleRecursionWithInnerInteractionFollowedByInteraction"); - } - - @org.junit.Test - public void testSimpleParallelFollowedByInteraction() { - - ProtocolModel pm=new ProtocolModel(); - - Role p1=new Role(); - p1.setName("p1"); - - Role p2=new Role(); - p2.setName("p2"); - - Protocol p=new Protocol(); - p.setLocatedRole(p1); - pm.setProtocol(p); - - Interaction i1=new Interaction(); - MessageSignature ms1=new MessageSignature(); - ms1.setOperation("op1"); - i1.setMessageSignature(ms1); - i1.getToRoles().add(p2); - - p.getBlock().add(i1); - - Parallel par1=new Parallel(); - - p.getBlock().add(par1); - - Block b1=new Block(); - par1.getPaths().add(b1); - - Interaction i3=new Interaction(); - MessageSignature ms3=new MessageSignature(); - ms3.setOperation("op3"); - i3.setMessageSignature(ms3); - i3.getToRoles().add(p2); - - b1.add(i3); - - Block b2=new Block(); - par1.getPaths().add(b2); - - Interaction i5=new Interaction(); - MessageSignature ms5=new MessageSignature(); - ms5.setOperation("op5"); - i5.setMessageSignature(ms5); - i5.getToRoles().add(p2); - - b2.add(i5); - - - Interaction i6=new Interaction(); - MessageSignature ms6=new MessageSignature(); - ms6.setOperation("op6"); - i6.setMessageSignature(ms6); - i6.setFromRole(p2); - - p.getBlock().add(i6); - - MonitorProtocolExporter exporter=new MonitorProtocolExporter(); - - CachedJournal journal=new CachedJournal(); - ByteArrayOutputStream os=new ByteArrayOutputStream(); - - exporter.export(pm, journal, os); - - if (journal.getIssues().size() > 0) { - fail("Export should not have raised any issues"); - } - - org.scribble.protocol.monitor.model.Description pd=null; - - try { - pd = org.scribble.protocol.monitor.util.MonitorModelUtil.deserialize(new java.io.ByteArrayInputStream(os.toByteArray())); - } catch (Exception e) { - e.printStackTrace(); - fail("Failed to parse protocol monitor description: "+e); - } - - validateMonitor(pd, "SimpleParallelFollowedByInteraction"); - } - - @org.junit.Test - public void testSimpleUnorderedFollowedByInteraction() { - - ProtocolModel pm=new ProtocolModel(); - - Role p1=new Role(); - p1.setName("p1"); - - Role p2=new Role(); - p2.setName("p2"); - - Protocol p=new Protocol(); - p.setLocatedRole(p1); - pm.setProtocol(p); - - Interaction i1=new Interaction(); - MessageSignature ms1=new MessageSignature(); - ms1.setOperation("op1"); - i1.setMessageSignature(ms1); - i1.getToRoles().add(p2); - - p.getBlock().add(i1); - - Unordered unord=new Unordered(); - - p.getBlock().add(unord); - - Interaction i3=new Interaction(); - MessageSignature ms3=new MessageSignature(); - ms3.setOperation("op3"); - i3.setMessageSignature(ms3); - i3.getToRoles().add(p2); - - unord.getBlock().add(i3); - - Interaction i5=new Interaction(); - MessageSignature ms5=new MessageSignature(); - ms5.setOperation("op5"); - i5.setMessageSignature(ms5); - i5.getToRoles().add(p2); - - unord.getBlock().add(i5); - - - Interaction i6=new Interaction(); - MessageSignature ms6=new MessageSignature(); - ms6.setOperation("op6"); - i6.setMessageSignature(ms6); - i6.setFromRole(p2); - - p.getBlock().add(i6); - - MonitorProtocolExporter exporter=new MonitorProtocolExporter(); - - CachedJournal journal=new CachedJournal(); - ByteArrayOutputStream os=new ByteArrayOutputStream(); - - exporter.export(pm, journal, os); - - if (journal.getIssues().size() > 0) { - fail("Export should not have raised any issues"); - } - - org.scribble.protocol.monitor.model.Description pd=null; - - try { - pd = org.scribble.protocol.monitor.util.MonitorModelUtil.deserialize(new java.io.ByteArrayInputStream(os.toByteArray())); - } catch (Exception e) { - e.printStackTrace(); - fail("Failed to parse protocol monitor description: "+e); - } - - validateMonitor(pd, "SimpleUnorderedFollowedByInteraction"); - } - - @org.junit.Test - public void testSimpleDoInterruptFollowedByInteraction() { - - ProtocolModel pm=new ProtocolModel(); - - Role p1=new Role(); - p1.setName("p1"); - - Role p2=new Role(); - p2.setName("p2"); - - Protocol p=new Protocol(); - p.setLocatedRole(p1); - pm.setProtocol(p); - - Interaction i1=new Interaction(); - MessageSignature ms1=new MessageSignature(); - ms1.setOperation("start"); - i1.setMessageSignature(ms1); - i1.getToRoles().add(p2); - - p.getBlock().add(i1); - - Do t=new Do(); - - p.getBlock().add(t); - - Interaction i2=new Interaction(); - MessageSignature ms2=new MessageSignature(); - ms2.setOperation("order"); - i2.setMessageSignature(ms2); - i2.getToRoles().add(p2); - - t.getBlock().add(i2); - - Interaction i3=new Interaction(); - MessageSignature ms3=new MessageSignature(); - ms3.setOperation("confirm"); - i3.setMessageSignature(ms3); - i3.setFromRole(p2); - - t.getBlock().add(i3); - - Interrupt cb=new Interrupt(); - t.getInterrupts().add(cb); - - Interaction i4=new Interaction(); - MessageSignature ms4=new MessageSignature(); - ms4.setOperation("cancel"); - i4.setMessageSignature(ms4); - i4.getToRoles().add(p2); - cb.getBlock().add(i4); - - Interaction i5=new Interaction(); - MessageSignature ms5=new MessageSignature(); - ms5.setOperation("finish"); - i5.setMessageSignature(ms5); - i5.getToRoles().add(p2); - - p.getBlock().add(i5); - - MonitorProtocolExporter exporter=new MonitorProtocolExporter(); - - CachedJournal journal=new CachedJournal(); - ByteArrayOutputStream os=new ByteArrayOutputStream(); - - exporter.export(pm, journal, os); - - if (journal.getIssues().size() > 0) { - fail("Export should not have raised any issues"); - } - - org.scribble.protocol.monitor.model.Description pd=null; - - try { - pd = org.scribble.protocol.monitor.util.MonitorModelUtil.deserialize(new java.io.ByteArrayInputStream(os.toByteArray())); - } catch (Exception e) { - e.printStackTrace(); - fail("Failed to parse protocol monitor description: "+e); - } - - validateMonitor(pd, "SimpleDoInterruptFollowedByInteraction"); - } - - @org.junit.Test - public void testSimpleDoInterruptMultipleFollowedByInteraction() { - - ProtocolModel pm=new ProtocolModel(); - - Role p1=new Role(); - p1.setName("p1"); - - Role p2=new Role(); - p2.setName("p2"); - - Protocol p=new Protocol(); - p.setLocatedRole(p1); - pm.setProtocol(p); - - Interaction i1=new Interaction(); - MessageSignature ms1=new MessageSignature(); - ms1.setOperation("start"); - i1.setMessageSignature(ms1); - i1.getToRoles().add(p2); - - p.getBlock().add(i1); - - Do t=new Do(); - - p.getBlock().add(t); - - Interaction i2=new Interaction(); - MessageSignature ms2=new MessageSignature(); - ms2.setOperation("order"); - i2.setMessageSignature(ms2); - i2.getToRoles().add(p2); - - t.getBlock().add(i2); - - Interaction i3=new Interaction(); - MessageSignature ms3=new MessageSignature(); - ms3.setOperation("confirm"); - i3.setMessageSignature(ms3); - i3.setFromRole(p2); - - t.getBlock().add(i3); - - Interrupt cb1=new Interrupt(); - t.getInterrupts().add(cb1); - - Interaction i4=new Interaction(); - MessageSignature ms4=new MessageSignature(); - ms4.setOperation("cancel"); - i4.setMessageSignature(ms4); - i4.getToRoles().add(p2); - cb1.getBlock().add(i4); - - Interrupt cb2=new Interrupt(); - t.getInterrupts().add(cb2); - - Interaction i4x=new Interaction(); - MessageSignature ms4x=new MessageSignature(); - ms4x.setOperation("abort"); - i4x.setMessageSignature(ms4x); - i4x.getToRoles().add(p2); - cb2.getBlock().add(i4x); - - Interaction i4y=new Interaction(); - MessageSignature ms4y=new MessageSignature(); - ms4y.setOperation("ack"); - i4y.setMessageSignature(ms4y); - i4y.setFromRole(p2); - - cb2.getBlock().add(i4y); - - Interaction i5=new Interaction(); - MessageSignature ms5=new MessageSignature(); - ms5.setOperation("finish"); - i5.setMessageSignature(ms5); - i5.getToRoles().add(p2); - - p.getBlock().add(i5); - - MonitorProtocolExporter exporter=new MonitorProtocolExporter(); - - CachedJournal journal=new CachedJournal(); - ByteArrayOutputStream os=new ByteArrayOutputStream(); - - exporter.export(pm, journal, os); - - if (journal.getIssues().size() > 0) { - fail("Export should not have raised any issues"); - } - - org.scribble.protocol.monitor.model.Description pd=null; - - try { - pd = org.scribble.protocol.monitor.util.MonitorModelUtil.deserialize(new java.io.ByteArrayInputStream(os.toByteArray())); - } catch (Exception e) { - e.printStackTrace(); - fail("Failed to parse protocol monitor description: "+e); - } - - validateMonitor(pd, "SimpleDoInterruptMultipleFollowedByInteraction"); - } - - protected void validateMonitor(org.scribble.protocol.monitor.model.Description pd, String filename) { - java.io.ByteArrayOutputStream os=new java.io.ByteArrayOutputStream(); - String pdtext=null; - - try { - MonitorModelUtil.serialize(pd, os); - - pdtext = new String(os.toByteArray()); - - os.close(); - } catch (Exception e) { - fail("Failed to serialize description associated with filename '"+filename+"'"); - } - - java.io.InputStream is= - MonitorProtocolExporterTest.class.getResourceAsStream("/monitor/results/"+filename+".txt"); - - if (is == null) { - fail("Failed to load protocol '"+filename+"'"); - } - - byte[] b=null; - - try { - b = new byte[is.available()]; - - is.read(b); - - is.close(); - } catch (Exception e) { - fail("Failed to load result '"+filename+": "+e); - } - - String result=new String(b); - - if (result.equals(pdtext) == false) { - System.out.println("["+filename+"]="+pdtext); - fail("Monitor result incorrect: was expecting (len="+result.length()+") ["+result+ - "] but got (len="+pdtext.length()+") ["+pdtext+"]"); - } - } -} diff --git a/bundles/org.scribble.protocol.export.monitor/src/test/resources/monitor/results/SimpleChoiceFollowedByInteraction.txt b/bundles/org.scribble.protocol.export.monitor/src/test/resources/monitor/results/SimpleChoiceFollowedByInteraction.txt deleted file mode 100644 index 2b485caf4..000000000 --- a/bundles/org.scribble.protocol.export.monitor/src/test/resources/monitor/results/SimpleChoiceFollowedByInteraction.txt +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - - - - - - - - diff --git a/bundles/org.scribble.protocol.export.monitor/src/test/resources/monitor/results/SimpleChoiceFollowedByInteractionWithAnnotation.txt b/bundles/org.scribble.protocol.export.monitor/src/test/resources/monitor/results/SimpleChoiceFollowedByInteractionWithAnnotation.txt deleted file mode 100644 index b3e367686..000000000 --- a/bundles/org.scribble.protocol.export.monitor/src/test/resources/monitor/results/SimpleChoiceFollowedByInteractionWithAnnotation.txt +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - - - - - - - - - - - - - - - diff --git a/bundles/org.scribble.protocol.export.monitor/src/test/resources/monitor/results/SimpleChoiceFollowedByNoActivity.txt b/bundles/org.scribble.protocol.export.monitor/src/test/resources/monitor/results/SimpleChoiceFollowedByNoActivity.txt deleted file mode 100644 index 394e8f7d7..000000000 --- a/bundles/org.scribble.protocol.export.monitor/src/test/resources/monitor/results/SimpleChoiceFollowedByNoActivity.txt +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - - - - - - diff --git a/bundles/org.scribble.protocol.export.monitor/src/test/resources/monitor/results/SimpleChoiceWithEmptyPathFollowedByInteraction.txt b/bundles/org.scribble.protocol.export.monitor/src/test/resources/monitor/results/SimpleChoiceWithEmptyPathFollowedByInteraction.txt deleted file mode 100644 index bac39fec3..000000000 --- a/bundles/org.scribble.protocol.export.monitor/src/test/resources/monitor/results/SimpleChoiceWithEmptyPathFollowedByInteraction.txt +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - - - - - - - - diff --git a/bundles/org.scribble.protocol.export.monitor/src/test/resources/monitor/results/SimpleDirectedChoiceFollowedByInteraction.txt b/bundles/org.scribble.protocol.export.monitor/src/test/resources/monitor/results/SimpleDirectedChoiceFollowedByInteraction.txt deleted file mode 100644 index 2b485caf4..000000000 --- a/bundles/org.scribble.protocol.export.monitor/src/test/resources/monitor/results/SimpleDirectedChoiceFollowedByInteraction.txt +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - - - - - - - - diff --git a/bundles/org.scribble.protocol.export.monitor/src/test/resources/monitor/results/SimpleDirectedChoiceFollowedByNoActivity.txt b/bundles/org.scribble.protocol.export.monitor/src/test/resources/monitor/results/SimpleDirectedChoiceFollowedByNoActivity.txt deleted file mode 100644 index 394e8f7d7..000000000 --- a/bundles/org.scribble.protocol.export.monitor/src/test/resources/monitor/results/SimpleDirectedChoiceFollowedByNoActivity.txt +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - - - - - - diff --git a/bundles/org.scribble.protocol.export.monitor/src/test/resources/monitor/results/SimpleDoInterruptFollowedByInteraction.txt b/bundles/org.scribble.protocol.export.monitor/src/test/resources/monitor/results/SimpleDoInterruptFollowedByInteraction.txt deleted file mode 100644 index 0603e2d71..000000000 --- a/bundles/org.scribble.protocol.export.monitor/src/test/resources/monitor/results/SimpleDoInterruptFollowedByInteraction.txt +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - diff --git a/bundles/org.scribble.protocol.export.monitor/src/test/resources/monitor/results/SimpleDoInterruptMultipleFollowedByInteraction.txt b/bundles/org.scribble.protocol.export.monitor/src/test/resources/monitor/results/SimpleDoInterruptMultipleFollowedByInteraction.txt deleted file mode 100644 index 32e2d0657..000000000 --- a/bundles/org.scribble.protocol.export.monitor/src/test/resources/monitor/results/SimpleDoInterruptMultipleFollowedByInteraction.txt +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - - - - - - diff --git a/bundles/org.scribble.protocol.export.monitor/src/test/resources/monitor/results/SimpleInteraction.txt b/bundles/org.scribble.protocol.export.monitor/src/test/resources/monitor/results/SimpleInteraction.txt deleted file mode 100644 index 478ae6956..000000000 --- a/bundles/org.scribble.protocol.export.monitor/src/test/resources/monitor/results/SimpleInteraction.txt +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/bundles/org.scribble.protocol.export.monitor/src/test/resources/monitor/results/SimpleInteractionWithAnnotation.txt b/bundles/org.scribble.protocol.export.monitor/src/test/resources/monitor/results/SimpleInteractionWithAnnotation.txt deleted file mode 100644 index 737924b64..000000000 --- a/bundles/org.scribble.protocol.export.monitor/src/test/resources/monitor/results/SimpleInteractionWithAnnotation.txt +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/bundles/org.scribble.protocol.export.monitor/src/test/resources/monitor/results/SimpleOptionalFollowedByInteraction.txt b/bundles/org.scribble.protocol.export.monitor/src/test/resources/monitor/results/SimpleOptionalFollowedByInteraction.txt deleted file mode 100644 index d76f46c1b..000000000 --- a/bundles/org.scribble.protocol.export.monitor/src/test/resources/monitor/results/SimpleOptionalFollowedByInteraction.txt +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/bundles/org.scribble.protocol.export.monitor/src/test/resources/monitor/results/SimpleOptionalFollowedByNoActivity.txt b/bundles/org.scribble.protocol.export.monitor/src/test/resources/monitor/results/SimpleOptionalFollowedByNoActivity.txt deleted file mode 100644 index f0b253fac..000000000 --- a/bundles/org.scribble.protocol.export.monitor/src/test/resources/monitor/results/SimpleOptionalFollowedByNoActivity.txt +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/bundles/org.scribble.protocol.export.monitor/src/test/resources/monitor/results/SimpleParallelFollowedByInteraction.txt b/bundles/org.scribble.protocol.export.monitor/src/test/resources/monitor/results/SimpleParallelFollowedByInteraction.txt deleted file mode 100644 index f06256712..000000000 --- a/bundles/org.scribble.protocol.export.monitor/src/test/resources/monitor/results/SimpleParallelFollowedByInteraction.txt +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - diff --git a/bundles/org.scribble.protocol.export.monitor/src/test/resources/monitor/results/SimpleRecursionFollowedByInteraction.txt b/bundles/org.scribble.protocol.export.monitor/src/test/resources/monitor/results/SimpleRecursionFollowedByInteraction.txt deleted file mode 100644 index 409032845..000000000 --- a/bundles/org.scribble.protocol.export.monitor/src/test/resources/monitor/results/SimpleRecursionFollowedByInteraction.txt +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - - - - - - - - - diff --git a/bundles/org.scribble.protocol.export.monitor/src/test/resources/monitor/results/SimpleRecursionWithInnerInteractionFollowedByInteraction.txt b/bundles/org.scribble.protocol.export.monitor/src/test/resources/monitor/results/SimpleRecursionWithInnerInteractionFollowedByInteraction.txt deleted file mode 100644 index 959783700..000000000 --- a/bundles/org.scribble.protocol.export.monitor/src/test/resources/monitor/results/SimpleRecursionWithInnerInteractionFollowedByInteraction.txt +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - - - - - - - - - - - diff --git a/bundles/org.scribble.protocol.export.monitor/src/test/resources/monitor/results/SimpleRepeatFollowedByInteraction.txt b/bundles/org.scribble.protocol.export.monitor/src/test/resources/monitor/results/SimpleRepeatFollowedByInteraction.txt deleted file mode 100644 index b1c97f387..000000000 --- a/bundles/org.scribble.protocol.export.monitor/src/test/resources/monitor/results/SimpleRepeatFollowedByInteraction.txt +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/bundles/org.scribble.protocol.export.monitor/src/test/resources/monitor/results/SimpleRepeatFollowedByNoActivity.txt b/bundles/org.scribble.protocol.export.monitor/src/test/resources/monitor/results/SimpleRepeatFollowedByNoActivity.txt deleted file mode 100644 index a5fd2713e..000000000 --- a/bundles/org.scribble.protocol.export.monitor/src/test/resources/monitor/results/SimpleRepeatFollowedByNoActivity.txt +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/bundles/org.scribble.protocol.export.monitor/src/test/resources/monitor/results/SimpleRunFollowedByInteraction.txt b/bundles/org.scribble.protocol.export.monitor/src/test/resources/monitor/results/SimpleRunFollowedByInteraction.txt deleted file mode 100644 index 89b888c7d..000000000 --- a/bundles/org.scribble.protocol.export.monitor/src/test/resources/monitor/results/SimpleRunFollowedByInteraction.txt +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/bundles/org.scribble.protocol.export.monitor/src/test/resources/monitor/results/SimpleRunFollowedByNoActivity.txt b/bundles/org.scribble.protocol.export.monitor/src/test/resources/monitor/results/SimpleRunFollowedByNoActivity.txt deleted file mode 100644 index f1d7f744c..000000000 --- a/bundles/org.scribble.protocol.export.monitor/src/test/resources/monitor/results/SimpleRunFollowedByNoActivity.txt +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/bundles/org.scribble.protocol.export.monitor/src/test/resources/monitor/results/SimpleRunInlineFollowedByInteraction.txt b/bundles/org.scribble.protocol.export.monitor/src/test/resources/monitor/results/SimpleRunInlineFollowedByInteraction.txt deleted file mode 100644 index e7735d02b..000000000 --- a/bundles/org.scribble.protocol.export.monitor/src/test/resources/monitor/results/SimpleRunInlineFollowedByInteraction.txt +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/bundles/org.scribble.protocol.export.monitor/src/test/resources/monitor/results/SimpleRunInlineFollowedByNoActivity.txt b/bundles/org.scribble.protocol.export.monitor/src/test/resources/monitor/results/SimpleRunInlineFollowedByNoActivity.txt deleted file mode 100644 index f1d7f744c..000000000 --- a/bundles/org.scribble.protocol.export.monitor/src/test/resources/monitor/results/SimpleRunInlineFollowedByNoActivity.txt +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/bundles/org.scribble.protocol.export.monitor/src/test/resources/monitor/results/SimpleUnorderedFollowedByInteraction.txt b/bundles/org.scribble.protocol.export.monitor/src/test/resources/monitor/results/SimpleUnorderedFollowedByInteraction.txt deleted file mode 100644 index f06256712..000000000 --- a/bundles/org.scribble.protocol.export.monitor/src/test/resources/monitor/results/SimpleUnorderedFollowedByInteraction.txt +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - diff --git a/bundles/org.scribble.protocol.monitor/LICENSE.txt b/bundles/org.scribble.protocol.monitor/LICENSE.txt deleted file mode 100644 index 29f81d812..000000000 --- a/bundles/org.scribble.protocol.monitor/LICENSE.txt +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - 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 - - http://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. diff --git a/bundles/org.scribble.protocol.monitor/META-INF/MANIFEST.MF b/bundles/org.scribble.protocol.monitor/META-INF/MANIFEST.MF deleted file mode 100644 index 99c2ad8a6..000000000 --- a/bundles/org.scribble.protocol.monitor/META-INF/MANIFEST.MF +++ /dev/null @@ -1,16 +0,0 @@ -Manifest-Version: 1.0 -Bundle-ManifestVersion: 2 -Bundle-Name: Scribble Protocol Monitor -Bundle-SymbolicName: org.scribble.protocol.monitor;singleton:=true -Bundle-Version: 2.1.0.SNAPSHOT -Bundle-Vendor: www.scribble.org -Import-Package: javax.xml.bind, - javax.xml.namespace, - org.osgi.framework;version="1.3.0" -Export-Package: org.scribble.protocol.monitor, - org.scribble.protocol.monitor.model, - org.scribble.protocol.monitor.util -Bundle-ClassPath: . -Bundle-RequiredExecutionEnvironment: JavaSE-1.6 -Bundle-ActivationPolicy: lazy -Bundle-Activator: org.scribble.protocol.monitor.osgi.Activator diff --git a/bundles/org.scribble.protocol.monitor/build.properties b/bundles/org.scribble.protocol.monitor/build.properties deleted file mode 100644 index f10366651..000000000 --- a/bundles/org.scribble.protocol.monitor/build.properties +++ /dev/null @@ -1,12 +0,0 @@ -source.. = src/main/java/ -output.. = bin/ -bin.includes = META-INF/,\ - .,\ - LICENSE.txt -src.includes = src/,\ - pom.xml,\ - build.properties,\ - META-INF/,\ - .project,\ - .classpath,\ - LICENSE.txt diff --git a/bundles/org.scribble.protocol.monitor/pom.xml b/bundles/org.scribble.protocol.monitor/pom.xml deleted file mode 100644 index 212e979fc..000000000 --- a/bundles/org.scribble.protocol.monitor/pom.xml +++ /dev/null @@ -1,76 +0,0 @@ - - 4.0.0 - org.scribble.bundles - org.scribble.protocol.monitor - jar - 2.1.0-SNAPSHOT - Scribble::Bundles::ProtocolMonitor - - - org.scribble - bundles - 2.1.0-SNAPSHOT - - - - - org.osgi - org.osgi.core - ${osgi.version} - - - junit - junit - test - - - - - - - maven-javadoc-plugin - - - generate-javadoc - package - - jar - - - - - org.jboss.apiviz.APIviz - - org.jboss.apiviz - apiviz - 1.2.4.GA - - true - false - - -d ${project.build.directory}/javadoc - -charset UTF-8 - -docencoding UTF-8 - -version - -author - -breakiterator - -windowtitle "${project.name} ${project.version} API Reference" - -doctitle "${project.name} ${project.version} API Reference" - -bottom "Copyright © ${project.inceptionYear}-Present ${project.organization.name}. All Rights Reserved." - -link http://java.sun.com/javase/6/docs/api/ - -sourceclasspath ${project.build.outputDirectory} - - UTF-8 - en_US - - org.scribble.protocol.monitor - - - *.osgi - - - - - - diff --git a/bundles/org.scribble.protocol.monitor/schema/Monitor.xsd b/bundles/org.scribble.protocol.monitor/schema/Monitor.xsd deleted file mode 100644 index c6ce32f98..000000000 --- a/bundles/org.scribble.protocol.monitor/schema/Monitor.xsd +++ /dev/null @@ -1,148 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/DefaultMessage.java b/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/DefaultMessage.java deleted file mode 100644 index 6d09d23c1..000000000 --- a/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/DefaultMessage.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.monitor; - -/** - * This class provides a default implementation of the message. - * - */ -public class DefaultMessage implements Message { - - private String _operator=null; - private java.util.List _types=new java.util.Vector(); - - /** - * Default constructor. - */ - public DefaultMessage() { - } - - /** - * {@inheritDoc} - */ - public String getOperator() { - return (_operator); - } - - /** - * {@inheritDoc} - */ - public void setOperator(String op) { - _operator = op; - } - - /** - * {@inheritDoc} - */ - public java.util.List getTypes() { - return (_types); - } - - @Override - public String toString() { - StringBuffer ret=new StringBuffer(); - - if (_operator != null && _operator.trim().length() > 0) { - ret.append(_operator); - ret.append('('); - } - - for (int i=0; i < getTypes().size(); i++) { - if (i > 0) { - ret.append(','); - } - ret.append(getTypes().get(i)); - } - - if (_operator != null && _operator.trim().length() > 0) { - ret.append(')'); - } - - return (ret.toString()); - } - - @Override - public int hashCode() { - return (toString().hashCode()); - } - - @Override - public boolean equals(Object obj) { - boolean ret=false; - - if (obj instanceof DefaultMessage) { - DefaultMessage other=(DefaultMessage)obj; - - if ((_operator == null && other._operator == null) - || (_operator != null && other._operator != null - && _operator.equals(other._operator))) { - - // TODO: Need to validate parameter types - // Could also have parameter types as Java types - ret = true; - } - } - - return (ret); - } -} diff --git a/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/DefaultMonitorContext.java b/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/DefaultMonitorContext.java deleted file mode 100644 index df50c377c..000000000 --- a/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/DefaultMonitorContext.java +++ /dev/null @@ -1,152 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.monitor; - -import java.util.logging.Level; -import java.util.logging.Logger; - -import org.scribble.protocol.monitor.model.MessageNode; -import org.scribble.protocol.monitor.model.MessageType; - -/** - * This class provides a default implementation of the monitor context. - * - */ -public class DefaultMonitorContext implements MonitorContext { - - private static final Logger LOG=Logger.getLogger(DefaultMonitorContext.class.getName()); - - /** - * {@inheritDoc} - */ - public Result validate(Session session, MessageNode mesgNode, Message mesg) { - // Do direct comparison for now, but could also check for derived - // types - Result ret=Result.NOT_HANDLED; - - if (mesgNode.getMessageType().size() > 0) { - - if (mesgNode.getMessageType().size() == mesg.getTypes().size()) { - ret = Result.VALID; - - // If message type defined on message node, then compare against it - for (int i=0; i < mesgNode.getMessageType().size(); i++) { - MessageType mt=mesgNode.getMessageType().get(i); - - if (mt.getValue() == null || !mt.getValue().equals(mesg.getTypes().get(i))) { - ret = Result.NOT_HANDLED; - break; - } - } - } else if (LOG.isLoggable(Level.FINEST)) { - LOG.finest("Number of message types different ("+mesgNode.getMessageType().size()+" : " - +mesg.getTypes().size()+")"); - } - } else { - // If not message types, then the operator names must be specified - // and equivalent - if (mesgNode.getOperator() != null - && mesg.getOperator() != null - && mesgNode.getOperator().equals(mesg.getOperator())) { - ret = Result.VALID; - } - } - - // TODO: Could check for match of operator name, in which case indicating - // the message type is mismatched - but issue is the same operator could - // be used with different message types in the model - in which case - // classifying the match as invalid, due to mismatching message type with - // a particular operator, could then prevent the subsequent match against - // another message node with the same operator name and correct message - // type. - - if (LOG.isLoggable(Level.FINEST)) { - LOG.finest("Session ("+session+") validate message '"+mesg+"' against node " - +mesgNode+" ret = "+ret); - } - - return (ret); - } - - /** - * {@inheritDoc} - */ - public Boolean evaluate(Session session, String expression) { - Boolean ret=null; - - ret = evalOR(session, expression); - - return (ret); - } - - protected Boolean evalOR(Session session, String expression) { - Boolean ret=Boolean.FALSE; - - String[] ors=expression.split("or"); - - for (String or : ors) { - Boolean result=evalAND(session, or.trim()); - - if (result == null) { - ret = null; - } else if (result != null && result.booleanValue()) { - ret = Boolean.TRUE; - break; - } - } - - return(ret); - } - - protected Boolean evalAND(Session session, String expression) { - Boolean ret=null; - - String[] ands=expression.split("and"); - - if (ands.length > 0) { - ret = Boolean.TRUE; - - for (String and : ands) { - Object result=session.getState(and.trim()); - - if (result == null) { - ret = null; - break; - } else if (!(result instanceof Boolean)) { - ret = Boolean.FALSE; - break; - } else if (!((Boolean)result).booleanValue()) { - ret = Boolean.FALSE; - break; - } - } - } - - return(ret); - } - - /** - * {@inheritDoc} - */ - public boolean fork(Session session, String linkName, String condition) { - // TODO Implement use of condition - - session.setState(linkName, Boolean.TRUE); - - return true; - } -} diff --git a/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/DefaultProtocolMonitor.java b/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/DefaultProtocolMonitor.java deleted file mode 100644 index 0e36e520a..000000000 --- a/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/DefaultProtocolMonitor.java +++ /dev/null @@ -1,449 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.monitor; - -import java.util.logging.Level; -import java.util.logging.Logger; - -import org.scribble.protocol.monitor.model.Description; -import org.scribble.protocol.monitor.model.Fork; -import org.scribble.protocol.monitor.model.Join; -import org.scribble.protocol.monitor.model.LinkDeclaration; -import org.scribble.protocol.monitor.model.MessageNode; -import org.scribble.protocol.monitor.model.Parallel; -import org.scribble.protocol.monitor.model.Scope; -import org.scribble.protocol.monitor.model.SendMessage; -import org.scribble.protocol.monitor.model.ReceiveMessage; -import org.scribble.protocol.monitor.model.Node; -import org.scribble.protocol.monitor.model.Path; -import org.scribble.protocol.monitor.model.Do; - -// NOTES: -// All top level event processes have the same structure: -// (1) They process all node indexes associated with the context to check for match -// (2) If match not found, then process any nested conversations -// (3) If nested conversation returns match, then check if it is finished, and if so remove from parent context -// Outside scope of monitor, the environment should check that when a match is found, whether the associated -// context is finished, to remove the top level conversation instance monitoring. - -/** - * This class provides a default implementation of the protocol monitor. - * - */ -public class DefaultProtocolMonitor implements ProtocolMonitor { - - private static final Logger LOG=Logger.getLogger(DefaultProtocolMonitor.class.getName()); - - /** - * Default constructor. - */ - public DefaultProtocolMonitor() { - } - - /** - * This method creates a new session (conversation instance) and initializes - * it based on the supplied description. - * - * @param context The monitor context - * @param protocol The protocol description - * @param sessionClass The session implenentation class to instantiate - * @return The created and initialized session - */ - public Session createSession(MonitorContext context, Description protocol, - Class sessionClass) { - Session ret=null; - - try { - ret = sessionClass.newInstance(); - - // Initialize the session with the protocol descriptions - if (protocol.getNode().size() > 0) { - addNodeToConversation(context, protocol, ret, 0); - } - } catch (Exception e) { - LOG.log(Level.SEVERE, "Failed to create and initialize session '" - +sessionClass+"'", e); - } - - return (ret); - } - - /** - * {@inheritDoc} - */ - public Result messageSent(MonitorContext context, Description protocol, - Session session, Message mesg) { - Result ret=Result.NOT_HANDLED; - - if (LOG.isLoggable(Level.FINE)) { - LOG.fine("messageSent start: session="+session+" mesg="+mesg); - } - - if (session == null) { - return(new Result(false, "Cannot monitor message due to no session instance")); - } - - // Check if context has state that is waiting for a send message - for (int i=0; ret == Result.NOT_HANDLED && i < session.getNumberOfNodeIndexes(); i++) { - ret = checkForMessage(context, protocol, - i, session.getNodeIndexAt(i), session, mesg, true); - } - - for (int i=0; ret == Result.NOT_HANDLED && i < session.getNestedConversations().size(); i++) { - Session nested=session.getNestedConversations().get(i); - - ret = messageSent(context, protocol, nested, mesg); - - if (ret .isValid()) { - - // If nested conversation has a 'main' conversation, then check that it - // has been terminated - // TODO: Issue is efficiency of doing this check for each message? - if (nested.getMainConversation() != null) { - Session main=nested.getMainConversation(); - - if (session.getNestedConversations().remove(main)) { - - // Terminate other catch blocks - for (Session cc : main.getInterruptConversations()) { - if (cc != nested) { - session.getNestedConversations().remove(cc); - } - } - } - } - - // If matched, then check if nested conversation has finished - if (nested.isFinished()) { - nestedConversationFinished(context, protocol, session, nested); - } - } - } - - if (LOG.isLoggable(Level.FINE)) { - LOG.fine("messageSent end: session="+session+" mesg="+mesg+" ret="+ret); - } - - return (ret); - } - - /** - * {@inheritDoc} - */ - public Result messageReceived(MonitorContext context, Description protocol, - Session session, Message mesg) { - Result ret=Result.NOT_HANDLED; - - if (session == null) { - return(new Result(false, "Cannot monitor message due to no session instance")); - } - - // Check if context has state that is waiting for a send message - for (int i=0; ret == Result.NOT_HANDLED && i < session.getNumberOfNodeIndexes(); i++) { - ret = checkForMessage(context, protocol, - i, session.getNodeIndexAt(i), session, mesg, false); - } - - for (int i=0; ret == Result.NOT_HANDLED && i < session.getNestedConversations().size(); i++) { - Session nested=session.getNestedConversations().get(i); - - ret = messageReceived(context, protocol, nested, mesg); - - if (ret.isValid()) { - - // If nested conversation has a 'main' conversation, then check that it - // has been terminated - // TODO: Issue is efficiency of doing this check for each message? - if (nested.getMainConversation() != null) { - Session main=nested.getMainConversation(); - - if (session.getNestedConversations().remove(main)) { - - // Terminate other interrupt blocks - for (Session cc : main.getInterruptConversations()) { - if (cc != nested) { - session.getNestedConversations().remove(cc); - } - } - } - } - - // If matched, then check if nested conversation has finished - if (nested.isFinished()) { - nestedConversationFinished(context, protocol, session, nested); - } - } - } - - return (ret); - } - - /** - * This method checks whether the send message is valid. - * - * @param context The monitor context - * @param protocol The protocol - * @param pos The position of the node in the conversation - * @param nodeIndex The nodex index in the protocol - * @param conv The conversation - * @param mesg The message - * @param send Whether this message is being sent - * @return The result - */ - protected Result checkForMessage(MonitorContext context, Description protocol, - int pos, int nodeIndex, Session conv, Message mesg, boolean send) { - Result ret=Result.NOT_HANDLED; - - Node node=protocol.getNode().get(nodeIndex); - - if ((send && node instanceof SendMessage) || - (!send && node instanceof ReceiveMessage)) { - ret = validateMessage(context, conv, (MessageNode)node, mesg); - - if (ret.isValid()) { - // Remove processed node - conv.removeNodeIndexAt(pos); - - // Add next node, if not end - if (node.getNextIndex() != -1) { - addNodeToConversation(context, protocol, conv, node.getNextIndex()); - } - } - - } else if (node instanceof org.scribble.protocol.monitor.model.Choice) { - // Check if lookahead for the indexes associated with each - // choice path - for (int j=0; ret == Result.NOT_HANDLED - && j < ((org.scribble.protocol.monitor.model.Choice)node).getPath().size(); j++) { - - Path cn=((org.scribble.protocol.monitor.model.Choice)node).getPath().get(j); - - if (cn.getNextIndex() != -1) { - ret = checkForMessage(context, protocol, - pos, cn.getNextIndex(), conv, mesg, send); - } - } - - } else if (node instanceof org.scribble.protocol.monitor.model.Decision) { - - if (((org.scribble.protocol.monitor.model.Decision)node).getInnerIndex() != -1) { - ret = checkForMessage(context, protocol, - pos, ((org.scribble.protocol.monitor.model.Decision)node).getInnerIndex(), - conv, mesg, send); - } - - if (ret == Result.NOT_HANDLED && node.getNextIndex() != -1) { - ret = checkForMessage(context, protocol, - pos, node.getNextIndex(), conv, mesg, send); - } - } else if (node instanceof Join) { - Join join=(Join)node; - - Boolean result=context.evaluate(conv, join.getExpression()); - - if (result != null && result.booleanValue()) { - - // Add next node, if not end - if (node.getNextIndex() != -1) { - ret = checkForMessage(context, protocol, - pos, node.getNextIndex(), conv, mesg, send); - - if (!ret.isValid()) { - // Remove node and add subsequent nodes - this makes sure - // the join is not processed again next time - conv.removeNodeIndexAt(pos); - addNodeToConversation(context, protocol, conv, node.getNextIndex()); - } - } else { - // Remove processed node - conv.removeNodeIndexAt(pos); - } - } - } - - if (LOG.isLoggable(Level.FINE)) { - LOG.fine("checkForMessage: pos="+pos+" nodeIndex="+nodeIndex - +" node="+node+" conv="+conv+" mesg="+mesg+" send="+send+" ret="+ret); - } - - return (ret); - } - - /** - * This method validates the message against a message (send/receive) node. - * - * @param context Monitor context - * @param conv Conversation - * @param node The message node - * @param sig The message signature - * @return The result - */ - protected Result validateMessage(MonitorContext context, Session conv, MessageNode node, - Message sig) { - return (context.validate(conv, node, sig)); - } - - /** - * This method adds a node to the conversation. - * - * @param context The context - * @param protocol The protocol - * @param session The conversation - * @param nodeIndex The node index - */ - protected void addNodeToConversation(MonitorContext context, Description protocol, - Session session, int nodeIndex) { - - // Check if specified node is a 'Run' node type - Node node=protocol.getNode().get(nodeIndex); - - if (node.getClass() == Scope.class) { - initScope(context, protocol, session, (Scope)node); - - } else if (node.getClass() == Do.class) { - Session nested=initScope(context, protocol, session, (Do)node); - - // TODO: Need to register catch blocks against the nested context in the - // parent context - for (Path path : ((Do)node).getPath()) { - - Session interruptScope=session.createInterruptConversation(nested, node.getNextIndex()); - interruptScope.addNodeIndex(path.getNextIndex()); - } - - } else if (node.getClass() == org.scribble.protocol.monitor.model.Call.class) { - - if (((org.scribble.protocol.monitor.model.Call)node).getCallIndex() != -1) { - addNodeToConversation(context, protocol, session, - ((org.scribble.protocol.monitor.model.Call)node).getCallIndex()); - } - - if (node.getNextIndex() != -1) { - addNodeToConversation(context, protocol, session, node.getNextIndex()); - } - - } else if (node.getClass() == org.scribble.protocol.monitor.model.Parallel.class) { - - if (node.getNextIndex() != -1) { - Session nestedContext=session.createNestedConversation(node.getNextIndex()); - - Parallel pnode=(Parallel)node; - - // TODO: Check what happens if no activities in the parallel paths? - - for (Path path : pnode.getPath()) { - if (path.getNextIndex() != -1) { - addNodeToConversation(context, protocol, nestedContext, path.getNextIndex()); - } - } - } - } else if (node.getClass() == org.scribble.protocol.monitor.model.LinkDeclaration.class) { - LinkDeclaration linkDecl=(LinkDeclaration)node; - - session.declareLink(linkDecl.getName()); - - if (node.getNextIndex() != -1) { - addNodeToConversation(context, protocol, session, node.getNextIndex()); - } - - } else if (node.getClass() == Fork.class) { - Fork fork=(Fork)node; - - if (context.fork(session, fork.getLinkName(), fork.getCondition())) { - - if (node.getNextIndex() != -1) { - addNodeToConversation(context, protocol, session, node.getNextIndex()); - } - } else { - // Block until the fork condition can be evaluated - session.addNodeIndex(nodeIndex); - } - - } else if (node.getClass() == Join.class) { - Join join=(Join)node; - - Boolean result=context.evaluate(session, join.getExpression()); - - if (result == null) { - // Block until the join expression can be evaluated - session.addNodeIndex(nodeIndex); - - } else if (result.booleanValue() && node.getNextIndex() != -1) { - addNodeToConversation(context, protocol, session, node.getNextIndex()); - } - - } else { - session.addNodeIndex(nodeIndex); - } - } - - /** - * This method initializes the supplied scope within the supplied context. This involves - * creating a nested context, which is subsequently returned. - * - * @param context The context - * @param protocol The protocol description - * @param conv The current context - * @param scope The scope to be initialized - * @return The new nested context, or null if failed - */ - protected Session initScope(MonitorContext context, Description protocol, Session conv, Scope scope) { - Session nestedContext=null; - - // Check if internal or external run - if (scope.getInnerIndex() != -1) { - // Internal - nestedContext = conv.createNestedConversation(scope.getNextIndex()); - - addNodeToConversation(context, protocol, nestedContext, scope.getInnerIndex()); - - } else { - // External - protocol name is in the 'name' field - System.err.println("EXTERNAL PROTOCOL MONITORING NOT CURRENTLY SUPPORTED"); - } - - return (nestedContext); - } - - /** - * This method is called when a nested conversation finishes. - * - * @param context The context - * @param protocol The protocol - * @param conv The conversation - * @param nested The nested conversation - */ - protected void nestedConversationFinished(MonitorContext context, Description protocol, - Session conv, Session nested) { - // Check if nested conversation has a return index - if (nested.getReturnIndex() != -1) { - addNodeToConversation(context, protocol, conv, nested.getReturnIndex()); - } - - // Remove nested conversation from parent context - conv.removeNestedConversation(nested); - - // Cancel dependent contexts - // TODO: Note this implies immediate cancellation of catch blocks. If - // we want to delay until subsequent activity, or explicit control message, - // then will need to change. Issue with subsequent activity is that it - // may not be within the containing context. - for (Session cc : nested.getInterruptConversations()) { - conv.removeNestedConversation(cc); - } - } -} diff --git a/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/DefaultSession.java b/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/DefaultSession.java deleted file mode 100644 index a2e12c7f4..000000000 --- a/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/DefaultSession.java +++ /dev/null @@ -1,360 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.monitor; - -import java.io.IOException; -import java.io.ObjectInput; -import java.io.ObjectOutput; - -/** - * This class represents the default implementation of the conversation - * interface. - * - */ -public class DefaultSession implements Session, java.io.Externalizable { - - /** - * Serialization version. - */ - private static final int VERSION=2; - - private java.util.List _nodeIndexes=new java.util.Vector(); - private int _returnIndex=-1; - private Session _parentConversation=null; - private Session _mainConversation=null; - private java.util.List _nestedConversations=new java.util.Vector(); - private java.util.List _interruptConversations=new java.util.Vector(); - private java.util.Map _state=new java.util.HashMap(); - - /** - * Default constructor. - */ - public DefaultSession() { - } - - /** - * This constructor is initialized with the return index for use when the - * nested session completes. - * - * @param returnIndex The return index - */ - protected DefaultSession(int returnIndex) { - _returnIndex = returnIndex; - } - - /** - * This constructor is initialized with the return index for use when the - * nested session completes. - * - * @param main The main session - * @param returnIndex The return index - */ - protected DefaultSession(Session main, int returnIndex) { - _mainConversation = main; - _returnIndex = returnIndex; - } - - /** - * {@inheritDoc} - */ - public void addNodeIndex(int index) { - _nodeIndexes.add(index); - } - - /** - * {@inheritDoc} - */ - public void removeNodeIndexAt(int pos) { - _nodeIndexes.remove(pos); - } - - /** - * {@inheritDoc} - */ - public int getNumberOfNodeIndexes() { - return (_nodeIndexes.size()); - } - - /** - * {@inheritDoc} - */ - public int getNodeIndexAt(int pos) { - return (_nodeIndexes.get(pos)); - } - - /** - * {@inheritDoc} - */ - public boolean isFinished() { - return (_nodeIndexes.size() == 0 && _nestedConversations.size() == 0); - } - - // Nested Conversation Management - - /** - * {@inheritDoc} - */ - public Session createNestedConversation(int returnIndex) { - DefaultSession ret=new DefaultSession(returnIndex); - - _nestedConversations.add(ret); - - // Establish parent conversation relationship - ret._parentConversation = this; - - return (ret); - } - - /** - * {@inheritDoc} - */ - public Session createInterruptConversation(Session main, int returnIndex) { - DefaultSession ret=new DefaultSession(main, returnIndex); - - _nestedConversations.add(ret); - main.getInterruptConversations().add(ret); - - // Establish parent conversation relationship - ret._parentConversation = this; - - return (ret); - } - - /** - * {@inheritDoc} - */ - public int getReturnIndex() { - return (_returnIndex); - } - - /** - * {@inheritDoc} - */ - public void setReturnIndex(int returnIndex) { - _returnIndex = returnIndex; - } - - /** - * {@inheritDoc} - */ - public java.util.List getNestedConversations() { - return (_nestedConversations); - } - - /** - * {@inheritDoc} - */ - public void removeNestedConversation(Session session) { - _nestedConversations.remove(session); - } - - /** - * {@inheritDoc} - */ - public Session getParentConversation() { - return (_parentConversation); - } - - /** - * {@inheritDoc} - */ - public Session getMainConversation() { - return (_mainConversation); - } - - /** - * {@inheritDoc} - */ - public java.util.List getInterruptConversations() { - return (_interruptConversations); - } - - /** - * {@inheritDoc} - */ - public void declareLink(String linkName) { - // Create a placeholder within the current session - setStateValue(linkName, null); - } - - /** - * This method returns the session that declares the named state. - * - * @param name The name - * @return The session, or null if the state is not declared in - * the scope of this session or its parents - */ - protected DefaultSession getDeclaredSession(String name) { - if (_state.containsKey(name)) { - return (this); - } else if (getParentConversation() instanceof DefaultSession) { - return (((DefaultSession)getParentConversation()).getDeclaredSession(name)); - } - - return (null); - } - - /** - * {@inheritDoc} - */ - public Object getState(String name) { - DefaultSession sess=getDeclaredSession(name); - - if (sess != null) { - return (sess.getStateValue(name)); - } - - return (null); - } - - /** - * This method returns the value associated with - * the supplied state name. - * - * @param name The name - * @return The value - */ - protected Object getStateValue(String name) { - return (_state.get(name)); - } - - /** - * This method sets the value associated with - * the supplied state name. - * - * @param name The name - * @param value The value - */ - protected void setStateValue(String name, Object value) { - _state.put(name, (java.io.Serializable)value); - } - - /** - * {@inheritDoc} - */ - public void setState(String name, Object value) { - DefaultSession sess=getDeclaredSession(name); - - if (sess == null) { - sess = this; - } - - sess.setStateValue(name, value); - } - - /** - * This method returns a map defining the current state snapshot - * associated with the session. It is readonly, and therefore - * modifications to the map will not be applied to the session. - * - * @return The state - */ - public java.util.Map getState() { - java.util.Map ret=new java.util.HashMap(); - - applyState(ret); - - return (ret); - } - - /** - * This method applies the session state to the supplied map. - * - * @param state The aggregated session state - */ - protected void applyState(java.util.Map state) { - // Apply parent state first, so child can overwrite if appropriate - - if (_parentConversation instanceof DefaultSession) { - ((DefaultSession)_parentConversation).applyState(state); - } - - state.putAll(_state); - } - - /** - * {@inheritDoc} - */ - public void readExternal(ObjectInput ois) throws IOException, - ClassNotFoundException { - int version=ois.readInt(); - - int nodeIndexes=ois.readInt(); - for (int i=0; i < nodeIndexes; i++) { - _nodeIndexes.add(ois.readInt()); - } - - _returnIndex = ois.readInt(); - - _mainConversation=(Session)ois.readObject(); - - int nestedSize=ois.readInt(); - for (int i=0; i < nestedSize; i++) { - _nestedConversations.add((Session)ois.readObject()); - } - - int interruptSize=ois.readInt(); - for (int i=0; i < interruptSize; i++) { - _interruptConversations.add((Session)ois.readObject()); - } - - if (version > 1) { - _parentConversation=(Session)ois.readObject(); - - int stateSize=ois.readInt(); - for (int i=0; i < stateSize; i++) { - String key=ois.readUTF(); - _state.put(key, ois.readObject()); - } - -} - } - - /** - * {@inheritDoc} - */ - public void writeExternal(ObjectOutput oos) throws IOException { - oos.writeInt(VERSION); - - oos.writeInt(_nodeIndexes.size()); - for (int index : _nodeIndexes) { - oos.writeInt(index); - } - - oos.writeInt(_returnIndex); - - oos.writeObject(_mainConversation); - - oos.writeInt(_nestedConversations.size()); - for (Session session : _nestedConversations) { - oos.writeObject(session); - } - - oos.writeInt(_interruptConversations.size()); - for (Session session : _interruptConversations) { - oos.writeObject(session); - } - - oos.writeObject(_parentConversation); - - oos.writeInt(_state.size()); - for (String key : _state.keySet()) { - oos.writeUTF(key); - oos.writeObject(_state.get(key)); - } - } -} diff --git a/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/Message.java b/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/Message.java deleted file mode 100644 index 2772131c2..000000000 --- a/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/Message.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.monitor; - -/** - * This interface represents a message to be monitored. - * - */ -public interface Message { - - /** - * This method returns the optional operator name. - * - * @return The operator, or null if not relevant - */ - public String getOperator(); - - /** - * This method returns the list of types associated with - * with the message. - * - * @return The types of the message parameters - */ - public java.util.List getTypes(); - -} diff --git a/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/MonitorContext.java b/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/MonitorContext.java deleted file mode 100644 index 713b123c1..000000000 --- a/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/MonitorContext.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.monitor; - -import org.scribble.protocol.monitor.model.MessageNode; - -/** - * This interface provides access to capabilities offered by - * the monitor. - * - */ -public interface MonitorContext { - - /** - * This method determines whether the supplied message is valid - * in respect of the supplied message node. - * - * If the message is not relevant, then a Result.NOT_HANDLED - * should be returned. Otherwise Result.VALID, Result.INVALID - * or a specific instance of Result should be returned to provide - * the relevant information from the monitoring environment's - * validation. - * - * @param session The session - * @param mesgNode The message node - * @param mesg The message to be validated - * @return The result - */ - public Result validate(Session session, MessageNode mesgNode, Message mesg); - - /** - * This method evaluates the supplied expression against the session. - * - * @param session The session - * @param expression The expression - * @return The result of the expression, or null if could not be evaluated - * at this time - */ - public Boolean evaluate(Session session, String expression); - - /** - * This method determines whether the fork, identified by the linkName - * and optional condition, should occur. - * - * @param session The session - * @param linkName The link name - * @param condition The optional condition - * @return Whether the fork has succeeded, or should block - */ - public boolean fork(Session session, String linkName, String condition); - -} diff --git a/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/ProtocolMonitor.java b/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/ProtocolMonitor.java deleted file mode 100644 index 94fb8d9ca..000000000 --- a/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/ProtocolMonitor.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.monitor; - -import org.scribble.protocol.monitor.model.Description; - -/** - * This is the interface for the Protocol Monitor. - * - */ -public interface ProtocolMonitor { - - /** - * This method creates a new session (conversation instance) and initializes - * it based on the supplied description. - * - * @param context The monitor context - * @param protocol The protocol description - * @param sessionClass The session implenentation class to instantiate - * @return The created and initialized session - */ - public Session createSession(MonitorContext context, Description protocol, - Class sessionClass); - - /** - * This method checks whether the conversation instance, managed by - * the supplied context, can handle the supplied 'sent' message. - * - * @param context The monitor context - * @param protocol The protocol description - * @param conv The conversation - * @param mesg The 'sent' message - * @return The result - */ - public Result messageSent(MonitorContext context, Description protocol, - Session conv, Message mesg); - - /** - * This method checks whether the conversation instance, managed by - * the supplied context, can handle the supplied 'received' message. - * - * @param context The monitor context - * @param protocol The protocol description - * @param conv The conversation - * @param mesg The 'received' message - * @return The result - */ - public Result messageReceived(MonitorContext context, Description protocol, - Session conv, Message mesg); - -} diff --git a/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/ProtocolMonitorFactory.java b/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/ProtocolMonitorFactory.java deleted file mode 100644 index 0b1194584..000000000 --- a/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/ProtocolMonitorFactory.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.monitor; - -/** - * This class provides a factory for creating protocol monitors. - * - */ -public final class ProtocolMonitorFactory { - - /** - * Private constructor. - */ - private ProtocolMonitorFactory() { - } - - /** - * This method returns an instance of the protocol monitor. - * - * @return The protocol monitor - */ - public static ProtocolMonitor createProtocolMonitor() { - return (new DefaultProtocolMonitor()); - } -} diff --git a/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/Result.java b/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/Result.java deleted file mode 100644 index 59dafa4ad..000000000 --- a/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/Result.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Copyright 2009-11 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.monitor; - -/** - * This class represents the result from monitoring an event against a - * behavioural description. - * - */ -public class Result implements java.io.Serializable { - - private static final long serialVersionUID = 8094872271195676976L; - - private boolean _valid=false; - private String _reason=null; - private java.util.Map _properties= - new java.util.HashMap(); - - /** - * Valid result. - */ - public static final Result VALID = new Result(true); - - /** - * Message was not handled. - */ - public static final Result NOT_HANDLED = new Result(false); - - /** - * Invalid result. - */ - public static final Result INVALID = new Result(false); - - /** - * Constructor specify whether result is valid. - * - * @param valid Whether result is valid - */ - public Result(boolean valid) { - _valid = valid; - } - - /** - * Constructor to specify whether the result is valid, and a reason. - * - * @param valid Whether the result is valid - * @param reason The reason for the result - */ - public Result(boolean valid, String reason) { - this(valid); - _reason = reason; - } - - /** - * This method determines whether the result is valid. - * - * @return Whether the result is valid - */ - public boolean isValid() { - return (_valid); - } - - /** - * This method returns the reason for the result. - * - * @return The reason, or null if not specified - */ - public String getReason() { - return (_reason); - } - - /** - * This method returns the properties. - * - * @return The properties - */ - public java.util.Map getProperties() { - return (_properties); - } - - /** - * {@inheritDoc} - */ - public String toString() { - return (this == VALID ? "VALID" : (this == NOT_HANDLED ? "NOT_HANDLED" - : (this == INVALID ? "INVALID" : "RESULT["+isValid()+" reason="+getReason() - +" props="+getProperties()+"]"))); - } -} diff --git a/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/Session.java b/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/Session.java deleted file mode 100644 index d5926efeb..000000000 --- a/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/Session.java +++ /dev/null @@ -1,148 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.monitor; - -/** - * This interface represents a session being monitored, which relates - * to a protocol evaluating events that belong to a conversation - * instance. - * - */ -public interface Session { - - /** - * This method adds a node index to the session. - * - * @param index The index - */ - public void addNodeIndex(int index); - - /** - * This method removes a node index to the session. - * - * @param index The index - */ - public void removeNodeIndexAt(int index); - - /** - * This method returns the number of node indexes associated - * with the session. - * - * @return The number of node indexes - */ - public int getNumberOfNodeIndexes(); - - /** - * This method returns the node index at the specified position. - * - * @param pos The position - * @return The node index, or -1 if not found - */ - public int getNodeIndexAt(int pos); - - /** - * This method indicates whether the session has finished. - * - * @return Whether the session has finished - */ - public boolean isFinished(); - - /** - * This method creates a nested conversation that should return - * to the supplied index when it completes. - * - * @param returnIndex The return index - * @return The nested session - */ - public Session createNestedConversation(int returnIndex); - - /** - * This method creates a nested conversation, associated with an - * interrupt scope, that should return to the supplied index - * when it completes. - * - * @param main The main session - * @param returnIndex The return index - * @return The session - */ - public Session createInterruptConversation(Session main, int returnIndex); - - /** - * This method retrieves the 'return' index associated with a - * nested session. - * - * @return The return index, or -1 if not set - */ - public int getReturnIndex(); - - /** - * This method returns the list of nested conversations. - * - * @return The list of nested conversations - */ - public java.util.List getNestedConversations(); - - /** - * This method returns the parent conversation. - * - * @return The parent conversation - */ - public Session getMainConversation(); - - /** - * This method returns the list of interrupt conversations. - * - * @return The interrupt conversations - */ - public java.util.List getInterruptConversations(); - - /** - * This method removes the nested session. - * - * @param session The session to be removed - */ - public void removeNestedConversation(Session session); - - /** - * This method declares a link that will be used for a 'join' - * within the current scope associated with this session. - * The status of the join link can be obtained as a boolean value - * associated with the state for the session. - * - * @param linkName The link name - */ - public void declareLink(String linkName); - - /** - * This method returns the value associated with supplied name. - * If a value has not yet been assigned to the named state, then - * a null will be returned. - * - * @param name The name - * @return The value, or null if not yet initialized - */ - public Object getState(String name); - - /** - * This method sets the state value for the supplied name. - * - * @param name The name - * @param value The value - */ - public void setState(String name, Object value); - -} diff --git a/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/model/Annotation.java b/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/model/Annotation.java deleted file mode 100644 index 734a53da3..000000000 --- a/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/model/Annotation.java +++ /dev/null @@ -1,101 +0,0 @@ -// -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2012.02.06 at 05:22:54 PM GMT -// - - -package org.scribble.protocol.monitor.model; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlID; -import javax.xml.bind.annotation.XmlSchemaType; -import javax.xml.bind.annotation.XmlType; -import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; -import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; - - -/** - *

Java class for Annotation complex type. - * - *

The following schema fragment specifies the expected content contained within this class. - * - *

- * <complexType name="Annotation">
- *   <complexContent>
- *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- *       <sequence>
- *       </sequence>
- *       <attribute name="id" type="{http://www.w3.org/2001/XMLSchema}ID" />
- *       <attribute name="value" type="{http://www.w3.org/2001/XMLSchema}string" />
- *     </restriction>
- *   </complexContent>
- * </complexType>
- * 
- * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "Annotation") -public class Annotation { - - @XmlAttribute - @XmlJavaTypeAdapter(CollapsedStringAdapter.class) - @XmlID - @XmlSchemaType(name = "ID") - protected String id; - @XmlAttribute - protected String value; - - /** - * Gets the value of the id property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getId() { - return id; - } - - /** - * Sets the value of the id property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setId(String value) { - this.id = value; - } - - /** - * Gets the value of the value property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getValue() { - return value; - } - - /** - * Sets the value of the value property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setValue(String value) { - this.value = value; - } - -} diff --git a/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/model/Call.java b/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/model/Call.java deleted file mode 100644 index b23264aec..000000000 --- a/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/model/Call.java +++ /dev/null @@ -1,71 +0,0 @@ -// -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2012.02.06 at 05:22:54 PM GMT -// - - -package org.scribble.protocol.monitor.model; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlType; - - -/** - *

Java class for Call complex type. - * - *

The following schema fragment specifies the expected content contained within this class. - * - *

- * <complexType name="Call">
- *   <complexContent>
- *     <extension base="{http://www.scribble.org/monitor}Node">
- *       <attribute name="callIndex" type="{http://www.w3.org/2001/XMLSchema}int" default="-1" />
- *     </extension>
- *   </complexContent>
- * </complexType>
- * 
- * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "Call") -public class Call - extends Node -{ - - @XmlAttribute - protected Integer callIndex; - - /** - * Gets the value of the callIndex property. - * - * @return - * possible object is - * {@link Integer } - * - */ - public int getCallIndex() { - if (callIndex == null) { - return -1; - } else { - return callIndex; - } - } - - /** - * Sets the value of the callIndex property. - * - * @param value - * allowed object is - * {@link Integer } - * - */ - public void setCallIndex(Integer value) { - this.callIndex = value; - } - -} diff --git a/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/model/Choice.java b/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/model/Choice.java deleted file mode 100644 index eb3d7b6e3..000000000 --- a/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/model/Choice.java +++ /dev/null @@ -1,78 +0,0 @@ -// -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2012.02.06 at 05:22:54 PM GMT -// - - -package org.scribble.protocol.monitor.model; - -import java.util.ArrayList; -import java.util.List; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlType; - - -/** - *

Java class for Choice complex type. - * - *

The following schema fragment specifies the expected content contained within this class. - * - *

- * <complexType name="Choice">
- *   <complexContent>
- *     <extension base="{http://www.scribble.org/monitor}Node">
- *       <sequence>
- *         <element name="path" type="{http://www.scribble.org/monitor}Path" maxOccurs="unbounded"/>
- *       </sequence>
- *     </extension>
- *   </complexContent>
- * </complexType>
- * 
- * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "Choice", propOrder = { - "path" -}) -public class Choice - extends Node -{ - - @XmlElement(required = true) - protected List path; - - /** - * Gets the value of the path property. - * - *

- * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the path property. - * - *

- * For example, to add a new item, do as follows: - *

-     *    getPath().add(newItem);
-     * 
- * - * - *

- * Objects of the following type(s) are allowed in the list - * {@link Path } - * - * - */ - public List getPath() { - if (path == null) { - path = new ArrayList(); - } - return this.path; - } - -} diff --git a/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/model/Decision.java b/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/model/Decision.java deleted file mode 100644 index 3d7041ca0..000000000 --- a/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/model/Decision.java +++ /dev/null @@ -1,71 +0,0 @@ -// -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2012.02.06 at 05:22:54 PM GMT -// - - -package org.scribble.protocol.monitor.model; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlType; - - -/** - *

Java class for Decision complex type. - * - *

The following schema fragment specifies the expected content contained within this class. - * - *

- * <complexType name="Decision">
- *   <complexContent>
- *     <extension base="{http://www.scribble.org/monitor}Node">
- *       <attribute name="innerIndex" type="{http://www.w3.org/2001/XMLSchema}int" default="-1" />
- *     </extension>
- *   </complexContent>
- * </complexType>
- * 
- * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "Decision") -public class Decision - extends Node -{ - - @XmlAttribute - protected Integer innerIndex; - - /** - * Gets the value of the innerIndex property. - * - * @return - * possible object is - * {@link Integer } - * - */ - public int getInnerIndex() { - if (innerIndex == null) { - return -1; - } else { - return innerIndex; - } - } - - /** - * Sets the value of the innerIndex property. - * - * @param value - * allowed object is - * {@link Integer } - * - */ - public void setInnerIndex(Integer value) { - this.innerIndex = value; - } - -} diff --git a/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/model/Description.java b/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/model/Description.java deleted file mode 100644 index 6c0d9a869..000000000 --- a/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/model/Description.java +++ /dev/null @@ -1,74 +0,0 @@ -// -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2012.02.06 at 05:22:54 PM GMT -// - - -package org.scribble.protocol.monitor.model; - -import java.util.ArrayList; -import java.util.List; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlType; - - -/** - *

Java class for Description complex type. - * - *

The following schema fragment specifies the expected content contained within this class. - * - *

- * <complexType name="Description">
- *   <complexContent>
- *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- *       <sequence>
- *         <element name="node" type="{http://www.scribble.org/monitor}Node" maxOccurs="unbounded" minOccurs="0"/>
- *       </sequence>
- *     </restriction>
- *   </complexContent>
- * </complexType>
- * 
- * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "Description", propOrder = { - "node" -}) -public class Description { - - protected List node; - - /** - * Gets the value of the node property. - * - *

- * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the node property. - * - *

- * For example, to add a new item, do as follows: - *

-     *    getNode().add(newItem);
-     * 
- * - * - *

- * Objects of the following type(s) are allowed in the list - * {@link Node } - * - * - */ - public List getNode() { - if (node == null) { - node = new ArrayList(); - } - return this.node; - } - -} diff --git a/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/model/Do.java b/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/model/Do.java deleted file mode 100644 index cbf3742f1..000000000 --- a/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/model/Do.java +++ /dev/null @@ -1,78 +0,0 @@ -// -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2012.02.06 at 05:22:54 PM GMT -// - - -package org.scribble.protocol.monitor.model; - -import java.util.ArrayList; -import java.util.List; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlType; - - -/** - *

Java class for Do complex type. - * - *

The following schema fragment specifies the expected content contained within this class. - * - *

- * <complexType name="Do">
- *   <complexContent>
- *     <extension base="{http://www.scribble.org/monitor}Scope">
- *       <sequence>
- *         <element name="path" type="{http://www.scribble.org/monitor}Path" maxOccurs="unbounded"/>
- *       </sequence>
- *     </extension>
- *   </complexContent>
- * </complexType>
- * 
- * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "Do", propOrder = { - "path" -}) -public class Do - extends Scope -{ - - @XmlElement(required = true) - protected List path; - - /** - * Gets the value of the path property. - * - *

- * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the path property. - * - *

- * For example, to add a new item, do as follows: - *

-     *    getPath().add(newItem);
-     * 
- * - * - *

- * Objects of the following type(s) are allowed in the list - * {@link Path } - * - * - */ - public List getPath() { - if (path == null) { - path = new ArrayList(); - } - return this.path; - } - -} diff --git a/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/model/Fork.java b/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/model/Fork.java deleted file mode 100644 index 26b85b375..000000000 --- a/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/model/Fork.java +++ /dev/null @@ -1,94 +0,0 @@ -// -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2012.02.06 at 05:22:54 PM GMT -// - - -package org.scribble.protocol.monitor.model; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlType; - - -/** - *

Java class for Fork complex type. - * - *

The following schema fragment specifies the expected content contained within this class. - * - *

- * <complexType name="Fork">
- *   <complexContent>
- *     <extension base="{http://www.scribble.org/monitor}Node">
- *       <attribute name="condition" type="{http://www.w3.org/2001/XMLSchema}string" />
- *       <attribute name="linkName" type="{http://www.w3.org/2001/XMLSchema}string" />
- *     </extension>
- *   </complexContent>
- * </complexType>
- * 
- * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "Fork") -public class Fork - extends Node -{ - - @XmlAttribute - protected String condition; - @XmlAttribute - protected String linkName; - - /** - * Gets the value of the condition property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getCondition() { - return condition; - } - - /** - * Sets the value of the condition property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setCondition(String value) { - this.condition = value; - } - - /** - * Gets the value of the linkName property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getLinkName() { - return linkName; - } - - /** - * Sets the value of the linkName property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setLinkName(String value) { - this.linkName = value; - } - -} diff --git a/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/model/Join.java b/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/model/Join.java deleted file mode 100644 index 865843567..000000000 --- a/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/model/Join.java +++ /dev/null @@ -1,67 +0,0 @@ -// -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2012.02.06 at 05:22:54 PM GMT -// - - -package org.scribble.protocol.monitor.model; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlType; - - -/** - *

Java class for Join complex type. - * - *

The following schema fragment specifies the expected content contained within this class. - * - *

- * <complexType name="Join">
- *   <complexContent>
- *     <extension base="{http://www.scribble.org/monitor}Node">
- *       <attribute name="expression" type="{http://www.w3.org/2001/XMLSchema}string" />
- *     </extension>
- *   </complexContent>
- * </complexType>
- * 
- * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "Join") -public class Join - extends Node -{ - - @XmlAttribute - protected String expression; - - /** - * Gets the value of the expression property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getExpression() { - return expression; - } - - /** - * Sets the value of the expression property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setExpression(String value) { - this.expression = value; - } - -} diff --git a/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/model/LinkDeclaration.java b/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/model/LinkDeclaration.java deleted file mode 100644 index e6074d6cc..000000000 --- a/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/model/LinkDeclaration.java +++ /dev/null @@ -1,67 +0,0 @@ -// -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2012.02.06 at 05:22:54 PM GMT -// - - -package org.scribble.protocol.monitor.model; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlType; - - -/** - *

Java class for LinkDeclaration complex type. - * - *

The following schema fragment specifies the expected content contained within this class. - * - *

- * <complexType name="LinkDeclaration">
- *   <complexContent>
- *     <extension base="{http://www.scribble.org/monitor}Node">
- *       <attribute name="name" type="{http://www.w3.org/2001/XMLSchema}string" />
- *     </extension>
- *   </complexContent>
- * </complexType>
- * 
- * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "LinkDeclaration") -public class LinkDeclaration - extends Node -{ - - @XmlAttribute - protected String name; - - /** - * Gets the value of the name property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getName() { - return name; - } - - /** - * Sets the value of the name property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setName(String value) { - this.name = value; - } - -} diff --git a/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/model/MessageNode.java b/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/model/MessageNode.java deleted file mode 100644 index 0ab118801..000000000 --- a/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/model/MessageNode.java +++ /dev/null @@ -1,109 +0,0 @@ -// -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2012.02.06 at 05:22:54 PM GMT -// - - -package org.scribble.protocol.monitor.model; - -import java.util.ArrayList; -import java.util.List; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlSeeAlso; -import javax.xml.bind.annotation.XmlType; - - -/** - *

Java class for MessageNode complex type. - * - *

The following schema fragment specifies the expected content contained within this class. - * - *

- * <complexType name="MessageNode">
- *   <complexContent>
- *     <extension base="{http://www.scribble.org/monitor}Node">
- *       <sequence>
- *         <element name="messageType" type="{http://www.scribble.org/monitor}MessageType" maxOccurs="unbounded" minOccurs="0"/>
- *       </sequence>
- *       <attribute name="operator" type="{http://www.w3.org/2001/XMLSchema}string" />
- *     </extension>
- *   </complexContent>
- * </complexType>
- * 
- * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "MessageNode", propOrder = { - "messageType" -}) -@XmlSeeAlso({ - SendMessage.class, - ReceiveMessage.class -}) -public class MessageNode - extends Node -{ - - protected List messageType; - @XmlAttribute - protected String operator; - - /** - * Gets the value of the messageType property. - * - *

- * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the messageType property. - * - *

- * For example, to add a new item, do as follows: - *

-     *    getMessageType().add(newItem);
-     * 
- * - * - *

- * Objects of the following type(s) are allowed in the list - * {@link MessageType } - * - * - */ - public List getMessageType() { - if (messageType == null) { - messageType = new ArrayList(); - } - return this.messageType; - } - - /** - * Gets the value of the operator property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getOperator() { - return operator; - } - - /** - * Sets the value of the operator property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setOperator(String value) { - this.operator = value; - } - -} diff --git a/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/model/MessageType.java b/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/model/MessageType.java deleted file mode 100644 index abf300faf..000000000 --- a/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/model/MessageType.java +++ /dev/null @@ -1,92 +0,0 @@ -// -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2012.02.06 at 05:22:54 PM GMT -// - - -package org.scribble.protocol.monitor.model; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlType; - - -/** - *

Java class for MessageType complex type. - * - *

The following schema fragment specifies the expected content contained within this class. - * - *

- * <complexType name="MessageType">
- *   <complexContent>
- *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- *       <attribute name="format" type="{http://www.w3.org/2001/XMLSchema}string" />
- *       <attribute name="value" type="{http://www.w3.org/2001/XMLSchema}string" />
- *     </restriction>
- *   </complexContent>
- * </complexType>
- * 
- * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "MessageType") -public class MessageType { - - @XmlAttribute - protected String format; - @XmlAttribute - protected String value; - - /** - * Gets the value of the format property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getFormat() { - return format; - } - - /** - * Sets the value of the format property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setFormat(String value) { - this.format = value; - } - - /** - * Gets the value of the value property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getValue() { - return value; - } - - /** - * Sets the value of the value property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setValue(String value) { - this.value = value; - } - -} diff --git a/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/model/Node.java b/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/model/Node.java deleted file mode 100644 index 7311c3792..000000000 --- a/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/model/Node.java +++ /dev/null @@ -1,118 +0,0 @@ -// -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2012.02.06 at 05:22:54 PM GMT -// - - -package org.scribble.protocol.monitor.model; - -import java.util.ArrayList; -import java.util.List; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlSeeAlso; -import javax.xml.bind.annotation.XmlType; - - -/** - *

Java class for Node complex type. - * - *

The following schema fragment specifies the expected content contained within this class. - * - *

- * <complexType name="Node">
- *   <complexContent>
- *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- *       <sequence>
- *         <element name="annotation" type="{http://www.scribble.org/monitor}Annotation" maxOccurs="unbounded" minOccurs="0"/>
- *       </sequence>
- *       <attribute name="nextIndex" type="{http://www.w3.org/2001/XMLSchema}int" default="-1" />
- *     </restriction>
- *   </complexContent>
- * </complexType>
- * 
- * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "Node", propOrder = { - "annotation" -}) -@XmlSeeAlso({ - LinkDeclaration.class, - Call.class, - Parallel.class, - Join.class, - MessageNode.class, - Fork.class, - Choice.class, - Decision.class, - Scope.class -}) -public class Node { - - protected List annotation; - @XmlAttribute - protected Integer nextIndex; - - /** - * Gets the value of the annotation property. - * - *

- * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the annotation property. - * - *

- * For example, to add a new item, do as follows: - *

-     *    getAnnotation().add(newItem);
-     * 
- * - * - *

- * Objects of the following type(s) are allowed in the list - * {@link Annotation } - * - * - */ - public List getAnnotation() { - if (annotation == null) { - annotation = new ArrayList(); - } - return this.annotation; - } - - /** - * Gets the value of the nextIndex property. - * - * @return - * possible object is - * {@link Integer } - * - */ - public int getNextIndex() { - if (nextIndex == null) { - return -1; - } else { - return nextIndex; - } - } - - /** - * Sets the value of the nextIndex property. - * - * @param value - * allowed object is - * {@link Integer } - * - */ - public void setNextIndex(Integer value) { - this.nextIndex = value; - } - -} diff --git a/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/model/ObjectFactory.java b/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/model/ObjectFactory.java deleted file mode 100644 index 26bfaad13..000000000 --- a/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/model/ObjectFactory.java +++ /dev/null @@ -1,188 +0,0 @@ -// -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2012.02.06 at 05:22:54 PM GMT -// - - -package org.scribble.protocol.monitor.model; - -import javax.xml.bind.JAXBElement; -import javax.xml.bind.annotation.XmlElementDecl; -import javax.xml.bind.annotation.XmlRegistry; -import javax.xml.namespace.QName; - - -/** - * This object contains factory methods for each - * Java content interface and Java element interface - * generated in the org.scribble.protocol.monitor.model package. - *

An ObjectFactory allows you to programatically - * construct new instances of the Java representation - * for XML content. The Java representation of XML - * content can consist of schema derived interfaces - * and classes representing the binding of schema - * type definitions, element declarations and model - * groups. Factory methods for each of these are - * provided in this class. - * - */ -@XmlRegistry -public class ObjectFactory { - - private final static QName _Description_QNAME = new QName("http://www.scribble.org/monitor", "description"); - - /** - * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: org.scribble.protocol.monitor.model - * - */ - public ObjectFactory() { - } - - /** - * Create an instance of {@link MessageType } - * - */ - public MessageType createMessageType() { - return new MessageType(); - } - - /** - * Create an instance of {@link SendMessage } - * - */ - public SendMessage createSendMessage() { - return new SendMessage(); - } - - /** - * Create an instance of {@link Description } - * - */ - public Description createDescription() { - return new Description(); - } - - /** - * Create an instance of {@link Fork } - * - */ - public Fork createFork() { - return new Fork(); - } - - /** - * Create an instance of {@link LinkDeclaration } - * - */ - public LinkDeclaration createLinkDeclaration() { - return new LinkDeclaration(); - } - - /** - * Create an instance of {@link Choice } - * - */ - public Choice createChoice() { - return new Choice(); - } - - /** - * Create an instance of {@link Do } - * - */ - public Do createDo() { - return new Do(); - } - - /** - * Create an instance of {@link MessageNode } - * - */ - public MessageNode createMessageNode() { - return new MessageNode(); - } - - /** - * Create an instance of {@link Join } - * - */ - public Join createJoin() { - return new Join(); - } - - /** - * Create an instance of {@link Parallel } - * - */ - public Parallel createParallel() { - return new Parallel(); - } - - /** - * Create an instance of {@link Annotation } - * - */ - public Annotation createAnnotation() { - return new Annotation(); - } - - /** - * Create an instance of {@link Call } - * - */ - public Call createCall() { - return new Call(); - } - - /** - * Create an instance of {@link Scope } - * - */ - public Scope createScope() { - return new Scope(); - } - - /** - * Create an instance of {@link Node } - * - */ - public Node createNode() { - return new Node(); - } - - /** - * Create an instance of {@link Decision } - * - */ - public Decision createDecision() { - return new Decision(); - } - - /** - * Create an instance of {@link ReceiveMessage } - * - */ - public ReceiveMessage createReceiveMessage() { - return new ReceiveMessage(); - } - - /** - * Create an instance of {@link Path } - * - */ - public Path createPath() { - return new Path(); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link Description }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://www.scribble.org/monitor", name = "description") - public JAXBElement createDescription(Description value) { - return new JAXBElement(_Description_QNAME, Description.class, null, value); - } - -} diff --git a/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/model/Parallel.java b/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/model/Parallel.java deleted file mode 100644 index 292d7027e..000000000 --- a/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/model/Parallel.java +++ /dev/null @@ -1,78 +0,0 @@ -// -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2012.02.06 at 05:22:54 PM GMT -// - - -package org.scribble.protocol.monitor.model; - -import java.util.ArrayList; -import java.util.List; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlType; - - -/** - *

Java class for Parallel complex type. - * - *

The following schema fragment specifies the expected content contained within this class. - * - *

- * <complexType name="Parallel">
- *   <complexContent>
- *     <extension base="{http://www.scribble.org/monitor}Node">
- *       <sequence>
- *         <element name="path" type="{http://www.scribble.org/monitor}Path" maxOccurs="unbounded"/>
- *       </sequence>
- *     </extension>
- *   </complexContent>
- * </complexType>
- * 
- * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "Parallel", propOrder = { - "path" -}) -public class Parallel - extends Node -{ - - @XmlElement(required = true) - protected List path; - - /** - * Gets the value of the path property. - * - *

- * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the path property. - * - *

- * For example, to add a new item, do as follows: - *

-     *    getPath().add(newItem);
-     * 
- * - * - *

- * Objects of the following type(s) are allowed in the list - * {@link Path } - * - * - */ - public List getPath() { - if (path == null) { - path = new ArrayList(); - } - return this.path; - } - -} diff --git a/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/model/Path.java b/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/model/Path.java deleted file mode 100644 index 6dd75551b..000000000 --- a/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/model/Path.java +++ /dev/null @@ -1,106 +0,0 @@ -// -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2012.02.06 at 05:22:54 PM GMT -// - - -package org.scribble.protocol.monitor.model; - -import java.util.ArrayList; -import java.util.List; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlType; - - -/** - *

Java class for Path complex type. - * - *

The following schema fragment specifies the expected content contained within this class. - * - *

- * <complexType name="Path">
- *   <complexContent>
- *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- *       <sequence>
- *         <element name="annotation" type="{http://www.scribble.org/monitor}Annotation" maxOccurs="unbounded" minOccurs="0"/>
- *       </sequence>
- *       <attribute name="nextIndex" type="{http://www.w3.org/2001/XMLSchema}int" default="-1" />
- *     </restriction>
- *   </complexContent>
- * </complexType>
- * 
- * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "Path", propOrder = { - "annotation" -}) -public class Path { - - protected List annotation; - @XmlAttribute - protected Integer nextIndex; - - /** - * Gets the value of the annotation property. - * - *

- * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the annotation property. - * - *

- * For example, to add a new item, do as follows: - *

-     *    getAnnotation().add(newItem);
-     * 
- * - * - *

- * Objects of the following type(s) are allowed in the list - * {@link Annotation } - * - * - */ - public List getAnnotation() { - if (annotation == null) { - annotation = new ArrayList(); - } - return this.annotation; - } - - /** - * Gets the value of the nextIndex property. - * - * @return - * possible object is - * {@link Integer } - * - */ - public int getNextIndex() { - if (nextIndex == null) { - return -1; - } else { - return nextIndex; - } - } - - /** - * Sets the value of the nextIndex property. - * - * @param value - * allowed object is - * {@link Integer } - * - */ - public void setNextIndex(Integer value) { - this.nextIndex = value; - } - -} diff --git a/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/model/ReceiveMessage.java b/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/model/ReceiveMessage.java deleted file mode 100644 index ee72508ec..000000000 --- a/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/model/ReceiveMessage.java +++ /dev/null @@ -1,39 +0,0 @@ -// -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2012.02.06 at 05:22:54 PM GMT -// - - -package org.scribble.protocol.monitor.model; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlType; - - -/** - *

Java class for ReceiveMessage complex type. - * - *

The following schema fragment specifies the expected content contained within this class. - * - *

- * <complexType name="ReceiveMessage">
- *   <complexContent>
- *     <extension base="{http://www.scribble.org/monitor}MessageNode">
- *     </extension>
- *   </complexContent>
- * </complexType>
- * 
- * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "ReceiveMessage") -public class ReceiveMessage - extends MessageNode -{ - - -} diff --git a/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/model/Scope.java b/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/model/Scope.java deleted file mode 100644 index df8e5fbd8..000000000 --- a/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/model/Scope.java +++ /dev/null @@ -1,102 +0,0 @@ -// -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2012.02.06 at 05:22:54 PM GMT -// - - -package org.scribble.protocol.monitor.model; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlSeeAlso; -import javax.xml.bind.annotation.XmlType; - - -/** - *

Java class for Scope complex type. - * - *

The following schema fragment specifies the expected content contained within this class. - * - *

- * <complexType name="Scope">
- *   <complexContent>
- *     <extension base="{http://www.scribble.org/monitor}Node">
- *       <attribute name="name" type="{http://www.w3.org/2001/XMLSchema}string" />
- *       <attribute name="innerIndex" type="{http://www.w3.org/2001/XMLSchema}int" default="-1" />
- *     </extension>
- *   </complexContent>
- * </complexType>
- * 
- * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "Scope") -@XmlSeeAlso({ - Do.class -}) -public class Scope - extends Node -{ - - @XmlAttribute - protected String name; - @XmlAttribute - protected Integer innerIndex; - - /** - * Gets the value of the name property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getName() { - return name; - } - - /** - * Sets the value of the name property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setName(String value) { - this.name = value; - } - - /** - * Gets the value of the innerIndex property. - * - * @return - * possible object is - * {@link Integer } - * - */ - public int getInnerIndex() { - if (innerIndex == null) { - return -1; - } else { - return innerIndex; - } - } - - /** - * Sets the value of the innerIndex property. - * - * @param value - * allowed object is - * {@link Integer } - * - */ - public void setInnerIndex(Integer value) { - this.innerIndex = value; - } - -} diff --git a/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/model/SendMessage.java b/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/model/SendMessage.java deleted file mode 100644 index b416803e8..000000000 --- a/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/model/SendMessage.java +++ /dev/null @@ -1,39 +0,0 @@ -// -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2012.02.06 at 05:22:54 PM GMT -// - - -package org.scribble.protocol.monitor.model; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlType; - - -/** - *

Java class for SendMessage complex type. - * - *

The following schema fragment specifies the expected content contained within this class. - * - *

- * <complexType name="SendMessage">
- *   <complexContent>
- *     <extension base="{http://www.scribble.org/monitor}MessageNode">
- *     </extension>
- *   </complexContent>
- * </complexType>
- * 
- * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "SendMessage") -public class SendMessage - extends MessageNode -{ - - -} diff --git a/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/model/package-info.java b/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/model/package-info.java deleted file mode 100644 index 02cd449b1..000000000 --- a/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/model/package-info.java +++ /dev/null @@ -1,9 +0,0 @@ -// -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2012.02.06 at 05:22:54 PM GMT -// - -@javax.xml.bind.annotation.XmlSchema(namespace = "http://www.scribble.org/monitor", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED) -package org.scribble.protocol.monitor.model; diff --git a/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/osgi/Activator.java b/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/osgi/Activator.java deleted file mode 100644 index 62c429150..000000000 --- a/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/osgi/Activator.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright 2009-11 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.monitor.osgi; - -import java.util.Properties; - -import org.osgi.framework.BundleActivator; -import org.osgi.framework.BundleContext; -import org.scribble.protocol.monitor.DefaultProtocolMonitor; -import org.scribble.protocol.monitor.ProtocolMonitor; - -/** - * This is the activator. - * - */ -public class Activator implements BundleActivator { - - /** - * {@inheritDoc} - */ - public void start(BundleContext context) throws Exception { - Properties props = new Properties(); - - ProtocolMonitor pm=new DefaultProtocolMonitor(); - - context.registerService(ProtocolMonitor.class.getName(), - pm, props); - } - - /** - * {@inheritDoc} - */ - public void stop(BundleContext context) throws Exception { - } - -} diff --git a/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/util/MonitorModelUtil.java b/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/util/MonitorModelUtil.java deleted file mode 100644 index 31874369f..000000000 --- a/bundles/org.scribble.protocol.monitor/src/main/java/org/scribble/protocol/monitor/util/MonitorModelUtil.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.monitor.util; - -import java.io.IOException; - -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBElement; -import javax.xml.bind.Marshaller; -import javax.xml.bind.Unmarshaller; - -import org.scribble.protocol.monitor.model.Description; - -/** - * Monitor model utility functions. - * - */ -public final class MonitorModelUtil { - - /** - * Private constructor. - */ - private MonitorModelUtil() { - } - - /** - * This method deserialises the model from the input stream. - * - * @param is The input stream - * @return The monitor description - * @throws IOException Failed to deserialize - */ - public static Description deserialize(java.io.InputStream is) throws IOException { - Description ret=null; - - try { - JAXBContext context = JAXBContext.newInstance("org.scribble.protocol.monitor.model", - MonitorModelUtil.class.getClassLoader()); - Unmarshaller unmarshaller = context.createUnmarshaller(); - - //note: setting schema to null will turn validator off - //unmarshaller.setSchema(null); - Object xmlObject = unmarshaller.unmarshal(is); - - if (xmlObject instanceof JAXBElement) { - ret = (Description)((JAXBElement)xmlObject).getValue(); - } - - } catch (Exception e) { - throw new IOException("Failed to deserialize description", e); - } - - return (ret); - } - - /** - * This method serializes the supplied monitor description to the - * supplied output stream. - * - * @param desc The monitoring description - * @param os The output stream - * @throws IOException Failed to serialize - */ - public static void serialize(Description desc, java.io.OutputStream os) throws IOException { - - try { - org.scribble.protocol.monitor.model.ObjectFactory factory= - new org.scribble.protocol.monitor.model.ObjectFactory(); - - JAXBContext context = JAXBContext.newInstance(Description.class); - Marshaller marshaller = context.createMarshaller(); - marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); - - marshaller.marshal(factory.createDescription(desc), os); - } catch (Exception e) { - throw new IOException("Failed to serialize description", e); - } - } -} diff --git a/bundles/org.scribble.protocol.monitor/src/test/java/org/scribble/protocol/monitor/BrokerParticipantTest.java b/bundles/org.scribble.protocol.monitor/src/test/java/org/scribble/protocol/monitor/BrokerParticipantTest.java deleted file mode 100644 index 9af4cb3a6..000000000 --- a/bundles/org.scribble.protocol.monitor/src/test/java/org/scribble/protocol/monitor/BrokerParticipantTest.java +++ /dev/null @@ -1,610 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.monitor; - -import static org.junit.Assert.*; - -import org.junit.Test; -import org.scribble.protocol.monitor.model.*; - -public class BrokerParticipantTest { - - private static final String OUT_OF_STOCK_MESSAGE_TYPE = "OutOfStock"; - private static final String INSUFFICIENT_CREDIT_MESSAGE_TYPE = "InsufficientCredit"; - private static final String CREDIT_OK_MESSAGE_TYPE = "CreditOk"; - private static final String CREDIT_CHECK_MESSAGE_TYPE = "CreditCheck"; - private static final String ORDER_MESSAGE_TYPE = "Order"; - private static final String CONFIRMATION_MESSAGE_TYPE = "Confirmation"; - - public enum PurchasingLabel { - _CreditOk, - _InsufficientCredit, - _Confirmation, - _OutOfStock, - } - - public Description getBrokerProtocol() { - Description pd=new Description(); - - // 0 - ReceiveMessage recvOrder=new ReceiveMessage(); - //recvOrder.setNodeType(Protocol.Node.NodeType.ReceiveMessage); - recvOrder.setNextIndex(1); - - MessageType mt1=new MessageType(); - mt1.setValue(ORDER_MESSAGE_TYPE); - recvOrder.getMessageType().add(mt1); - pd.getNode().add(recvOrder); - - // 1 - SendMessage sendCreditCheck=new SendMessage(); - //sendCreditCheck.setNodeType(Protocol.Node.NodeType.SendMessage); - sendCreditCheck.setNextIndex(2); - - MessageType mt2=new MessageType(); - mt2.setValue(CREDIT_CHECK_MESSAGE_TYPE); - sendCreditCheck.getMessageType().add(mt2); - pd.getNode().add(sendCreditCheck); - - // 2 - Choice choice1=new Choice(); - //choice1.setNodeType(Protocol.Node.NodeType.ReceiveChoice); - - Path c1=new Path(); - //c1.setId(PurchasingLabel._CreditOk.name()); - c1.setNextIndex(3); - choice1.getPath().add(c1); - - Path c2=new Path(); - //c2.setId(PurchasingLabel._InsufficientCredit.name()); - c2.setNextIndex(10); - choice1.getPath().add(c2); - - pd.getNode().add(choice1); - - // 3 - ReceiveMessage recvCreditOk=new ReceiveMessage(); - //recvCreditOk.setNodeType(Protocol.Node.NodeType.ReceiveMessage); - - MessageType mt3=new MessageType(); - mt3.setValue(CREDIT_OK_MESSAGE_TYPE); - recvCreditOk.getMessageType().add(mt3); - recvCreditOk.setNextIndex(4); - pd.getNode().add(recvCreditOk); - - // 4 - SendMessage sendOrder=new SendMessage(); - //sendOrder.setNodeType(Protocol.Node.NodeType.SendMessage); - sendOrder.setNextIndex(5); - - MessageType mt4=new MessageType(); - mt4.setValue(ORDER_MESSAGE_TYPE); - sendOrder.getMessageType().add(mt4); - pd.getNode().add(sendOrder); - - // 5 - Choice choice2=new Choice(); - //choice2.setNodeType(Protocol.Node.NodeType.ReceiveChoice); - - Path c3=new Path(); - //c3.setId(PurchasingLabel._Confirmation.name()); - c3.setNextIndex(6); - choice2.getPath().add(c3); - - Path c4=new Path(); - //c4.setId(PurchasingLabel._OutOfStock.name()); - c4.setNextIndex(8); - choice2.getPath().add(c4); - - pd.getNode().add(choice2); - - // 6 - ReceiveMessage recvConfirmation=new ReceiveMessage(); - //recvConfirmation.setNodeType(Protocol.Node.NodeType.ReceiveMessage); - - MessageType mt1a=new MessageType(); - mt1a.setValue(CONFIRMATION_MESSAGE_TYPE); - recvConfirmation.getMessageType().add(mt1a); - recvConfirmation.setNextIndex(7); - pd.getNode().add(recvConfirmation); - - // 7 - SendMessage sendConformation=new SendMessage(); - //sendConformation.setNodeType(Protocol.Node.NodeType.SendMessage); - - MessageType mt2a=new MessageType(); - mt2a.setValue(CONFIRMATION_MESSAGE_TYPE); - sendConformation.getMessageType().add(mt2a); - pd.getNode().add(sendConformation); - - // 8 - ReceiveMessage recvOutOfStock=new ReceiveMessage(); - //recvOutOfStock.setNodeType(Protocol.Node.NodeType.ReceiveMessage); - - MessageType mt3a=new MessageType(); - mt3a.setValue(OUT_OF_STOCK_MESSAGE_TYPE); - recvOutOfStock.getMessageType().add(mt3a); - recvOutOfStock.setNextIndex(9); - pd.getNode().add(recvOutOfStock); - - // 9 - SendMessage sendOutOfStock=new SendMessage(); - //sendOutOfStock.setNodeType(Protocol.Node.NodeType.SendMessage); - - MessageType mt4a=new MessageType(); - mt4a.setValue(OUT_OF_STOCK_MESSAGE_TYPE); - sendOutOfStock.getMessageType().add(mt4a); - pd.getNode().add(sendOutOfStock); - - // 10 - ReceiveMessage recvInsufficientCredit=new ReceiveMessage(); - //recvInsufficientCredit.setNodeType(Protocol.Node.NodeType.ReceiveMessage); - - MessageType mt5=new MessageType(); - mt5.setValue(INSUFFICIENT_CREDIT_MESSAGE_TYPE); - recvInsufficientCredit.getMessageType().add(mt5); - recvInsufficientCredit.setNextIndex(11); - pd.getNode().add(recvInsufficientCredit); - - // 11 - ReceiveMessage sendInsufficientCredit=new ReceiveMessage(); - //sendInsufficientCredit.setNodeType(Protocol.Node.NodeType.ReceiveMessage); - - MessageType mt6=new MessageType(); - mt6.setValue(INSUFFICIENT_CREDIT_MESSAGE_TYPE); - sendInsufficientCredit.getMessageType().add(mt6); - pd.getNode().add(sendInsufficientCredit); - - return (pd); - } - - public Description getBrokerWithParticipantProtocol() { - Description pd=new Description(); - - // 0 - ReceiveMessage recvOrder=new ReceiveMessage(); - //recvOrder.setNodeType(Protocol.Node.NodeType.ReceiveMessage); - recvOrder.setNextIndex(1); - - MessageType mt1=new MessageType(); - mt1.setValue(ORDER_MESSAGE_TYPE); - recvOrder.getMessageType().add(mt1); - pd.getNode().add(recvOrder); - - // 1 - SendMessage sendCreditCheck=new SendMessage(); - //sendCreditCheck.setNodeType(Protocol.Node.NodeType.SendMessage); - sendCreditCheck.setNextIndex(2); - - MessageType mt2=new MessageType(); - mt2.setValue(CREDIT_CHECK_MESSAGE_TYPE); - sendCreditCheck.getMessageType().add(mt2); - pd.getNode().add(sendCreditCheck); - - // 2 - Choice choice1=new Choice(); - //choice1.setNodeType(Protocol.Node.NodeType.ReceiveChoice); - //choice1.setOtherRole(CREDIT_AGENCY); - - Path c1=new Path(); - //c1.setId(PurchasingLabel._CreditOk.name()); - c1.setNextIndex(3); - choice1.getPath().add(c1); - - Path c2=new Path(); - //c2.setId(PurchasingLabel._InsufficientCredit.name()); - c2.setNextIndex(10); - choice1.getPath().add(c2); - - pd.getNode().add(choice1); - - // 3 - ReceiveMessage recvCreditOk=new ReceiveMessage(); - //recvCreditOk.setNodeType(Protocol.Node.NodeType.ReceiveMessage); - - MessageType mt3=new MessageType(); - mt3.setValue(CREDIT_OK_MESSAGE_TYPE); - recvCreditOk.getMessageType().add(mt3); - recvCreditOk.setNextIndex(4); - pd.getNode().add(recvCreditOk); - - // 4 - SendMessage sendOrder=new SendMessage(); - //sendOrder.setNodeType(Protocol.Node.NodeType.SendMessage); - sendOrder.setNextIndex(5); - - MessageType mt4=new MessageType(); - mt4.setValue(ORDER_MESSAGE_TYPE); - sendOrder.getMessageType().add(mt4); - pd.getNode().add(sendOrder); - - // 5 - Choice choice2=new Choice(); - //choice2.setNodeType(Protocol.Node.NodeType.ReceiveChoice); - //choice2.setOtherRole(SUPPLIER); - - Path c3=new Path(); - //c3.setId(PurchasingLabel._Confirmation.name()); - c3.setNextIndex(6); - choice2.getPath().add(c3); - - Path c4=new Path(); - //c4.setId(PurchasingLabel._OutOfStock.name()); - c4.setNextIndex(8); - choice2.getPath().add(c4); - - pd.getNode().add(choice2); - - // 6 - ReceiveMessage recvConfirmation=new ReceiveMessage(); - //recvConfirmation.setNodeType(Protocol.Node.NodeType.ReceiveMessage); - - MessageType mt5=new MessageType(); - mt5.setValue(CONFIRMATION_MESSAGE_TYPE); - recvConfirmation.getMessageType().add(mt5); - recvConfirmation.setNextIndex(7); - pd.getNode().add(recvConfirmation); - - // 7 - SendMessage sendConfirmation=new SendMessage(); - //sendConfirmation.setNodeType(Protocol.Node.NodeType.SendMessage); - - MessageType mt6=new MessageType(); - mt6.setValue(CONFIRMATION_MESSAGE_TYPE); - sendConfirmation.getMessageType().add(mt6); - pd.getNode().add(sendConfirmation); - - // 8 - ReceiveMessage recvOutOfStock=new ReceiveMessage(); - //recvOutOfStock.setNodeType(Protocol.Node.NodeType.ReceiveMessage); - - MessageType mt7=new MessageType(); - mt7.setValue(OUT_OF_STOCK_MESSAGE_TYPE); - recvOutOfStock.getMessageType().add(mt7); - recvOutOfStock.setNextIndex(9); - pd.getNode().add(recvOutOfStock); - - // 9 - SendMessage sendOutOfStock=new SendMessage(); - //sendOutOfStock.setNodeType(Protocol.Node.NodeType.SendMessage); - - MessageType mt8=new MessageType(); - mt8.setValue(OUT_OF_STOCK_MESSAGE_TYPE); - sendOutOfStock.getMessageType().add(mt8); - pd.getNode().add(sendOutOfStock); - - // 10 - ReceiveMessage recvInsufficientCredit=new ReceiveMessage(); - //recvInsufficientCredit.setNodeType(Protocol.Node.NodeType.ReceiveMessage); - - MessageType mt9=new MessageType(); - mt9.setValue(INSUFFICIENT_CREDIT_MESSAGE_TYPE); - recvInsufficientCredit.getMessageType().add(mt9); - recvInsufficientCredit.setNextIndex(11); - pd.getNode().add(recvInsufficientCredit); - - // 11 - ReceiveMessage sendInsufficientCredit=new ReceiveMessage(); - //sendInsufficientCredit.setNodeType(Protocol.Node.NodeType.ReceiveMessage); - - MessageType mt10=new MessageType(); - mt10.setValue(INSUFFICIENT_CREDIT_MESSAGE_TYPE); - sendInsufficientCredit.getMessageType().add(mt10); - pd.getNode().add(sendInsufficientCredit); - - return (pd); - } - - @Test - public void testBrokerValidOrderCreditCheckOk() { - Description pd=getBrokerProtocol(); - - // Create Protocol Monitor - ProtocolMonitor monitor=new DefaultProtocolMonitor(); - - DefaultMonitorContext context=new DefaultMonitorContext(); - - Session conv=monitor.createSession(context, pd, DefaultSession.class); - - DefaultMessage message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Receive Order failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CREDIT_CHECK_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Credit check failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CREDIT_OK_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Credit ok failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Send Order failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CONFIRMATION_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Receive Confirmation failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CONFIRMATION_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Send Confirmation failed"); - } - - if (conv.isFinished() == false) { - fail("Conversation should be finished"); - } - } - - @Test - public void testBrokerValidOrderCreditCheckOkLookahead() { - Description pd=getBrokerProtocol(); - - // Create Protocol Monitor - ProtocolMonitor monitor=new DefaultProtocolMonitor(); - - DefaultMonitorContext context=new DefaultMonitorContext(); - - Session conv=monitor.createSession(context, pd, DefaultSession.class); - - DefaultMessage message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Receive Order failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CREDIT_CHECK_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Credit check failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CREDIT_OK_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Credit ok failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Send Order failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CONFIRMATION_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Receive Confirmation failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CONFIRMATION_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Send Confirmation failed"); - } - - if (conv.isFinished() == false) { - fail("Conversation should be finished"); - } - } - - @Test - public void testBrokerInvalidOrderCreditCheckOk() { - Description pd=getBrokerProtocol(); - - // Create Protocol Monitor - ProtocolMonitor monitor=new DefaultProtocolMonitor(); - - DefaultMonitorContext context=new DefaultMonitorContext(); - - Session conv=monitor.createSession(context, pd, DefaultSession.class); - - DefaultMessage message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Receive Order failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CREDIT_CHECK_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Credit check failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == true) { - fail("Second order should have failed"); - } - - if (conv.isFinished() == true) { - fail("Conversation should NOT be finished"); - } - } - - @Test - public void testBrokerValidOrderCreditCheckOkWithParticipant() { - Description pd=getBrokerWithParticipantProtocol(); - - // Create Protocol Monitor - ProtocolMonitor monitor=new DefaultProtocolMonitor(); - - DefaultMonitorContext context=new DefaultMonitorContext(); - - Session conv=monitor.createSession(context, pd, DefaultSession.class); - - DefaultMessage message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Receive Order failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CREDIT_CHECK_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Credit check failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CREDIT_OK_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Credit ok failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Send Order failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CONFIRMATION_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Receive Confirmation failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CONFIRMATION_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Send Confirmation failed"); - } - - if (conv.isFinished() == false) { - fail("Conversation should be finished"); - } - } - - @Test - public void testBrokerValidOrderCreditCheckOkLookaheadWithParticipant() { - Description pd=getBrokerWithParticipantProtocol(); - - // Create Protocol Monitor - ProtocolMonitor monitor=new DefaultProtocolMonitor(); - - DefaultMonitorContext context=new DefaultMonitorContext(); - - Session conv=monitor.createSession(context, pd, DefaultSession.class); - - DefaultMessage message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Receive Order failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CREDIT_CHECK_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Credit check failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CREDIT_OK_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Credit ok failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Send Order failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CONFIRMATION_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Receive Confirmation failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CONFIRMATION_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Send Confirmation failed"); - } - - if (conv.isFinished() == false) { - fail("Conversation should be finished"); - } - } - - @Test - public void testBrokerInvalidOrderCreditCheckOkByParticipant() { - Description pd=getBrokerWithParticipantProtocol(); - - // Create Protocol Monitor - ProtocolMonitor monitor=new DefaultProtocolMonitor(); - - DefaultMonitorContext context=new DefaultMonitorContext(); - - Session conv=monitor.createSession(context, pd, DefaultSession.class); - - DefaultMessage message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Receive Order failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CREDIT_CHECK_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Credit check failed"); - } - - if (conv.isFinished() == true) { - fail("Conversation should NOT be finished"); - } - } -} diff --git a/bundles/org.scribble.protocol.monitor/src/test/java/org/scribble/protocol/monitor/BuyerParticipantTest.java b/bundles/org.scribble.protocol.monitor/src/test/java/org/scribble/protocol/monitor/BuyerParticipantTest.java deleted file mode 100644 index a77c3798e..000000000 --- a/bundles/org.scribble.protocol.monitor/src/test/java/org/scribble/protocol/monitor/BuyerParticipantTest.java +++ /dev/null @@ -1,186 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.monitor; - -import static org.junit.Assert.*; - -import org.junit.Test; -import org.scribble.protocol.monitor.model.*; - - -public class BuyerParticipantTest { - - private static final String INSUFFICIENT_CREDIT_MESSAGE_TYPE = "InsufficientCredit"; - private static final String OUT_OF_STOCK_MESSAGE_TYPE = "OutOfStock"; - private static final String CONFIRMATION_MESSAGE_TYPE = "Confirmation"; - private static final String ORDER_MESSAGE_TYPE = "Order"; - - public enum PurchasingLabel { - _Confirmation, - _OutOfStock, - _InsufficientCredit - } - - public Description getBuyerProtocol() { - Description pd=new Description(); - - SendMessage sendOrder=new SendMessage(); - //sendOrder.setNodeType(Protocol.Node.NodeType.SendMessage); - sendOrder.setNextIndex(1); - - MessageType mt1=new MessageType(); - mt1.setValue(ORDER_MESSAGE_TYPE); - sendOrder.getMessageType().add(mt1); - pd.getNode().add(sendOrder); - - Choice choice=new Choice(); - //choice.setNodeType(Protocol.Node.NodeType.ReceiveChoice); - - Path c1=new Path(); - //c1.setId(PurchasingLabel._Confirmation.name()); - c1.setNextIndex(2); - choice.getPath().add(c1); - - Path c2=new Path(); - //c2.setId(PurchasingLabel._OutOfStock.name()); - c2.setNextIndex(3); - choice.getPath().add(c2); - - Path c3=new Path(); - //c3.setId(PurchasingLabel._InsufficientCredit.name()); - c3.setNextIndex(4); - choice.getPath().add(c3); - - pd.getNode().add(choice); - - ReceiveMessage recvConfirmation=new ReceiveMessage(); - //recvConfirmation.setNodeType(Protocol.Node.NodeType.ReceiveMessage); - - MessageType mt2=new MessageType(); - mt2.setValue(CONFIRMATION_MESSAGE_TYPE); - recvConfirmation.getMessageType().add(mt2); - pd.getNode().add(recvConfirmation); - - ReceiveMessage recvOutOfStock=new ReceiveMessage(); - //recvOutOfStock.setNodeType(Protocol.Node.NodeType.ReceiveMessage); - - MessageType mt3=new MessageType(); - mt3.setValue(OUT_OF_STOCK_MESSAGE_TYPE); - recvOutOfStock.getMessageType().add(mt3); - pd.getNode().add(recvOutOfStock); - - ReceiveMessage recvInsufficientCredit=new ReceiveMessage(); - //recvInsufficientCredit.setNodeType(Protocol.Node.NodeType.ReceiveMessage); - - MessageType mt4=new MessageType(); - mt4.setValue(INSUFFICIENT_CREDIT_MESSAGE_TYPE); - recvInsufficientCredit.getMessageType().add(mt4); - pd.getNode().add(recvInsufficientCredit); - - return (pd); - } - - @Test - public void testBuyerValidOrderConfirmation() { - Description pd=getBuyerProtocol(); - - // Create Protocol Monitor - ProtocolMonitor monitor=new DefaultProtocolMonitor(); - - DefaultMonitorContext context=new DefaultMonitorContext(); - - Session conv=monitor.createSession(context, pd, DefaultSession.class); - - DefaultMessage message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Order failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CONFIRMATION_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Confirmation failed"); - } - - if (conv.isFinished() == false) { - fail("Conversation should be finished"); - } - } - - @Test - public void testBuyerValidOrderConfirmationLookahead() { - Description pd=getBuyerProtocol(); - - // Create Protocol Monitor - ProtocolMonitor monitor=new DefaultProtocolMonitor(); - - DefaultMonitorContext context=new DefaultMonitorContext(); - - Session conv=monitor.createSession(context, pd, DefaultSession.class); - - DefaultMessage message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Order failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CONFIRMATION_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Confirmation failed"); - } - - if (conv.isFinished() == false) { - fail("Conversation should be finished"); - } - } - - @Test - public void testBuyerInvalidOrderConfirmation() { - Description pd=getBuyerProtocol(); - - // Create Protocol Monitor - ProtocolMonitor monitor=new DefaultProtocolMonitor(); - - DefaultMonitorContext context=new DefaultMonitorContext(); - - Session conv=monitor.createSession(context, pd, DefaultSession.class); - - DefaultMessage message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Order failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == true) { - fail("Second order should have failed"); - } - - if (conv.isFinished() == true) { - fail("Conversation should NOT be finished"); - } - } -} diff --git a/bundles/org.scribble.protocol.monitor/src/test/java/org/scribble/protocol/monitor/CreditAgencyParticipantTest.java b/bundles/org.scribble.protocol.monitor/src/test/java/org/scribble/protocol/monitor/CreditAgencyParticipantTest.java deleted file mode 100644 index 6c9f04a48..000000000 --- a/bundles/org.scribble.protocol.monitor/src/test/java/org/scribble/protocol/monitor/CreditAgencyParticipantTest.java +++ /dev/null @@ -1,171 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.monitor; - -import static org.junit.Assert.*; - -import org.junit.Test; -import org.scribble.protocol.monitor.model.*; - - -public class CreditAgencyParticipantTest { - - private static final String INSUFFICIENT_CREDIT_MESSAGE_TYPE = "InsufficientCredit"; - private static final String CREDIT_OK_MESSAGE_TYPE = "CreditOk"; - private static final String CREDIT_CHECK_MESSAGE_TYPE = "CreditCheck"; - - public enum PurchasingLabel { - _CreditOk, - _InsufficientCredit - } - - public Description getCreditAgencyProtocol() { - Description pd=new Description(); - - ReceiveMessage recvCreditCheck=new ReceiveMessage(); - //recvCreditCheck.setNodeType(Protocol.Node.NodeType.ReceiveMessage); - recvCreditCheck.setNextIndex(1); - - MessageType mt1=new MessageType(); - mt1.setValue(CREDIT_CHECK_MESSAGE_TYPE); - recvCreditCheck.getMessageType().add(mt1); - pd.getNode().add(recvCreditCheck); - - Choice choice=new Choice(); - //choice.setNodeType(Protocol.Node.NodeType.SendChoice); - - Path c1=new Path(); - //c1.setId(PurchasingLabel._CreditOk.name()); - c1.setNextIndex(2); - choice.getPath().add(c1); - - Path c2=new Path(); - //c2.setId(PurchasingLabel._InsufficientCredit.name()); - c2.setNextIndex(3); - choice.getPath().add(c2); - - pd.getNode().add(choice); - - SendMessage sendCreditOk=new SendMessage(); - //sendCreditOk.setNodeType(Protocol.Node.NodeType.SendMessage); - - MessageType mt2=new MessageType(); - mt2.setValue(CREDIT_OK_MESSAGE_TYPE); - sendCreditOk.getMessageType().add(mt2); - pd.getNode().add(sendCreditOk); - - SendMessage sendInsufficientCredit=new SendMessage(); - //sendInsufficientCredit.setNodeType(Protocol.Node.NodeType.SendMessage); - - MessageType mt3=new MessageType(); - mt3.setValue(INSUFFICIENT_CREDIT_MESSAGE_TYPE); - sendInsufficientCredit.getMessageType().add(mt3); - pd.getNode().add(sendInsufficientCredit); - - return (pd); - } - - @Test - public void testCreditAgencyValidCreditCheckOk() { - Description pd=getCreditAgencyProtocol(); - - // Create Protocol Monitor - ProtocolMonitor monitor=new DefaultProtocolMonitor(); - - DefaultMonitorContext context=new DefaultMonitorContext(); - - Session conv=monitor.createSession(context, pd, DefaultSession.class); - - DefaultMessage message=new DefaultMessage(); - message.getTypes().add(CREDIT_CHECK_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Credit check failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CREDIT_OK_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Credit ok failed"); - } - - if (conv.isFinished() == false) { - fail("Conversation should be finished"); - } - } - - @Test - public void testCreditAgencyValidCreditCheckOkLookahead() { - Description pd=getCreditAgencyProtocol(); - - // Create Protocol Monitor - ProtocolMonitor monitor=new DefaultProtocolMonitor(); - - DefaultMonitorContext context=new DefaultMonitorContext(); - - Session conv=monitor.createSession(context, pd, DefaultSession.class); - - DefaultMessage message=new DefaultMessage(); - message.getTypes().add(CREDIT_CHECK_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("CreditCheck failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CREDIT_OK_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("CreditOk failed"); - } - - if (conv.isFinished() == false) { - fail("Conversation should be finished"); - } - } - - @Test - public void testCreditAgencyInvalidOrderConfirmation() { - Description pd=getCreditAgencyProtocol(); - - // Create Protocol Monitor - ProtocolMonitor monitor=new DefaultProtocolMonitor(); - - DefaultMonitorContext context=new DefaultMonitorContext(); - - Session conv=monitor.createSession(context, pd, DefaultSession.class); - - DefaultMessage message=new DefaultMessage(); - message.getTypes().add(CREDIT_CHECK_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("CreditCheck failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CREDIT_CHECK_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == true) { - fail("Second Credit Check should have failed"); - } - - if (conv.isFinished() == true) { - fail("Conversation should NOT be finished"); - } - } -} diff --git a/bundles/org.scribble.protocol.monitor/src/test/java/org/scribble/protocol/monitor/DefaultMonitorContextTest.java b/bundles/org.scribble.protocol.monitor/src/test/java/org/scribble/protocol/monitor/DefaultMonitorContextTest.java deleted file mode 100644 index b99fda057..000000000 --- a/bundles/org.scribble.protocol.monitor/src/test/java/org/scribble/protocol/monitor/DefaultMonitorContextTest.java +++ /dev/null @@ -1,216 +0,0 @@ -/* - * Copyright 2009-11 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.monitor; - -import static org.junit.Assert.*; - -import org.junit.Test; - -public class DefaultMonitorContextTest { - - @Test - public void testLinkTrue() { - DefaultMonitorContext context=new DefaultMonitorContext(); - - DefaultSession session=new DefaultSession(); - session.setState("X", Boolean.TRUE); - - Boolean result=context.evaluate(session, "X"); - - if (result == null) { - fail("Result was null"); - } - - if (!result.booleanValue()) { - fail("Result should be true"); - } - } - - @Test - public void testLinkFalse() { - DefaultMonitorContext context=new DefaultMonitorContext(); - - DefaultSession session=new DefaultSession(); - session.setState("X", Boolean.FALSE); - - Boolean result=context.evaluate(session, "X"); - - if (result == null) { - fail("Result was null"); - } - - if (result.booleanValue()) { - fail("Result should be false"); - } - } - - @Test - public void testLinkUnset() { - DefaultMonitorContext context=new DefaultMonitorContext(); - - DefaultSession session=new DefaultSession(); - session.setState("X", null); - - Boolean result=context.evaluate(session, "X"); - - if (result != null) { - fail("Result was NOT null"); - } - } - - @Test - public void testLinkANDTrueNull() { - DefaultMonitorContext context=new DefaultMonitorContext(); - - DefaultSession session=new DefaultSession(); - session.setState("X", null); - session.setState("Y", Boolean.TRUE); - - Boolean result=context.evaluate(session, "X and Y"); - - if (result != null) { - fail("Result should be null"); - } - } - - @Test - public void testLinkANDFalseNull() { - DefaultMonitorContext context=new DefaultMonitorContext(); - - DefaultSession session=new DefaultSession(); - session.setState("X", null); - session.setState("Y", Boolean.FALSE); - - Boolean result=context.evaluate(session, "X and Y"); - - if (result != null) { - fail("Result should be null"); - } - } - - @Test - public void testLinkANDTrueFalse() { - DefaultMonitorContext context=new DefaultMonitorContext(); - - DefaultSession session=new DefaultSession(); - session.setState("X", Boolean.FALSE); - session.setState("Y", Boolean.TRUE); - - Boolean result=context.evaluate(session, "X and Y"); - - if (result == null) { - fail("Result was null"); - } - - if (result.booleanValue()) { - fail("Result should be false"); - } - } - - @Test - public void testLinkANDTrueTrue() { - DefaultMonitorContext context=new DefaultMonitorContext(); - - DefaultSession session=new DefaultSession(); - session.setState("X", Boolean.TRUE); - session.setState("Y", Boolean.TRUE); - - Boolean result=context.evaluate(session, "X and Y"); - - if (result == null) { - fail("Result was null"); - } - - if (!result.booleanValue()) { - fail("Result should be true"); - } - } - - @Test - public void testLinkORTrue1() { - DefaultMonitorContext context=new DefaultMonitorContext(); - - DefaultSession session=new DefaultSession(); - session.setState("X", null); - session.setState("Y", Boolean.TRUE); - - Boolean result=context.evaluate(session, "X or Y"); - - if (result == null) { - fail("Result was null"); - } - - if (!result.booleanValue()) { - fail("Result should be true"); - } - } - - @Test - public void testLinkORTrue2() { - DefaultMonitorContext context=new DefaultMonitorContext(); - - DefaultSession session=new DefaultSession(); - session.setState("X", Boolean.FALSE); - session.setState("Y", Boolean.TRUE); - - Boolean result=context.evaluate(session, "X or Y"); - - if (result == null) { - fail("Result was null"); - } - - if (!result.booleanValue()) { - fail("Result should be true"); - } - } - - @Test - public void testLinkORNull() { - DefaultMonitorContext context=new DefaultMonitorContext(); - - DefaultSession session=new DefaultSession(); - session.setState("X", Boolean.FALSE); - session.setState("Y", null); - - // Result should be null, as still chance that result - // could become true - Boolean result=context.evaluate(session, "X or Y"); - - if (result != null) { - fail("Result should be null"); - } - } - - @Test - public void testLinkORFalse() { - DefaultMonitorContext context=new DefaultMonitorContext(); - - DefaultSession session=new DefaultSession(); - session.setState("X", Boolean.FALSE); - session.setState("Y", Boolean.FALSE); - - Boolean result=context.evaluate(session, "X or Y"); - - if (result == null) { - fail("Result was null"); - } - - if (result.booleanValue()) { - fail("Result should be false"); - } - } -} diff --git a/bundles/org.scribble.protocol.monitor/src/test/java/org/scribble/protocol/monitor/DefaultSessionTest.java b/bundles/org.scribble.protocol.monitor/src/test/java/org/scribble/protocol/monitor/DefaultSessionTest.java deleted file mode 100644 index a3b189a14..000000000 --- a/bundles/org.scribble.protocol.monitor/src/test/java/org/scribble/protocol/monitor/DefaultSessionTest.java +++ /dev/null @@ -1,265 +0,0 @@ -/* - * Copyright 2009-11 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.monitor; - -import static org.junit.Assert.*; - -import org.junit.Test; - -public class DefaultSessionTest { - - @Test - public void testSerializeSimple() { - DefaultSession session=new DefaultSession(); - - session.addNodeIndex(1); - session.addNodeIndex(2); - - try { - java.io.ByteArrayOutputStream os=new java.io.ByteArrayOutputStream(); - java.io.ObjectOutputStream oos=new java.io.ObjectOutputStream(os); - - oos.writeObject(session); - - java.io.ByteArrayInputStream is=new java.io.ByteArrayInputStream(os.toByteArray()); - - java.io.ObjectInputStream ois=new java.io.ObjectInputStream(is); - - DefaultSession result=(DefaultSession)ois.readObject(); - - validateSessions(result, session); - - } catch (Exception e) { - fail("Failed to serialize: "+e); - } - } - - @Test - public void testSerializeNested() { - DefaultSession session=new DefaultSession(); - - session.addNodeIndex(1); - session.addNodeIndex(2); - - DefaultSession nested1=(DefaultSession)session.createNestedConversation(3); - nested1.addNodeIndex(4); - - session.getNestedConversations().add(nested1); - - try { - java.io.ByteArrayOutputStream os=new java.io.ByteArrayOutputStream(); - java.io.ObjectOutputStream oos=new java.io.ObjectOutputStream(os); - - oos.writeObject(session); - - java.io.ByteArrayInputStream is=new java.io.ByteArrayInputStream(os.toByteArray()); - - java.io.ObjectInputStream ois=new java.io.ObjectInputStream(is); - - DefaultSession result=(DefaultSession)ois.readObject(); - - validateSessions(result, session); - - } catch (Exception e) { - fail("Failed to serialize: "+e); - } - } - - @Test - public void testSerializeInterrupt() { - DefaultSession session=new DefaultSession(); - - session.addNodeIndex(1); - session.addNodeIndex(2); - - DefaultSession main=(DefaultSession)session.createNestedConversation(6); - - DefaultSession interrupt1=(DefaultSession)session.createInterruptConversation(main, 4); - interrupt1.addNodeIndex(5); - - try { - java.io.ByteArrayOutputStream os=new java.io.ByteArrayOutputStream(); - java.io.ObjectOutputStream oos=new java.io.ObjectOutputStream(os); - - oos.writeObject(session); - - java.io.ByteArrayInputStream is=new java.io.ByteArrayInputStream(os.toByteArray()); - - java.io.ObjectInputStream ois=new java.io.ObjectInputStream(is); - - DefaultSession result=(DefaultSession)ois.readObject(); - - validateSessions(result, session); - - } catch (Exception e) { - fail("Failed to serialize: "+e); - } - } - - @Test - public void testSerializeState() { - DefaultSession session=new DefaultSession(); - - DefaultSession child=(DefaultSession)session.createNestedConversation(6); - - session.setState("state1", null); - session.setState("state2", "value1"); - child.setState("state3", "value2"); - - try { - java.io.ByteArrayOutputStream os=new java.io.ByteArrayOutputStream(); - java.io.ObjectOutputStream oos=new java.io.ObjectOutputStream(os); - - oos.writeObject(session); - - java.io.ByteArrayInputStream is=new java.io.ByteArrayInputStream(os.toByteArray()); - - java.io.ObjectInputStream ois=new java.io.ObjectInputStream(is); - - DefaultSession result=(DefaultSession)ois.readObject(); - - validateSessions(result, session); - - if (result.getState("state1") != null) { - fail("State1 should be null"); - } - - if (result.getState("state2") == null) { - fail("State2 should NOT be null"); - } - - if (!result.getState("state2").equals("value1")) { - fail("State2 value incorrect"); - } - - if (result.getNestedConversations().size() != 1) { - fail("Expecting 1 nested conversation: "+result.getNestedConversations().size()); - } - - if (result.getNestedConversations().get(0).getState("state3") == null) { - fail("State3 should not be null"); - } - - if (!result.getNestedConversations().get(0).getState("state3").equals("value2")) { - fail("State3 value incorrect"); - } - } catch (Exception e) { - fail("Failed to serialize: "+e); - } - } - - protected void validateSessions(DefaultSession result, DefaultSession session) { - - if (result.getNumberOfNodeIndexes() != session.getNumberOfNodeIndexes()) { - fail("Number of node indexes different"); - } - - for (int i=0; i < result.getNumberOfNodeIndexes(); i++) { - if (result.getNodeIndexAt(i) != session.getNodeIndexAt(i)) { - fail("Node index ["+i+"] is wrong"); - } - } - - if (result.getReturnIndex() != session.getReturnIndex()) { - fail("Return index different"); - } - - if ((result.getParentConversation() != null && session.getParentConversation() == null) || - (result.getParentConversation() == null && session.getParentConversation() != null)) { - fail("Parent conversation not null"); - } - - if ((result.getMainConversation() != null && session.getMainConversation() == null) || - (result.getMainConversation() == null && session.getMainConversation() != null)) { - fail("Main conversation not null"); - } - - if (result.getNestedConversations().size() != session.getNestedConversations().size()) { - fail("Nested conversation size different"); - } - - for (int i=0; i < result.getNestedConversations().size(); i++) { - validateSessions((DefaultSession)result.getNestedConversations().get(i), - (DefaultSession)session.getNestedConversations().get(i)); - } - - if (result.getInterruptConversations().size() != session.getInterruptConversations().size()) { - fail("Interrupt conversation size different"); - } - - for (int i=0; i < result.getInterruptConversations().size(); i++) { - validateSessions((DefaultSession)result.getInterruptConversations().get(i), - (DefaultSession)session.getInterruptConversations().get(i)); - } - } - - @Test - public void testSetState() { - DefaultSession sess=new DefaultSession(); - - sess.setState("testState", "testValue"); - - if (sess.getState("testState") == null) { - fail("State not found"); - } - - if (!sess.getState("testState").equals("testValue")) { - fail("State value not correct"); - } - } - - @Test - public void testGetStateFromChild() { - DefaultSession parent=new DefaultSession(); - - Session child=parent.createNestedConversation(-1); - - parent.setState("testState", "testValue"); - - if (child.getState("testState") == null) { - fail("State not found"); - } - - if (!child.getState("testState").equals("testValue")) { - fail("State value not correct"); - } - } - - @Test - public void testSetStateDeclaredInParent() { - DefaultSession parent=new DefaultSession(); - - Session child=parent.createNestedConversation(-1); - - // Declare var by setting to null in parent - parent.setState("testState", null); - - if (parent.getState("testState") != null) { - fail("State should be null"); - } - - child.setState("testState", "testValue"); - - if (parent.getState("testState") == null) { - fail("State should NOT be null"); - } - - if (!parent.getState("testState").equals("testValue")) { - fail("State value not correct"); - } - } -} diff --git a/bundles/org.scribble.protocol.monitor/src/test/java/org/scribble/protocol/monitor/DoInterruptTest.java b/bundles/org.scribble.protocol.monitor/src/test/java/org/scribble/protocol/monitor/DoInterruptTest.java deleted file mode 100644 index 57c70d388..000000000 --- a/bundles/org.scribble.protocol.monitor/src/test/java/org/scribble/protocol/monitor/DoInterruptTest.java +++ /dev/null @@ -1,159 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.monitor; - -import static org.junit.Assert.*; - -import org.junit.Test; -import org.scribble.protocol.monitor.model.*; - - -public class DoInterruptTest { - - private static final String CONFIRMATION_MESSAGE_TYPE = "Confirmation"; - private static final String ORDER_MESSAGE_TYPE = "Order"; - private static final String CANCEL_MESSAGE_TYPE = "Cancel"; - private static final String FINISH_MESSAGE_TYPE = "Finish"; - - public enum PurchasingLabel { - _Confirmation, - _OutOfStock - } - - public Description getSellerProtocol() { - Description pd=new Description(); - - // 0 - Do tn=new Do(); - pd.getNode().add(tn); - tn.setNextIndex(4); - tn.setInnerIndex(1); - - Path p=new Path(); - p.setNextIndex(3); - tn.getPath().add(p); - - // 1 - ReceiveMessage recvOrder=new ReceiveMessage(); - recvOrder.setNextIndex(2); - - MessageType mt1=new MessageType(); - mt1.setValue(ORDER_MESSAGE_TYPE); - recvOrder.getMessageType().add(mt1); - pd.getNode().add(recvOrder); - - // 2 - SendMessage sendConformation=new SendMessage(); - - MessageType mt2=new MessageType(); - mt2.setValue(CONFIRMATION_MESSAGE_TYPE); - sendConformation.getMessageType().add(mt2); - pd.getNode().add(sendConformation); - - // 3 - ReceiveMessage recvCancel=new ReceiveMessage(); - - MessageType mt3=new MessageType(); - mt3.setValue(CANCEL_MESSAGE_TYPE); - recvCancel.getMessageType().add(mt3); - pd.getNode().add(recvCancel); - - // 4 - ReceiveMessage recvFinish=new ReceiveMessage(); - - MessageType mt4=new MessageType(); - mt4.setValue(FINISH_MESSAGE_TYPE); - recvFinish.getMessageType().add(mt4); - pd.getNode().add(recvFinish); - - return (pd); - } - - @Test - public void testNoCancel() { - Description pd=getSellerProtocol(); - - // Create Protocol Monitor - ProtocolMonitor monitor=new DefaultProtocolMonitor(); - - DefaultMonitorContext context=new DefaultMonitorContext(); - - Session conv=monitor.createSession(context, pd, DefaultSession.class); - - DefaultMessage message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Order failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CONFIRMATION_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Confirmation failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(FINISH_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Finish message failed"); - } - - if (conv.isFinished() == false) { - fail("Conversation should be finished"); - } - } - - @Test - public void testCancel() { - Description pd=getSellerProtocol(); - - // Create Protocol Monitor - ProtocolMonitor monitor=new DefaultProtocolMonitor(); - - DefaultMonitorContext context=new DefaultMonitorContext(); - - Session conv=monitor.createSession(context, pd, DefaultSession.class); - - DefaultMessage message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Order failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CANCEL_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Cancel failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(FINISH_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Finish message failed"); - } - - if (conv.isFinished() == false) { - fail("Conversation should be finished"); - } - } -} diff --git a/bundles/org.scribble.protocol.monitor/src/test/java/org/scribble/protocol/monitor/ForkJoinTest.java b/bundles/org.scribble.protocol.monitor/src/test/java/org/scribble/protocol/monitor/ForkJoinTest.java deleted file mode 100644 index 770143837..000000000 --- a/bundles/org.scribble.protocol.monitor/src/test/java/org/scribble/protocol/monitor/ForkJoinTest.java +++ /dev/null @@ -1,203 +0,0 @@ -/* - * Copyright 2009-12 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.monitor; - -import static org.junit.Assert.*; - -import org.junit.Test; -import org.scribble.protocol.monitor.model.*; - -public class ForkJoinTest { - - private static final String OUT_OF_STOCK_MESSAGE_TYPE = "OutOfStock"; - private static final String CONFIRMATION_MESSAGE_TYPE = "Confirmation"; - private static final String ORDER_MESSAGE_TYPE = "Order"; - private static final String FINISH_MESSAGE_TYPE = "Finish"; - - public enum PurchasingLabel { - _Confirmation, - _OutOfStock - } - - public Description getProtocol() { - Description pd=new Description(); - - // 0 - ReceiveMessage recvOrder=new ReceiveMessage(); - recvOrder.setNextIndex(1); - - MessageType mt1=new MessageType(); - mt1.setValue(ORDER_MESSAGE_TYPE); - recvOrder.getMessageType().add(mt1); - pd.getNode().add(recvOrder); - - // 1 - LinkDeclaration linkdecl=new LinkDeclaration(); - linkdecl.setName("link1"); - linkdecl.setNextIndex(2); - pd.getNode().add(linkdecl); - - // 2 - Parallel parallel=new Parallel(); - parallel.setNextIndex(7); - - Path c1=new Path(); - c1.setNextIndex(3); - parallel.getPath().add(c1); - - Path c2=new Path(); - c2.setNextIndex(5); - parallel.getPath().add(c2); - - pd.getNode().add(parallel); - - // 3 - SendMessage sendConfirmation=new SendMessage(); - - MessageType mt2=new MessageType(); - mt2.setValue(CONFIRMATION_MESSAGE_TYPE); - sendConfirmation.getMessageType().add(mt2); - sendConfirmation.setNextIndex(4); - pd.getNode().add(sendConfirmation); - - // 4 - Fork fork=new Fork(); - fork.setLinkName("link1"); - pd.getNode().add(fork); - - // 5 - Join join=new Join(); - join.setExpression("link1"); - join.setNextIndex(6); - pd.getNode().add(join); - - // 6 - SendMessage sendOutOfStock=new SendMessage(); - - MessageType mt3=new MessageType(); - mt3.setValue(OUT_OF_STOCK_MESSAGE_TYPE); - sendOutOfStock.getMessageType().add(mt3); - pd.getNode().add(sendOutOfStock); - - // 7 - SendMessage sendFinish=new SendMessage(); - - MessageType mt4=new MessageType(); - mt4.setValue(FINISH_MESSAGE_TYPE); - sendFinish.getMessageType().add(mt4); - pd.getNode().add(sendFinish); - - return (pd); - } - - @Test - public void testValidCompletion() { - Description pd=getProtocol(); - - // Create Protocol Monitor - ProtocolMonitor monitor=new DefaultProtocolMonitor(); - - DefaultMonitorContext context=new DefaultMonitorContext(); - - Session conv=monitor.createSession(context, pd, DefaultSession.class); - - DefaultMessage message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Order failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CONFIRMATION_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Confirmation failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(OUT_OF_STOCK_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Out Of Stock failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(FINISH_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Finish message failed"); - } - - if (conv.isFinished() == false) { - fail("Conversation should be finished"); - } - } - - - @Test - public void testValidCompletionAfterOutOfOrderMessage() { - Description pd=getProtocol(); - - // Create Protocol Monitor - ProtocolMonitor monitor=new DefaultProtocolMonitor(); - - DefaultMonitorContext context=new DefaultMonitorContext(); - - Session conv=monitor.createSession(context, pd, DefaultSession.class); - - DefaultMessage message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Order failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(OUT_OF_STOCK_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == true) { - fail("Out Of Stock should initially fail"); - } - - message=new DefaultMessage(); - message.getTypes().add(CONFIRMATION_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Confirmation failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(OUT_OF_STOCK_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Out Of Stock failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(FINISH_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Finish message failed"); - } - - if (conv.isFinished() == false) { - fail("Conversation should be finished"); - } - } - -} \ No newline at end of file diff --git a/bundles/org.scribble.protocol.monitor/src/test/java/org/scribble/protocol/monitor/OptionalTest.java b/bundles/org.scribble.protocol.monitor/src/test/java/org/scribble/protocol/monitor/OptionalTest.java deleted file mode 100644 index f8b517bf6..000000000 --- a/bundles/org.scribble.protocol.monitor/src/test/java/org/scribble/protocol/monitor/OptionalTest.java +++ /dev/null @@ -1,497 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.monitor; - -import static org.junit.Assert.*; - -import org.junit.Test; -import org.scribble.protocol.monitor.model.*; - -public class OptionalTest { - - private static final String CREDIT_OK_MESSAGE_TYPE = "CreditOk"; - private static final String CREDIT_CHECK_MESSAGE_TYPE = "CreditCheck"; - private static final String ORDER_MESSAGE_TYPE = "Order"; - private static final String CONFIRMATION_MESSAGE_TYPE = "Confirmation"; - - public enum PurchasingLabel { - _CreditOk, - _InsufficientCredit, - _Confirmation, - _OutOfStock, - } - - public Description getSendDecisionProtocol() { - Description pd=new Description(); - - // 0 - ReceiveMessage recvOrder=new ReceiveMessage(); - //recvOrder.setNodeType(Protocol.Node.NodeType.ReceiveMessage); - recvOrder.setNextIndex(1); - - MessageType mt1=new MessageType(); - mt1.setValue(ORDER_MESSAGE_TYPE); - recvOrder.getMessageType().add(mt1); - pd.getNode().add(recvOrder); - - // 1 - Decision conditional=new Decision(); - //conditional.setNodeType(Protocol.Node.NodeType.SendDecision); - conditional.setNextIndex(4); - conditional.setInnerIndex(2); - pd.getNode().add(conditional); - - // 2 - SendMessage sendCreditCheck=new SendMessage(); - //sendCreditCheck.setNodeType(Protocol.Node.NodeType.SendMessage); - sendCreditCheck.setNextIndex(3); - - MessageType mt2=new MessageType(); - mt2.setValue(CREDIT_CHECK_MESSAGE_TYPE); - sendCreditCheck.getMessageType().add(mt2); - pd.getNode().add(sendCreditCheck); - - // 3 - ReceiveMessage recvCreditOk=new ReceiveMessage(); - //recvCreditOk.setNodeType(Protocol.Node.NodeType.ReceiveMessage); - recvCreditOk.setNextIndex(4); - - MessageType mt3=new MessageType(); - mt3.setValue(CREDIT_OK_MESSAGE_TYPE); - recvCreditOk.getMessageType().add(mt3); - pd.getNode().add(recvCreditOk); - - // 4 - SendMessage sendOrder=new SendMessage(); - //sendOrder.setNodeType(Protocol.Node.NodeType.SendMessage); - - MessageType mt4=new MessageType(); - mt4.setValue(CONFIRMATION_MESSAGE_TYPE); - sendOrder.getMessageType().add(mt4); - pd.getNode().add(sendOrder); - - return (pd); - } - - public Description getReceiveDecisionProtocol() { - Description pd=new Description(); - - // 0 - SendMessage recvOrder=new SendMessage(); - //recvOrder.setNodeType(Protocol.Node.NodeType.SendMessage); - recvOrder.setNextIndex(1); - - MessageType mt1=new MessageType(); - mt1.setValue(ORDER_MESSAGE_TYPE); - recvOrder.getMessageType().add(mt1); - pd.getNode().add(recvOrder); - - // 1 - Decision conditional=new Decision(); - //conditional.setNodeType(Protocol.Node.NodeType.ReceiveDecision); - conditional.setNextIndex(4); - conditional.setInnerIndex(2); - pd.getNode().add(conditional); - - // 2 - ReceiveMessage sendCreditCheck=new ReceiveMessage(); - //sendCreditCheck.setNodeType(Protocol.Node.NodeType.ReceiveMessage); - sendCreditCheck.setNextIndex(3); - - MessageType mt2=new MessageType(); - mt2.setValue(CREDIT_CHECK_MESSAGE_TYPE); - sendCreditCheck.getMessageType().add(mt2); - pd.getNode().add(sendCreditCheck); - - // 3 - SendMessage recvCreditOk=new SendMessage(); - //recvCreditOk.setNodeType(Protocol.Node.NodeType.SendMessage); - recvCreditOk.setNextIndex(4); - - MessageType mt3=new MessageType(); - mt3.setValue(CREDIT_OK_MESSAGE_TYPE); - recvCreditOk.getMessageType().add(mt3); - pd.getNode().add(recvCreditOk); - - // 4 - ReceiveMessage sendOrder=new ReceiveMessage(); - //sendOrder.setNodeType(Protocol.Node.NodeType.ReceiveMessage); - - MessageType mt4=new MessageType(); - mt4.setValue(CONFIRMATION_MESSAGE_TYPE); - sendOrder.getMessageType().add(mt4); - pd.getNode().add(sendOrder); - - return (pd); - } - - @Test - public void testConditionalSendValidOrderCreditCheckOk() { - Description pd=getSendDecisionProtocol(); - - // Create Protocol Monitor - ProtocolMonitor monitor=new DefaultProtocolMonitor(); - - DefaultMonitorContext context=new DefaultMonitorContext(); - - Session conv=monitor.createSession(context, pd, DefaultSession.class); - - DefaultMessage message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Receive Order failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CREDIT_CHECK_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Credit check failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CREDIT_OK_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Credit ok failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CONFIRMATION_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Send Confirmation failed"); - } - - if (conv.isFinished() == false) { - fail("Conversation should be finished"); - } - } - - @Test - public void testConditionalSendValidOrderConfirmation() { - Description pd=getSendDecisionProtocol(); - - // Create Protocol Monitor - ProtocolMonitor monitor=new DefaultProtocolMonitor(); - - DefaultMonitorContext context=new DefaultMonitorContext(); - - Session conv=monitor.createSession(context, pd, DefaultSession.class); - - DefaultMessage message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Receive Order failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CONFIRMATION_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Send Confirmation failed"); - } - - if (conv.isFinished() == false) { - fail("Conversation should be finished"); - } - } - - @Test - public void testConditionalSendValidOrderCreditCheckOkLookahead() { - Description pd=getSendDecisionProtocol(); - - // Create Protocol Monitor - ProtocolMonitor monitor=new DefaultProtocolMonitor(); - - DefaultMonitorContext context=new DefaultMonitorContext(); - - Session conv=monitor.createSession(context, pd, DefaultSession.class); - - DefaultMessage message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Receive Order failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CREDIT_CHECK_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Credit check failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CREDIT_OK_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Credit ok failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CONFIRMATION_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Send Confirmation failed"); - } - - if (conv.isFinished() == false) { - fail("Conversation should be finished"); - } - } - - @Test - public void testConditionalSendValidOrderConfirmationLookahead() { - Description pd=getSendDecisionProtocol(); - - // Create Protocol Monitor - ProtocolMonitor monitor=new DefaultProtocolMonitor(); - - DefaultMonitorContext context=new DefaultMonitorContext(); - - Session conv=monitor.createSession(context, pd, DefaultSession.class); - - DefaultMessage message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Receive Order failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CONFIRMATION_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Send Confirmation failed"); - } - - if (conv.isFinished() == false) { - fail("Conversation should be finished"); - } - } - - @Test - public void testConditionalSendInvalidOrderCreditCheckOk() { - Description pd=getSendDecisionProtocol(); - - // Create Protocol Monitor - ProtocolMonitor monitor=new DefaultProtocolMonitor(); - - DefaultMonitorContext context=new DefaultMonitorContext(); - - Session conv=monitor.createSession(context, pd, DefaultSession.class); - - DefaultMessage message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Receive Order failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == true) { - fail("Second order should have failed"); - } - - if (conv.isFinished() == true) { - fail("Conversation should NOT be finished"); - } - } - - @Test - public void testConditionalReceiveValidOrderCreditCheckOk() { - Description pd=getReceiveDecisionProtocol(); - - // Create Protocol Monitor - ProtocolMonitor monitor=new DefaultProtocolMonitor(); - - DefaultMonitorContext context=new DefaultMonitorContext(); - - Session conv=monitor.createSession(context, pd, DefaultSession.class); - - DefaultMessage message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Send Order failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CREDIT_CHECK_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Credit check failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CREDIT_OK_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Credit ok failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CONFIRMATION_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Confirmation failed"); - } - - if (conv.isFinished() == false) { - fail("Conversation should be finished"); - } - } - - @Test - public void testConditionalReceiveValidOrderConfirmation() { - Description pd=getReceiveDecisionProtocol(); - - // Create Protocol Monitor - ProtocolMonitor monitor=new DefaultProtocolMonitor(); - - DefaultMonitorContext context=new DefaultMonitorContext(); - - Session conv=monitor.createSession(context, pd, DefaultSession.class); - - DefaultMessage message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Order failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CONFIRMATION_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Confirmation failed"); - } - - if (conv.isFinished() == false) { - fail("Conversation should be finished"); - } - } - - @Test - public void testConditionalReceiveValidOrderCreditCheckOkLookahead() { - Description pd=getReceiveDecisionProtocol(); - - // Create Protocol Monitor - ProtocolMonitor monitor=new DefaultProtocolMonitor(); - - DefaultMonitorContext context=new DefaultMonitorContext(); - - Session conv=monitor.createSession(context, pd, DefaultSession.class); - - DefaultMessage message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Send Order failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CREDIT_CHECK_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Credit check failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CREDIT_OK_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Credit ok failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CONFIRMATION_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Confirmation failed"); - } - - if (conv.isFinished() == false) { - fail("Conversation should be finished"); - } - } - - @Test - public void testConditionalReceiveValidOrderConfirmationLookahead() { - Description pd=getReceiveDecisionProtocol(); - - // Create Protocol Monitor - ProtocolMonitor monitor=new DefaultProtocolMonitor(); - - DefaultMonitorContext context=new DefaultMonitorContext(); - - Session conv=monitor.createSession(context, pd, DefaultSession.class); - - DefaultMessage message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Send Order failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CONFIRMATION_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Receive Confirmation failed"); - } - - if (conv.isFinished() == false) { - fail("Conversation should be finished"); - } - } - - @Test - public void testConditionalReceiveInvalidOrderCreditCheckOk() { - Description pd=getReceiveDecisionProtocol(); - - // Create Protocol Monitor - ProtocolMonitor monitor=new DefaultProtocolMonitor(); - - DefaultMonitorContext context=new DefaultMonitorContext(); - - Session conv=monitor.createSession(context, pd, DefaultSession.class); - - DefaultMessage message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Send Order failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == true) { - fail("Second order should have failed"); - } - - if (conv.isFinished() == true) { - fail("Conversation should NOT be finished"); - } - } -} diff --git a/bundles/org.scribble.protocol.monitor/src/test/java/org/scribble/protocol/monitor/OptionalWithParticipantTest.java b/bundles/org.scribble.protocol.monitor/src/test/java/org/scribble/protocol/monitor/OptionalWithParticipantTest.java deleted file mode 100644 index 7a7c90984..000000000 --- a/bundles/org.scribble.protocol.monitor/src/test/java/org/scribble/protocol/monitor/OptionalWithParticipantTest.java +++ /dev/null @@ -1,499 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.monitor; - -import static org.junit.Assert.*; - -import org.junit.Test; -import org.scribble.protocol.monitor.model.*; - -public class OptionalWithParticipantTest { - - private static final String CREDIT_OK_MESSAGE_TYPE = "CreditOk"; - private static final String CREDIT_CHECK_MESSAGE_TYPE = "CreditCheck"; - private static final String ORDER_MESSAGE_TYPE = "Order"; - private static final String CONFIRMATION_MESSAGE_TYPE = "Confirmation"; - - public enum PurchasingLabel { - _CreditOk, - _InsufficientCredit, - _Confirmation, - _OutOfStock, - } - - public Description getSendDecisionProtocol() { - Description pd=new Description(); - - // 0 - ReceiveMessage recvOrder=new ReceiveMessage(); - //recvOrder.setNodeType(Protocol.Node.NodeType.ReceiveMessage); - recvOrder.setNextIndex(1); - - MessageType mt1=new MessageType(); - mt1.setValue(ORDER_MESSAGE_TYPE); - recvOrder.getMessageType().add(mt1); - pd.getNode().add(recvOrder); - - // 1 - Decision conditional=new Decision(); - //conditional.setNodeType(Protocol.Node.NodeType.SendDecision); - conditional.setNextIndex(4); - conditional.setInnerIndex(2); - //conditional.setOtherRole(OTHER_ROLE); - pd.getNode().add(conditional); - - // 2 - SendMessage sendCreditCheck=new SendMessage(); - //sendCreditCheck.setNodeType(Protocol.Node.NodeType.SendMessage); - sendCreditCheck.setNextIndex(3); - - MessageType mt2=new MessageType(); - mt2.setValue(CREDIT_CHECK_MESSAGE_TYPE); - sendCreditCheck.getMessageType().add(mt2); - pd.getNode().add(sendCreditCheck); - - // 3 - ReceiveMessage recvCreditOk=new ReceiveMessage(); - //recvCreditOk.setNodeType(Protocol.Node.NodeType.ReceiveMessage); - recvCreditOk.setNextIndex(4); - - MessageType mt3=new MessageType(); - mt3.setValue(CREDIT_OK_MESSAGE_TYPE); - recvCreditOk.getMessageType().add(mt3); - pd.getNode().add(recvCreditOk); - - // 4 - SendMessage sendOrder=new SendMessage(); - //sendOrder.setNodeType(Protocol.Node.NodeType.SendMessage); - - MessageType mt4=new MessageType(); - mt4.setValue(CONFIRMATION_MESSAGE_TYPE); - sendOrder.getMessageType().add(mt4); - pd.getNode().add(sendOrder); - - return (pd); - } - - public Description getReceiveDecisionProtocol() { - Description pd=new Description(); - - // 0 - SendMessage recvOrder=new SendMessage(); - //recvOrder.setNodeType(Protocol.Node.NodeType.SendMessage); - recvOrder.setNextIndex(1); - - MessageType mt1=new MessageType(); - mt1.setValue(ORDER_MESSAGE_TYPE); - recvOrder.getMessageType().add(mt1); - pd.getNode().add(recvOrder); - - // 1 - Decision conditional=new Decision(); - //conditional.setNodeType(Protocol.Node.NodeType.ReceiveDecision); - conditional.setNextIndex(4); - conditional.setInnerIndex(2); - //conditional.setOtherRole(OTHER_ROLE); - pd.getNode().add(conditional); - - // 2 - ReceiveMessage sendCreditCheck=new ReceiveMessage(); - //sendCreditCheck.setNodeType(Protocol.Node.NodeType.ReceiveMessage); - sendCreditCheck.setNextIndex(3); - - MessageType mt2=new MessageType(); - mt2.setValue(CREDIT_CHECK_MESSAGE_TYPE); - sendCreditCheck.getMessageType().add(mt2); - pd.getNode().add(sendCreditCheck); - - // 3 - SendMessage recvCreditOk=new SendMessage(); - //recvCreditOk.setNodeType(Protocol.Node.NodeType.SendMessage); - recvCreditOk.setNextIndex(4); - - MessageType mt3=new MessageType(); - mt3.setValue(CREDIT_OK_MESSAGE_TYPE); - recvCreditOk.getMessageType().add(mt3); - pd.getNode().add(recvCreditOk); - - // 4 - ReceiveMessage sendOrder=new ReceiveMessage(); - //sendOrder.setNodeType(Protocol.Node.NodeType.ReceiveMessage); - - MessageType mt4=new MessageType(); - mt4.setValue(CONFIRMATION_MESSAGE_TYPE); - sendOrder.getMessageType().add(mt4); - pd.getNode().add(sendOrder); - - return (pd); - } - - @Test - public void testConditionalSendValidOrderCreditCheckOk() { - Description pd=getSendDecisionProtocol(); - - // Create Protocol Monitor - ProtocolMonitor monitor=new DefaultProtocolMonitor(); - - DefaultMonitorContext context=new DefaultMonitorContext(); - - Session conv=monitor.createSession(context, pd, DefaultSession.class); - - DefaultMessage message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Receive Order failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CREDIT_CHECK_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Credit check failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CREDIT_OK_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Credit ok failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CONFIRMATION_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Send Confirmation failed"); - } - - if (conv.isFinished() == false) { - fail("Conversation should be finished"); - } - } - - @Test - public void testConditionalSendValidOrderConfirmation() { - Description pd=getSendDecisionProtocol(); - - // Create Protocol Monitor - ProtocolMonitor monitor=new DefaultProtocolMonitor(); - - DefaultMonitorContext context=new DefaultMonitorContext(); - - Session conv=monitor.createSession(context, pd, DefaultSession.class); - - DefaultMessage message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Receive Order failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CONFIRMATION_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Send Confirmation failed"); - } - - if (conv.isFinished() == false) { - fail("Conversation should be finished"); - } - } - - @Test - public void testConditionalSendValidOrderCreditCheckOkLookahead() { - Description pd=getSendDecisionProtocol(); - - // Create Protocol Monitor - ProtocolMonitor monitor=new DefaultProtocolMonitor(); - - DefaultMonitorContext context=new DefaultMonitorContext(); - - Session conv=monitor.createSession(context, pd, DefaultSession.class); - - DefaultMessage message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Receive Order failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CREDIT_CHECK_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Credit check failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CREDIT_OK_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Credit ok failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CONFIRMATION_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Send Confirmation failed"); - } - - if (conv.isFinished() == false) { - fail("Conversation should be finished"); - } - } - - @Test - public void testConditionalSendValidOrderConfirmationLookahead() { - Description pd=getSendDecisionProtocol(); - - // Create Protocol Monitor - ProtocolMonitor monitor=new DefaultProtocolMonitor(); - - DefaultMonitorContext context=new DefaultMonitorContext(); - - Session conv=monitor.createSession(context, pd, DefaultSession.class); - - DefaultMessage message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Receive Order failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CONFIRMATION_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Send Confirmation failed"); - } - - if (conv.isFinished() == false) { - fail("Conversation should be finished"); - } - } - - @Test - public void testConditionalSendInvalidOrderCreditCheckOkByDecision() { - Description pd=getSendDecisionProtocol(); - - // Create Protocol Monitor - ProtocolMonitor monitor=new DefaultProtocolMonitor(); - - DefaultMonitorContext context=new DefaultMonitorContext(); - - Session conv=monitor.createSession(context, pd, DefaultSession.class); - - DefaultMessage message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Receive Order failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == true) { - fail("Second order should have failed"); - } - - if (conv.isFinished() == true) { - fail("Conversation should NOT be finished"); - } - } - - @Test - public void testConditionalReceiveValidOrderCreditCheckOk() { - Description pd=getReceiveDecisionProtocol(); - - // Create Protocol Monitor - ProtocolMonitor monitor=new DefaultProtocolMonitor(); - - DefaultMonitorContext context=new DefaultMonitorContext(); - - Session conv=monitor.createSession(context, pd, DefaultSession.class); - - DefaultMessage message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Send Order failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CREDIT_CHECK_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Credit check failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CREDIT_OK_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Credit ok failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CONFIRMATION_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Confirmation failed"); - } - - if (conv.isFinished() == false) { - fail("Conversation should be finished"); - } - } - - @Test - public void testConditionalReceiveValidOrderConfirmation() { - Description pd=getReceiveDecisionProtocol(); - - // Create Protocol Monitor - ProtocolMonitor monitor=new DefaultProtocolMonitor(); - - DefaultMonitorContext context=new DefaultMonitorContext(); - - Session conv=monitor.createSession(context, pd, DefaultSession.class); - - DefaultMessage message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Order failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CONFIRMATION_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Confirmation failed"); - } - - if (conv.isFinished() == false) { - fail("Conversation should be finished"); - } - } - - @Test - public void testConditionalReceiveValidOrderCreditCheckOkLookahead() { - Description pd=getReceiveDecisionProtocol(); - - // Create Protocol Monitor - ProtocolMonitor monitor=new DefaultProtocolMonitor(); - - DefaultMonitorContext context=new DefaultMonitorContext(); - - Session conv=monitor.createSession(context, pd, DefaultSession.class); - - DefaultMessage message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Send Order failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CREDIT_CHECK_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Credit check failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CREDIT_OK_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Credit ok failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CONFIRMATION_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Confirmation failed"); - } - - if (conv.isFinished() == false) { - fail("Conversation should be finished"); - } - } - - @Test - public void testConditionalReceiveValidOrderConfirmationLookahead() { - Description pd=getReceiveDecisionProtocol(); - - // Create Protocol Monitor - ProtocolMonitor monitor=new DefaultProtocolMonitor(); - - DefaultMonitorContext context=new DefaultMonitorContext(); - - Session conv=monitor.createSession(context, pd, DefaultSession.class); - - DefaultMessage message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Send Order failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CONFIRMATION_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Receive Confirmation failed"); - } - - if (conv.isFinished() == false) { - fail("Conversation should be finished"); - } - } - - @Test - public void testConditionalReceiveInvalidOrderCreditCheckOkByDecision() { - Description pd=getReceiveDecisionProtocol(); - - // Create Protocol Monitor - ProtocolMonitor monitor=new DefaultProtocolMonitor(); - - DefaultMonitorContext context=new DefaultMonitorContext(); - - Session conv=monitor.createSession(context, pd, DefaultSession.class); - - DefaultMessage message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Send Order failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == true) { - fail("Second order should have failed"); - } - - if (conv.isFinished() == true) { - fail("Conversation should NOT be finished"); - } - } -} diff --git a/bundles/org.scribble.protocol.monitor/src/test/java/org/scribble/protocol/monitor/ParallelTest.java b/bundles/org.scribble.protocol.monitor/src/test/java/org/scribble/protocol/monitor/ParallelTest.java deleted file mode 100644 index 08fed43b7..000000000 --- a/bundles/org.scribble.protocol.monitor/src/test/java/org/scribble/protocol/monitor/ParallelTest.java +++ /dev/null @@ -1,165 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.monitor; - -import static org.junit.Assert.*; - -import org.junit.Test; -import org.scribble.protocol.monitor.model.*; - - -public class ParallelTest { - - private static final String OUT_OF_STOCK_MESSAGE_TYPE = "OutOfStock"; - private static final String CONFIRMATION_MESSAGE_TYPE = "Confirmation"; - private static final String ORDER_MESSAGE_TYPE = "Order"; - private static final String FINISH_MESSAGE_TYPE = "Finish"; - - public enum PurchasingLabel { - _Confirmation, - _OutOfStock - } - - public Description getSellerProtocol() { - Description pd=new Description(); - - ReceiveMessage recvOrder=new ReceiveMessage(); - recvOrder.setNextIndex(1); - - MessageType mt1=new MessageType(); - mt1.setValue(ORDER_MESSAGE_TYPE); - recvOrder.getMessageType().add(mt1); - pd.getNode().add(recvOrder); - - Parallel parallel=new Parallel(); - parallel.setNextIndex(4); - - Path c1=new Path(); - c1.setNextIndex(2); - parallel.getPath().add(c1); - - Path c2=new Path(); - c2.setNextIndex(3); - parallel.getPath().add(c2); - - pd.getNode().add(parallel); - - SendMessage sendConformation=new SendMessage(); - - MessageType mt2=new MessageType(); - mt2.setValue(CONFIRMATION_MESSAGE_TYPE); - sendConformation.getMessageType().add(mt2); - pd.getNode().add(sendConformation); - - SendMessage sendOutOfStock=new SendMessage(); - - MessageType mt3=new MessageType(); - mt3.setValue(OUT_OF_STOCK_MESSAGE_TYPE); - sendOutOfStock.getMessageType().add(mt3); - pd.getNode().add(sendOutOfStock); - - SendMessage sendFinish=new SendMessage(); - - MessageType mt4=new MessageType(); - mt4.setValue(FINISH_MESSAGE_TYPE); - sendFinish.getMessageType().add(mt4); - pd.getNode().add(sendFinish); - - return (pd); - } - - @Test - public void testValidCompletion() { - Description pd=getSellerProtocol(); - - // Create Protocol Monitor - ProtocolMonitor monitor=new DefaultProtocolMonitor(); - - DefaultMonitorContext context=new DefaultMonitorContext(); - - Session conv=monitor.createSession(context, pd, DefaultSession.class); - - DefaultMessage message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Order failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CONFIRMATION_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Confirmation failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(OUT_OF_STOCK_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Out Of Stock failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(FINISH_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Finish message failed"); - } - - if (conv.isFinished() == false) { - fail("Conversation should be finished"); - } - } - - @Test - public void testMissingOutOfStock() { - Description pd=getSellerProtocol(); - - // Create Protocol Monitor - ProtocolMonitor monitor=new DefaultProtocolMonitor(); - - DefaultMonitorContext context=new DefaultMonitorContext(); - - Session conv=monitor.createSession(context, pd, DefaultSession.class); - - DefaultMessage message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Order failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CONFIRMATION_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Confirmation failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(FINISH_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == true) { - fail("Finish message should have failed, as parallel should not have completed"); - } - - if (conv.isFinished() == true) { - fail("Conversation should NOT be finished"); - } - } -} diff --git a/bundles/org.scribble.protocol.monitor/src/test/java/org/scribble/protocol/monitor/ProtocolMonitorAllTests.java b/bundles/org.scribble.protocol.monitor/src/test/java/org/scribble/protocol/monitor/ProtocolMonitorAllTests.java deleted file mode 100644 index d1e1cadf7..000000000 --- a/bundles/org.scribble.protocol.monitor/src/test/java/org/scribble/protocol/monitor/ProtocolMonitorAllTests.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.monitor; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - -@RunWith(Suite.class) -@Suite.SuiteClasses( { BrokerParticipantTest.class, - BuyerParticipantTest.class, - CreditAgencyParticipantTest.class, - OptionalTest.class, - OptionalWithParticipantTest.class, - RepeatTest.class, - RepeatWithParticipantTest.class, - RunTest.class, - ParallelTest.class, - RunWithParticipantTest.class, - SellerParticipantTest.class}) -public class ProtocolMonitorAllTests { -} \ No newline at end of file diff --git a/bundles/org.scribble.protocol.monitor/src/test/java/org/scribble/protocol/monitor/RepeatTest.java b/bundles/org.scribble.protocol.monitor/src/test/java/org/scribble/protocol/monitor/RepeatTest.java deleted file mode 100644 index 6452c6a01..000000000 --- a/bundles/org.scribble.protocol.monitor/src/test/java/org/scribble/protocol/monitor/RepeatTest.java +++ /dev/null @@ -1,553 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.monitor; - -import static org.junit.Assert.*; - -import org.junit.Test; -import org.scribble.protocol.monitor.model.*; - -public class RepeatTest { - - private static final String CREDIT_OK_MESSAGE_TYPE = "CreditOk"; - private static final String CREDIT_CHECK_MESSAGE_TYPE = "CreditCheck"; - private static final String ORDER_MESSAGE_TYPE = "Order"; - private static final String CONFIRMATION_MESSAGE_TYPE = "Confirmation"; - - public enum PurchasingLabel { - _CreditOk, - _InsufficientCredit, - _Confirmation, - _OutOfStock, - } - - public Description getSendRepeatProtocol() { - Description pd=new Description(); - - // 0 - ReceiveMessage recvOrder=new ReceiveMessage(); - //recvOrder.setNodeType(Protocol.Node.NodeType.ReceiveMessage); - recvOrder.setNextIndex(1); - - MessageType mt1=new MessageType(); - mt1.setValue(ORDER_MESSAGE_TYPE); - recvOrder.getMessageType().add(mt1); - pd.getNode().add(recvOrder); - - // 1 - Decision conditional=new Decision(); - //conditional.setNodeType(Protocol.Node.NodeType.SendDecision); - conditional.setNextIndex(4); - conditional.setInnerIndex(2); - pd.getNode().add(conditional); - - // 2 - SendMessage sendCreditCheck=new SendMessage(); - //sendCreditCheck.setNodeType(Protocol.Node.NodeType.SendMessage); - sendCreditCheck.setNextIndex(3); - - MessageType mt2=new MessageType(); - mt2.setValue(CREDIT_CHECK_MESSAGE_TYPE); - sendCreditCheck.getMessageType().add(mt2); - pd.getNode().add(sendCreditCheck); - - // 3 - ReceiveMessage recvCreditOk=new ReceiveMessage(); - //recvCreditOk.setNodeType(Protocol.Node.NodeType.ReceiveMessage); - recvCreditOk.setNextIndex(1); - - MessageType mt3=new MessageType(); - mt3.setValue(CREDIT_OK_MESSAGE_TYPE); - recvCreditOk.getMessageType().add(mt3); - pd.getNode().add(recvCreditOk); - - // 4 - SendMessage sendOrder=new SendMessage(); - //sendOrder.setNodeType(Protocol.Node.NodeType.SendMessage); - - MessageType mt4=new MessageType(); - mt4.setValue(CONFIRMATION_MESSAGE_TYPE); - sendOrder.getMessageType().add(mt4); - pd.getNode().add(sendOrder); - - return (pd); - } - - public Description getReceiveRepeatProtocol() { - Description pd=new Description(); - - // 0 - SendMessage recvOrder=new SendMessage(); - //recvOrder.setNodeType(Protocol.Node.NodeType.SendMessage); - recvOrder.setNextIndex(1); - - MessageType mt1=new MessageType(); - mt1.setValue(ORDER_MESSAGE_TYPE); - recvOrder.getMessageType().add(mt1); - pd.getNode().add(recvOrder); - - // 1 - Decision conditional=new Decision(); - //conditional.setNodeType(Protocol.Node.NodeType.ReceiveDecision); - conditional.setNextIndex(4); - conditional.setInnerIndex(2); - pd.getNode().add(conditional); - - // 2 - ReceiveMessage sendCreditCheck=new ReceiveMessage(); - //sendCreditCheck.setNodeType(Protocol.Node.NodeType.ReceiveMessage); - sendCreditCheck.setNextIndex(3); - - MessageType mt2=new MessageType(); - mt2.setValue(CREDIT_CHECK_MESSAGE_TYPE); - sendCreditCheck.getMessageType().add(mt2); - pd.getNode().add(sendCreditCheck); - - // 3 - SendMessage recvCreditOk=new SendMessage(); - //recvCreditOk.setNodeType(Protocol.Node.NodeType.SendMessage); - recvCreditOk.setNextIndex(1); - - MessageType mt3=new MessageType(); - mt3.setValue(CREDIT_OK_MESSAGE_TYPE); - recvCreditOk.getMessageType().add(mt3); - pd.getNode().add(recvCreditOk); - - // 4 - ReceiveMessage sendOrder=new ReceiveMessage(); - //sendOrder.setNodeType(Protocol.Node.NodeType.ReceiveMessage); - - MessageType mt4=new MessageType(); - mt4.setValue(CONFIRMATION_MESSAGE_TYPE); - sendOrder.getMessageType().add(mt4); - pd.getNode().add(sendOrder); - - return (pd); - } - - @Test - public void testRepeatSendValidOrderCreditCheckOk() { - Description pd=getSendRepeatProtocol(); - - // Create Protocol Monitor - ProtocolMonitor monitor=new DefaultProtocolMonitor(); - - DefaultMonitorContext context=new DefaultMonitorContext(); - - Session conv=monitor.createSession(context, pd, DefaultSession.class); - - DefaultMessage message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Receive Order failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CREDIT_CHECK_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Credit check failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CREDIT_OK_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Credit ok failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CREDIT_CHECK_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Credit check failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CREDIT_OK_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Credit ok failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CONFIRMATION_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Send Confirmation failed"); - } - - if (conv.isFinished() == false) { - fail("Conversation should be finished"); - } - } - - @Test - public void testRepeatSendValidOrderConfirmation() { - Description pd=getSendRepeatProtocol(); - - // Create Protocol Monitor - ProtocolMonitor monitor=new DefaultProtocolMonitor(); - - DefaultMonitorContext context=new DefaultMonitorContext(); - - Session conv=monitor.createSession(context, pd, DefaultSession.class); - - DefaultMessage message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Receive Order failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CONFIRMATION_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Send Confirmation failed"); - } - - if (conv.isFinished() == false) { - fail("Conversation should be finished"); - } - } - - @Test - public void testRepeatSendValidOrderCreditCheckOkLookahead() { - Description pd=getSendRepeatProtocol(); - - // Create Protocol Monitor - ProtocolMonitor monitor=new DefaultProtocolMonitor(); - - DefaultMonitorContext context=new DefaultMonitorContext(); - - Session conv=monitor.createSession(context, pd, DefaultSession.class); - - DefaultMessage message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Receive Order failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CREDIT_CHECK_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Credit check failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CREDIT_OK_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Credit ok failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CREDIT_CHECK_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Credit check failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CREDIT_OK_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Credit ok failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CONFIRMATION_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Send Confirmation failed"); - } - - if (conv.isFinished() == false) { - fail("Conversation should be finished"); - } - } - - @Test - public void testRepeatSendValidOrderConfirmationLookahead() { - Description pd=getSendRepeatProtocol(); - - // Create Protocol Monitor - ProtocolMonitor monitor=new DefaultProtocolMonitor(); - - DefaultMonitorContext context=new DefaultMonitorContext(); - - Session conv=monitor.createSession(context, pd, DefaultSession.class); - - DefaultMessage message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Receive Order failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CONFIRMATION_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Send Confirmation failed"); - } - - if (conv.isFinished() == false) { - fail("Conversation should be finished"); - } - } - - @Test - public void testRepeatSendInvalidOrderCreditCheckOk() { - Description pd=getSendRepeatProtocol(); - - // Create Protocol Monitor - ProtocolMonitor monitor=new DefaultProtocolMonitor(); - - DefaultMonitorContext context=new DefaultMonitorContext(); - - Session conv=monitor.createSession(context, pd, DefaultSession.class); - - DefaultMessage message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Receive Order failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CREDIT_OK_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == true) { - fail("Credit ok should have failed"); - } - - if (conv.isFinished() == true) { - fail("Conversation should NOT be finished"); - } - } - - @Test - public void testRepeatReceiveValidOrderCreditCheckOk() { - Description pd=getReceiveRepeatProtocol(); - - // Create Protocol Monitor - ProtocolMonitor monitor=new DefaultProtocolMonitor(); - - DefaultMonitorContext context=new DefaultMonitorContext(); - - Session conv=monitor.createSession(context, pd, DefaultSession.class); - - DefaultMessage message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Send Order failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CREDIT_CHECK_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Credit check failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CREDIT_OK_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Credit ok failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CREDIT_CHECK_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Credit check failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CREDIT_OK_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Credit ok failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CONFIRMATION_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Confirmation failed"); - } - - if (conv.isFinished() == false) { - fail("Conversation should be finished"); - } - } - - @Test - public void testRepeatReceiveValidOrderConfirmation() { - Description pd=getReceiveRepeatProtocol(); - - // Create Protocol Monitor - ProtocolMonitor monitor=new DefaultProtocolMonitor(); - - DefaultMonitorContext context=new DefaultMonitorContext(); - - Session conv=monitor.createSession(context, pd, DefaultSession.class); - - DefaultMessage message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Order failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CONFIRMATION_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Confirmation failed"); - } - - if (conv.isFinished() == false) { - fail("Conversation should be finished"); - } - } - - @Test - public void testRepeatReceiveValidOrderCreditCheckOkLookahead() { - Description pd=getReceiveRepeatProtocol(); - - // Create Protocol Monitor - ProtocolMonitor monitor=new DefaultProtocolMonitor(); - - DefaultMonitorContext context=new DefaultMonitorContext(); - - Session conv=monitor.createSession(context, pd, DefaultSession.class); - - DefaultMessage message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Send Order failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CREDIT_CHECK_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Credit check failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CREDIT_OK_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Credit ok failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CREDIT_CHECK_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Credit check failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CREDIT_OK_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Credit ok failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CONFIRMATION_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Confirmation failed"); - } - - if (conv.isFinished() == false) { - fail("Conversation should be finished"); - } - } - - @Test - public void testRepeatReceiveValidOrderConfirmationLookahead() { - Description pd=getReceiveRepeatProtocol(); - - // Create Protocol Monitor - ProtocolMonitor monitor=new DefaultProtocolMonitor(); - - DefaultMonitorContext context=new DefaultMonitorContext(); - - Session conv=monitor.createSession(context, pd, DefaultSession.class); - - DefaultMessage message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Send Order failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CONFIRMATION_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Receive Confirmation failed"); - } - - if (conv.isFinished() == false) { - fail("Conversation should be finished"); - } - } - - @Test - public void testRepeatReceiveInvalidOrderCreditCheckOk() { - Description pd=getReceiveRepeatProtocol(); - - // Create Protocol Monitor - ProtocolMonitor monitor=new DefaultProtocolMonitor(); - - DefaultMonitorContext context=new DefaultMonitorContext(); - - Session conv=monitor.createSession(context, pd, DefaultSession.class); - - DefaultMessage message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Send Order failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CREDIT_OK_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == true) { - fail("Credit ok should have failed"); - } - - if (conv.isFinished() == true) { - fail("Conversation should NOT be finished"); - } - } -} diff --git a/bundles/org.scribble.protocol.monitor/src/test/java/org/scribble/protocol/monitor/RepeatWithParticipantTest.java b/bundles/org.scribble.protocol.monitor/src/test/java/org/scribble/protocol/monitor/RepeatWithParticipantTest.java deleted file mode 100644 index e001d3854..000000000 --- a/bundles/org.scribble.protocol.monitor/src/test/java/org/scribble/protocol/monitor/RepeatWithParticipantTest.java +++ /dev/null @@ -1,555 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.monitor; - -import static org.junit.Assert.*; - -import org.junit.Test; -import org.scribble.protocol.monitor.model.*; - -public class RepeatWithParticipantTest { - - private static final String CREDIT_OK_MESSAGE_TYPE = "CreditOk"; - private static final String CREDIT_CHECK_MESSAGE_TYPE = "CreditCheck"; - private static final String ORDER_MESSAGE_TYPE = "Order"; - private static final String CONFIRMATION_MESSAGE_TYPE = "Confirmation"; - - public enum PurchasingLabel { - _CreditOk, - _InsufficientCredit, - _Confirmation, - _OutOfStock, - } - - public Description getSendRepeatProtocol() { - Description pd=new Description(); - - // 0 - ReceiveMessage recvOrder=new ReceiveMessage(); - //recvOrder.setNodeType(Protocol.Node.NodeType.ReceiveMessage); - recvOrder.setNextIndex(1); - - MessageType mt1=new MessageType(); - mt1.setValue(ORDER_MESSAGE_TYPE); - recvOrder.getMessageType().add(mt1); - pd.getNode().add(recvOrder); - - // 1 - Decision conditional=new Decision(); - //conditional.setNodeType(Protocol.Node.NodeType.SendDecision); - conditional.setNextIndex(4); - conditional.setInnerIndex(2); - //conditional.setOtherRole(OTHER_ROLE); - pd.getNode().add(conditional); - - // 2 - SendMessage sendCreditCheck=new SendMessage(); - //sendCreditCheck.setNodeType(Protocol.Node.NodeType.SendMessage); - sendCreditCheck.setNextIndex(3); - - MessageType mt2=new MessageType(); - mt2.setValue(CREDIT_CHECK_MESSAGE_TYPE); - sendCreditCheck.getMessageType().add(mt2); - pd.getNode().add(sendCreditCheck); - - // 3 - ReceiveMessage recvCreditOk=new ReceiveMessage(); - //recvCreditOk.setNodeType(Protocol.Node.NodeType.ReceiveMessage); - recvCreditOk.setNextIndex(1); - - MessageType mt3=new MessageType(); - mt3.setValue(CREDIT_OK_MESSAGE_TYPE); - recvCreditOk.getMessageType().add(mt3); - pd.getNode().add(recvCreditOk); - - // 4 - SendMessage sendOrder=new SendMessage(); - //sendOrder.setNodeType(Protocol.Node.NodeType.SendMessage); - - MessageType mt4=new MessageType(); - mt4.setValue(CONFIRMATION_MESSAGE_TYPE); - sendOrder.getMessageType().add(mt4); - pd.getNode().add(sendOrder); - - return (pd); - } - - public Description getReceiveRepeatProtocol() { - Description pd=new Description(); - - // 0 - SendMessage recvOrder=new SendMessage(); - //recvOrder.setNodeType(Protocol.Node.NodeType.SendMessage); - recvOrder.setNextIndex(1); - - MessageType mt1=new MessageType(); - mt1.setValue(ORDER_MESSAGE_TYPE); - recvOrder.getMessageType().add(mt1); - pd.getNode().add(recvOrder); - - // 1 - Decision conditional=new Decision(); - //conditional.setNodeType(Protocol.Node.NodeType.ReceiveDecision); - conditional.setNextIndex(4); - conditional.setInnerIndex(2); - //conditional.setOtherRole(OTHER_ROLE); - pd.getNode().add(conditional); - - // 2 - ReceiveMessage sendCreditCheck=new ReceiveMessage(); - //sendCreditCheck.setNodeType(Protocol.Node.NodeType.ReceiveMessage); - sendCreditCheck.setNextIndex(3); - - MessageType mt2=new MessageType(); - mt2.setValue(CREDIT_CHECK_MESSAGE_TYPE); - sendCreditCheck.getMessageType().add(mt2); - pd.getNode().add(sendCreditCheck); - - // 3 - SendMessage recvCreditOk=new SendMessage(); - //recvCreditOk.setNodeType(Protocol.Node.NodeType.SendMessage); - recvCreditOk.setNextIndex(1); - - MessageType mt3=new MessageType(); - mt3.setValue(CREDIT_OK_MESSAGE_TYPE); - recvCreditOk.getMessageType().add(mt3); - pd.getNode().add(recvCreditOk); - - // 4 - ReceiveMessage sendOrder=new ReceiveMessage(); - //sendOrder.setNodeType(Protocol.Node.NodeType.ReceiveMessage); - - MessageType mt4=new MessageType(); - mt4.setValue(CONFIRMATION_MESSAGE_TYPE); - sendOrder.getMessageType().add(mt4); - pd.getNode().add(sendOrder); - - return (pd); - } - - @Test - public void testRepeatSendValidOrderCreditCheckOk() { - Description pd=getSendRepeatProtocol(); - - // Create Protocol Monitor - ProtocolMonitor monitor=new DefaultProtocolMonitor(); - - DefaultMonitorContext context=new DefaultMonitorContext(); - - Session conv=monitor.createSession(context, pd, DefaultSession.class); - - DefaultMessage message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Receive Order failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CREDIT_CHECK_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Credit check failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CREDIT_OK_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Credit ok failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CREDIT_CHECK_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Credit check failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CREDIT_OK_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Credit ok failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CONFIRMATION_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Send Confirmation failed"); - } - - if (conv.isFinished() == false) { - fail("Conversation should be finished"); - } - } - - @Test - public void testRepeatSendValidOrderConfirmation() { - Description pd=getSendRepeatProtocol(); - - // Create Protocol Monitor - ProtocolMonitor monitor=new DefaultProtocolMonitor(); - - DefaultMonitorContext context=new DefaultMonitorContext(); - - Session conv=monitor.createSession(context, pd, DefaultSession.class); - - DefaultMessage message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Receive Order failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CONFIRMATION_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Send Confirmation failed"); - } - - if (conv.isFinished() == false) { - fail("Conversation should be finished"); - } - } - - @Test - public void testRepeatSendValidOrderCreditCheckOkLookahead() { - Description pd=getSendRepeatProtocol(); - - // Create Protocol Monitor - ProtocolMonitor monitor=new DefaultProtocolMonitor(); - - DefaultMonitorContext context=new DefaultMonitorContext(); - - Session conv=monitor.createSession(context, pd, DefaultSession.class); - - DefaultMessage message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Receive Order failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CREDIT_CHECK_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Credit check failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CREDIT_OK_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Credit ok failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CREDIT_CHECK_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Credit check failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CREDIT_OK_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Credit ok failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CONFIRMATION_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Send Confirmation failed"); - } - - if (conv.isFinished() == false) { - fail("Conversation should be finished"); - } - } - - @Test - public void testRepeatSendValidOrderConfirmationLookahead() { - Description pd=getSendRepeatProtocol(); - - // Create Protocol Monitor - ProtocolMonitor monitor=new DefaultProtocolMonitor(); - - DefaultMonitorContext context=new DefaultMonitorContext(); - - Session conv=monitor.createSession(context, pd, DefaultSession.class); - - DefaultMessage message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Receive Order failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CONFIRMATION_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Send Confirmation failed"); - } - - if (conv.isFinished() == false) { - fail("Conversation should be finished"); - } - } - - @Test - public void testRepeatSendInvalidOrderCreditCheckOkByDecision() { - Description pd=getSendRepeatProtocol(); - - // Create Protocol Monitor - ProtocolMonitor monitor=new DefaultProtocolMonitor(); - - DefaultMonitorContext context=new DefaultMonitorContext(); - - Session conv=monitor.createSession(context, pd, DefaultSession.class); - - DefaultMessage message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Receive Order failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == true) { - fail("Second order should have failed"); - } - - if (conv.isFinished() == true) { - fail("Conversation should NOT be finished"); - } - } - - @Test - public void testRepeatReceiveValidOrderCreditCheckOk() { - Description pd=getReceiveRepeatProtocol(); - - // Create Protocol Monitor - ProtocolMonitor monitor=new DefaultProtocolMonitor(); - - DefaultMonitorContext context=new DefaultMonitorContext(); - - Session conv=monitor.createSession(context, pd, DefaultSession.class); - - DefaultMessage message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Send Order failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CREDIT_CHECK_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Credit check failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CREDIT_OK_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Credit ok failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CREDIT_CHECK_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Credit check failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CREDIT_OK_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Credit ok failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CONFIRMATION_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Confirmation failed"); - } - - if (conv.isFinished() == false) { - fail("Conversation should be finished"); - } - } - - @Test - public void testRepeatReceiveValidOrderConfirmation() { - Description pd=getReceiveRepeatProtocol(); - - // Create Protocol Monitor - ProtocolMonitor monitor=new DefaultProtocolMonitor(); - - DefaultMonitorContext context=new DefaultMonitorContext(); - - Session conv=monitor.createSession(context, pd, DefaultSession.class); - - DefaultMessage message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Order failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CONFIRMATION_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Confirmation failed"); - } - - if (conv.isFinished() == false) { - fail("Conversation should be finished"); - } - } - - @Test - public void testRepeatReceiveValidOrderCreditCheckOkLookahead() { - Description pd=getReceiveRepeatProtocol(); - - // Create Protocol Monitor - ProtocolMonitor monitor=new DefaultProtocolMonitor(); - - DefaultMonitorContext context=new DefaultMonitorContext(); - - Session conv=monitor.createSession(context, pd, DefaultSession.class); - - DefaultMessage message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Send Order failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CREDIT_CHECK_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Credit check failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CREDIT_OK_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Credit ok failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CREDIT_CHECK_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Credit check failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CREDIT_OK_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Credit ok failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CONFIRMATION_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Confirmation failed"); - } - - if (conv.isFinished() == false) { - fail("Conversation should be finished"); - } - } - - @Test - public void testRepeatReceiveValidOrderConfirmationLookahead() { - Description pd=getReceiveRepeatProtocol(); - - // Create Protocol Monitor - ProtocolMonitor monitor=new DefaultProtocolMonitor(); - - DefaultMonitorContext context=new DefaultMonitorContext(); - - Session conv=monitor.createSession(context, pd, DefaultSession.class); - - DefaultMessage message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Send Order failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CONFIRMATION_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Receive Confirmation failed"); - } - - if (conv.isFinished() == false) { - fail("Conversation should be finished"); - } - } - - @Test - public void testRepeatReceiveInvalidOrderCreditCheckOkByDecision() { - Description pd=getReceiveRepeatProtocol(); - - // Create Protocol Monitor - ProtocolMonitor monitor=new DefaultProtocolMonitor(); - - DefaultMonitorContext context=new DefaultMonitorContext(); - - Session conv=monitor.createSession(context, pd, DefaultSession.class); - - DefaultMessage message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Send Order failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == true) { - fail("Second order should have failed"); - } - - if (conv.isFinished() == true) { - fail("Conversation should NOT be finished"); - } - } -} diff --git a/bundles/org.scribble.protocol.monitor/src/test/java/org/scribble/protocol/monitor/RunTest.java b/bundles/org.scribble.protocol.monitor/src/test/java/org/scribble/protocol/monitor/RunTest.java deleted file mode 100644 index e35ef7394..000000000 --- a/bundles/org.scribble.protocol.monitor/src/test/java/org/scribble/protocol/monitor/RunTest.java +++ /dev/null @@ -1,300 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.monitor; - -import static org.junit.Assert.*; - -import org.junit.Test; -import org.scribble.protocol.monitor.model.*; - -public class RunTest { - - private static final String CREDIT_OK_MESSAGE_TYPE = "CreditOk"; - private static final String CREDIT_CHECK_MESSAGE_TYPE = "CreditCheck"; - private static final String ORDER_MESSAGE_TYPE = "Order"; - private static final String CONFIRMATION_MESSAGE_TYPE = "Confirmation"; - - public enum PurchasingLabel { - _CreditOk, - _InsufficientCredit, - _Confirmation, - _OutOfStock, - } - - public Description getSendProtocol() { - Description pd=new Description(); - - // 0 - ReceiveMessage recvOrder=new ReceiveMessage(); - //recvOrder.setNodeType(Protocol.Node.NodeType.ReceiveMessage); - recvOrder.setNextIndex(1); - - MessageType mt1=new MessageType(); - mt1.setValue(ORDER_MESSAGE_TYPE); - recvOrder.getMessageType().add(mt1); - pd.getNode().add(recvOrder); - - // 1 - Scope run=new Scope(); - //run.setNodeType(Protocol.Node.NodeType.Run); - run.setNextIndex(2); - run.setInnerIndex(3); - pd.getNode().add(run); - - // 2 - SendMessage sendOrder=new SendMessage(); - //sendOrder.setNodeType(Protocol.Node.NodeType.SendMessage); - - MessageType mt2=new MessageType(); - mt2.setValue(CONFIRMATION_MESSAGE_TYPE); - sendOrder.getMessageType().add(mt2); - pd.getNode().add(sendOrder); - - // 3 - SendMessage sendCreditCheck=new SendMessage(); - //sendCreditCheck.setNodeType(Protocol.Node.NodeType.SendMessage); - sendCreditCheck.setNextIndex(4); - - MessageType mt3=new MessageType(); - mt3.setValue(CREDIT_CHECK_MESSAGE_TYPE); - sendCreditCheck.getMessageType().add(mt3); - pd.getNode().add(sendCreditCheck); - - // 4 - ReceiveMessage recvCreditOk=new ReceiveMessage(); - //recvCreditOk.setNodeType(Protocol.Node.NodeType.ReceiveMessage); - - MessageType mt4=new MessageType(); - mt4.setValue(CREDIT_OK_MESSAGE_TYPE); - recvCreditOk.getMessageType().add(mt4); - pd.getNode().add(recvCreditOk); - - return (pd); - } - - public Description getReceiveProtocol() { - Description pd=new Description(); - - // 0 - SendMessage recvOrder=new SendMessage(); - //recvOrder.setNodeType(Protocol.Node.NodeType.SendMessage); - recvOrder.setNextIndex(1); - - MessageType mt1=new MessageType(); - mt1.setValue(ORDER_MESSAGE_TYPE); - recvOrder.getMessageType().add(mt1); - pd.getNode().add(recvOrder); - - // 1 - Scope run=new Scope(); - //run.setNodeType(Protocol.Node.NodeType.Run); - run.setNextIndex(2); - run.setInnerIndex(3); - pd.getNode().add(run); - - // 2 - ReceiveMessage sendOrder=new ReceiveMessage(); - //sendOrder.setNodeType(Protocol.Node.NodeType.ReceiveMessage); - - MessageType mt2=new MessageType(); - mt2.setValue(CONFIRMATION_MESSAGE_TYPE); - sendOrder.getMessageType().add(mt2); - pd.getNode().add(sendOrder); - - // 3 - ReceiveMessage sendCreditCheck=new ReceiveMessage(); - //sendCreditCheck.setNodeType(Protocol.Node.NodeType.ReceiveMessage); - sendCreditCheck.setNextIndex(4); - - MessageType mt3=new MessageType(); - mt3.setValue(CREDIT_CHECK_MESSAGE_TYPE); - sendCreditCheck.getMessageType().add(mt3); - pd.getNode().add(sendCreditCheck); - - // 4 - SendMessage recvCreditOk=new SendMessage(); - //recvCreditOk.setNodeType(Protocol.Node.NodeType.SendMessage); - - MessageType mt4=new MessageType(); - mt4.setValue(CREDIT_OK_MESSAGE_TYPE); - recvCreditOk.getMessageType().add(mt4); - pd.getNode().add(recvCreditOk); - - return (pd); - } - - @Test - public void testRunSendValidOrderCreditCheckOk() { - Description pd=getSendProtocol(); - - // Create Protocol Monitor - ProtocolMonitor monitor=new DefaultProtocolMonitor(); - - DefaultMonitorContext context=new DefaultMonitorContext(); - - Session conv=monitor.createSession(context, pd, DefaultSession.class); - - DefaultMessage message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Receive Order failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CREDIT_CHECK_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Credit check failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CREDIT_OK_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Credit ok failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CONFIRMATION_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Send Confirmation failed"); - } - - if (conv.isFinished() == false) { - fail("Conversation should be finished"); - } - } - - @Test - public void testRunSendInvalidOrderCreditCheckOk() { - Description pd=getSendProtocol(); - - // Create Protocol Monitor - ProtocolMonitor monitor=new DefaultProtocolMonitor(); - - DefaultMonitorContext context=new DefaultMonitorContext(); - - Session conv=monitor.createSession(context, pd, DefaultSession.class); - - DefaultMessage message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Receive Order failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CREDIT_CHECK_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Credit check failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CONFIRMATION_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == true) { - fail("Send Confirmation should have failed"); - } - - if (conv.isFinished() == true) { - fail("Conversation should NOT be finished"); - } - } - @Test - public void testRunReceiveValidOrderCreditCheckOk() { - Description pd=getReceiveProtocol(); - - // Create Protocol Monitor - ProtocolMonitor monitor=new DefaultProtocolMonitor(); - - DefaultMonitorContext context=new DefaultMonitorContext(); - - Session conv=monitor.createSession(context, pd, DefaultSession.class); - - DefaultMessage message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Send Order failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CREDIT_CHECK_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Credit check failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CREDIT_OK_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Credit ok failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CONFIRMATION_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Receive Confirmation failed"); - } - - if (conv.isFinished() == false) { - fail("Conversation should be finished"); - } - } - - @Test - public void testRunReceiveInvalidOrderCreditCheckOk() { - Description pd=getReceiveProtocol(); - - // Create Protocol Monitor - ProtocolMonitor monitor=new DefaultProtocolMonitor(); - - DefaultMonitorContext context=new DefaultMonitorContext(); - - Session conv=monitor.createSession(context, pd, DefaultSession.class); - - DefaultMessage message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Send Order failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CREDIT_CHECK_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Credit check failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CONFIRMATION_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == true) { - fail("Receive Confirmation should have failed"); - } - - if (conv.isFinished() == true) { - fail("Conversation should NOT be finished"); - } - } -} diff --git a/bundles/org.scribble.protocol.monitor/src/test/java/org/scribble/protocol/monitor/RunWithParticipantTest.java b/bundles/org.scribble.protocol.monitor/src/test/java/org/scribble/protocol/monitor/RunWithParticipantTest.java deleted file mode 100644 index 0aefa1761..000000000 --- a/bundles/org.scribble.protocol.monitor/src/test/java/org/scribble/protocol/monitor/RunWithParticipantTest.java +++ /dev/null @@ -1,302 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.monitor; - -import static org.junit.Assert.*; - -import org.junit.Test; -import org.scribble.protocol.monitor.model.*; - -public class RunWithParticipantTest { - - private static final String CREDIT_OK_MESSAGE_TYPE = "CreditOk"; - private static final String CREDIT_CHECK_MESSAGE_TYPE = "CreditCheck"; - private static final String ORDER_MESSAGE_TYPE = "Order"; - private static final String CONFIRMATION_MESSAGE_TYPE = "Confirmation"; - - public enum PurchasingLabel { - _CreditOk, - _InsufficientCredit, - _Confirmation, - _OutOfStock, - } - - public Description getSendProtocol() { - Description pd=new Description(); - - // 0 - ReceiveMessage recvOrder=new ReceiveMessage(); - //recvOrder.setNodeType(Protocol.Node.NodeType.ReceiveMessage); - recvOrder.setNextIndex(1); - - MessageType mt1=new MessageType(); - mt1.setValue(ORDER_MESSAGE_TYPE); - recvOrder.getMessageType().add(mt1); - pd.getNode().add(recvOrder); - - // 1 - Scope run=new Scope(); - //run.setNodeType(Protocol.Node.NodeType.Run); - run.setNextIndex(2); - run.setInnerIndex(3); - pd.getNode().add(run); - - // 2 - SendMessage sendOrder=new SendMessage(); - //sendOrder.setNodeType(Protocol.Node.NodeType.SendMessage); - - MessageType mt2=new MessageType(); - mt2.setValue(CONFIRMATION_MESSAGE_TYPE); - sendOrder.getMessageType().add(mt2); - pd.getNode().add(sendOrder); - - // 3 - SendMessage sendCreditCheck=new SendMessage(); - //sendCreditCheck.setNodeType(Protocol.Node.NodeType.SendMessage); - sendCreditCheck.setNextIndex(4); - - MessageType mt3=new MessageType(); - mt3.setValue(CREDIT_CHECK_MESSAGE_TYPE); - sendCreditCheck.getMessageType().add(mt3); - pd.getNode().add(sendCreditCheck); - - // 4 - ReceiveMessage recvCreditOk=new ReceiveMessage(); - //recvCreditOk.setNodeType(Protocol.Node.NodeType.ReceiveMessage); - - MessageType mt4=new MessageType(); - mt4.setValue(CREDIT_OK_MESSAGE_TYPE); - recvCreditOk.getMessageType().add(mt4); - pd.getNode().add(recvCreditOk); - - return (pd); - } - - public Description getReceiveProtocol() { - Description pd=new Description(); - - // 0 - SendMessage recvOrder=new SendMessage(); - //recvOrder.setNodeType(Protocol.Node.NodeType.SendMessage); - recvOrder.setNextIndex(1); - - MessageType mt1=new MessageType(); - mt1.setValue(ORDER_MESSAGE_TYPE); - recvOrder.getMessageType().add(mt1); - pd.getNode().add(recvOrder); - - // 1 - Scope run=new Scope(); - //run.setNodeType(Protocol.Node.NodeType.Run); - run.setNextIndex(2); - run.setInnerIndex(3); - pd.getNode().add(run); - - // 2 - ReceiveMessage sendOrder=new ReceiveMessage(); - //sendOrder.setNodeType(Protocol.Node.NodeType.ReceiveMessage); - - MessageType mt2=new MessageType(); - mt2.setValue(CONFIRMATION_MESSAGE_TYPE); - sendOrder.getMessageType().add(mt2); - pd.getNode().add(sendOrder); - - // 3 - ReceiveMessage sendCreditCheck=new ReceiveMessage(); - //sendCreditCheck.setNodeType(Protocol.Node.NodeType.ReceiveMessage); - sendCreditCheck.setNextIndex(4); - - MessageType mt3=new MessageType(); - mt3.setValue(CREDIT_CHECK_MESSAGE_TYPE); - sendCreditCheck.getMessageType().add(mt3); - pd.getNode().add(sendCreditCheck); - - // 4 - SendMessage recvCreditOk=new SendMessage(); - //recvCreditOk.setNodeType(Protocol.Node.NodeType.SendMessage); - - MessageType mt4=new MessageType(); - mt4.setValue(CREDIT_OK_MESSAGE_TYPE); - recvCreditOk.getMessageType().add(mt4); - pd.getNode().add(recvCreditOk); - - return (pd); - } - - @Test - public void testRunSendValidOrderCreditCheckOk() { - Description pd=getSendProtocol(); - - // Create Protocol Monitor - ProtocolMonitor monitor=new DefaultProtocolMonitor(); - - DefaultMonitorContext context=new DefaultMonitorContext(); - - Session conv=monitor.createSession(context, pd, DefaultSession.class); - - DefaultMessage message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Receive Order failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CREDIT_CHECK_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Credit check failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CREDIT_OK_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Credit ok failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CONFIRMATION_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Send Confirmation failed"); - } - - if (conv.isFinished() == false) { - fail("Conversation should be finished"); - } - } - - @Test - public void testRunSendInvalidOrderCreditCheckOkByMissingMessage() { - Description pd=getSendProtocol(); - - // Create Protocol Monitor - ProtocolMonitor monitor=new DefaultProtocolMonitor(); - - DefaultMonitorContext context=new DefaultMonitorContext(); - - Session conv=monitor.createSession(context, pd, DefaultSession.class); - - DefaultMessage message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Receive Order failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CREDIT_CHECK_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Credit check failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CONFIRMATION_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == true) { - fail("Send Confirmation should have failed"); - } - - if (conv.isFinished() == true) { - fail("Conversation should NOT be finished"); - } - } - - @Test - public void testRunReceiveValidOrderCreditCheckOk() { - Description pd=getReceiveProtocol(); - - // Create Protocol Monitor - ProtocolMonitor monitor=new DefaultProtocolMonitor(); - - DefaultMonitorContext context=new DefaultMonitorContext(); - - Session conv=monitor.createSession(context, pd, DefaultSession.class); - - DefaultMessage message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Send Order failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CREDIT_CHECK_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Credit check failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CREDIT_OK_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Credit ok failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CONFIRMATION_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Receive Confirmation failed"); - } - - if (conv.isFinished() == false) { - fail("Conversation should be finished"); - } - } - - @Test - public void testRunReceiveInvalidOrderCreditCheckOkByMissingMessage() { - Description pd=getReceiveProtocol(); - - // Create Protocol Monitor - ProtocolMonitor monitor=new DefaultProtocolMonitor(); - - DefaultMonitorContext context=new DefaultMonitorContext(); - - Session conv=monitor.createSession(context, pd, DefaultSession.class); - - DefaultMessage message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Send Order failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CREDIT_CHECK_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Credit check failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CONFIRMATION_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == true) { - fail("Receive Confirmation should have failed"); - } - - if (conv.isFinished() == true) { - fail("Conversation should NOT be finished"); - } - } - -} diff --git a/bundles/org.scribble.protocol.monitor/src/test/java/org/scribble/protocol/monitor/SellerParticipantTest.java b/bundles/org.scribble.protocol.monitor/src/test/java/org/scribble/protocol/monitor/SellerParticipantTest.java deleted file mode 100644 index 10df6fcd5..000000000 --- a/bundles/org.scribble.protocol.monitor/src/test/java/org/scribble/protocol/monitor/SellerParticipantTest.java +++ /dev/null @@ -1,171 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.monitor; - -import static org.junit.Assert.*; - -import org.junit.Test; -import org.scribble.protocol.monitor.model.*; - - -public class SellerParticipantTest { - - private static final String OUT_OF_STOCK_MESSAGE_TYPE = "OutOfStock"; - private static final String CONFIRMATION_MESSAGE_TYPE = "Confirmation"; - private static final String ORDER_MESSAGE_TYPE = "Order"; - - public enum PurchasingLabel { - _Confirmation, - _OutOfStock - } - - public Description getSellerProtocol() { - Description pd=new Description(); - - ReceiveMessage recvOrder=new ReceiveMessage(); - //recvOrder.setNodeType(Protocol.Node.NodeType.ReceiveMessage); - recvOrder.setNextIndex(1); - - MessageType mt1=new MessageType(); - mt1.setValue(ORDER_MESSAGE_TYPE); - recvOrder.getMessageType().add(mt1); - pd.getNode().add(recvOrder); - - Choice choice=new Choice(); - //choice.setNodeType(Protocol.Node.NodeType.SendChoice); - - Path c1=new Path(); - //c1.setId(PurchasingLabel._Confirmation.name()); - c1.setNextIndex(2); - choice.getPath().add(c1); - - Path c2=new Path(); - //c2.setId(PurchasingLabel._OutOfStock.name()); - c2.setNextIndex(3); - choice.getPath().add(c2); - - pd.getNode().add(choice); - - SendMessage sendConformation=new SendMessage(); - //sendConformation.setNodeType(Protocol.Node.NodeType.SendMessage); - - MessageType mt2=new MessageType(); - mt2.setValue(CONFIRMATION_MESSAGE_TYPE); - sendConformation.getMessageType().add(mt2); - pd.getNode().add(sendConformation); - - SendMessage sendOutOfStock=new SendMessage(); - //sendOutOfStock.setNodeType(Protocol.Node.NodeType.SendMessage); - - MessageType mt3=new MessageType(); - mt3.setValue(OUT_OF_STOCK_MESSAGE_TYPE); - sendOutOfStock.getMessageType().add(mt3); - pd.getNode().add(sendOutOfStock); - - return (pd); - } - - @Test - public void testSellerValidOrderConfirmation() { - Description pd=getSellerProtocol(); - - // Create Protocol Monitor - ProtocolMonitor monitor=new DefaultProtocolMonitor(); - - DefaultMonitorContext context=new DefaultMonitorContext(); - - Session conv=monitor.createSession(context, pd, DefaultSession.class); - - DefaultMessage message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Order failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CONFIRMATION_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Confirmation failed"); - } - - if (conv.isFinished() == false) { - fail("Conversation should be finished"); - } - } - - @Test - public void testSellerValidOrderConfirmationLookahead() { - Description pd=getSellerProtocol(); - - // Create Protocol Monitor - ProtocolMonitor monitor=new DefaultProtocolMonitor(); - - DefaultMonitorContext context=new DefaultMonitorContext(); - - Session conv=monitor.createSession(context, pd, DefaultSession.class); - - DefaultMessage message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Order failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(CONFIRMATION_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == false) { - fail("Confirmation failed"); - } - - if (conv.isFinished() == false) { - fail("Conversation should be finished"); - } - } - - @Test - public void testSellerInvalidOrderConfirmation() { - Description pd=getSellerProtocol(); - - // Create Protocol Monitor - ProtocolMonitor monitor=new DefaultProtocolMonitor(); - - DefaultMonitorContext context=new DefaultMonitorContext(); - - Session conv=monitor.createSession(context, pd, DefaultSession.class); - - DefaultMessage message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageReceived(context, pd, conv, message).isValid() == false) { - fail("Order failed"); - } - - message=new DefaultMessage(); - message.getTypes().add(ORDER_MESSAGE_TYPE); - - if (monitor.messageSent(context, pd, conv, message).isValid() == true) { - fail("Second order should have failed"); - } - - if (conv.isFinished() == true) { - fail("Conversation should NOT be finished"); - } - } -} diff --git a/bundles/org.scribble.protocol.parser/LICENSE.txt b/bundles/org.scribble.protocol.parser/LICENSE.txt deleted file mode 100644 index 29f81d812..000000000 --- a/bundles/org.scribble.protocol.parser/LICENSE.txt +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - 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 - - http://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. diff --git a/bundles/org.scribble.protocol.parser/META-INF/MANIFEST.MF b/bundles/org.scribble.protocol.parser/META-INF/MANIFEST.MF deleted file mode 100644 index 429f5f81a..000000000 --- a/bundles/org.scribble.protocol.parser/META-INF/MANIFEST.MF +++ /dev/null @@ -1,15 +0,0 @@ -Manifest-Version: 1.0 -Bundle-ManifestVersion: 2 -Bundle-Name: Scribble Protocol Parser -Bundle-SymbolicName: org.scribble.protocol.parser;singleton:=true -Bundle-Version: 2.1.0.SNAPSHOT -Bundle-Vendor: www.scribble.org -Import-Package: org.osgi.framework;version="1.3.0" -Export-Package: org.scribble.protocol.parser.antlr -Bundle-ClassPath: ., - lib/antlr-3.2.jar, - src/main/resources/lib/antlr-3.2.jar -Bundle-RequiredExecutionEnvironment: JavaSE-1.6 -Require-Bundle: org.scribble.protocol, - org.scribble.common -Bundle-Activator: org.scribble.protocol.parser.osgi.Activator diff --git a/bundles/org.scribble.protocol.parser/build.properties b/bundles/org.scribble.protocol.parser/build.properties deleted file mode 100644 index b844f8dbe..000000000 --- a/bundles/org.scribble.protocol.parser/build.properties +++ /dev/null @@ -1,19 +0,0 @@ -source.. = src/main/java/,\ - target/generated-sources/antlr3/ -output.. = bin/ -bin.includes = META-INF/,\ - .,\ - src/main/resources/lib/antlr-3.2.jar,\ - OSGI-INF/,\ - LICENSE.txt -src.includes = target/generated-sources/,\ - src/,\ - pom.xml,\ - build.properties,\ - META-INF/,\ - .project,\ - .classpath,\ - OSGI-INF/,\ - LICENSE.txt -jars.compile.order = .,\ - lib/antlr-3.2.jar diff --git a/bundles/org.scribble.protocol.parser/pom.xml b/bundles/org.scribble.protocol.parser/pom.xml deleted file mode 100644 index d07b4a235..000000000 --- a/bundles/org.scribble.protocol.parser/pom.xml +++ /dev/null @@ -1,61 +0,0 @@ - - 4.0.0 - org.scribble.bundles - org.scribble.protocol.parser - jar - 2.1.0-SNAPSHOT - Scribble::Bundles::ProtocolParser - - - org.scribble - bundles - 2.1.0-SNAPSHOT - - - - - org.scribble.bundles - org.scribble.common - ${scribble.bundles.version} - - - org.scribble.bundles - org.scribble.protocol - ${scribble.bundles.version} - - - org.osgi - org.osgi.core - ${osgi.version} - - - org.antlr - antlr-runtime - ${antlr.version} - - - junit - junit - test - - - - - - - org.antlr - antlr3-maven-plugin - 3.2 - - - - antlr - - - - - - - - diff --git a/bundles/org.scribble.protocol.parser/src/main/antlr3/org/scribble/protocol/parser/antlr/ScribbleProtocol.g b/bundles/org.scribble.protocol.parser/src/main/antlr3/org/scribble/protocol/parser/antlr/ScribbleProtocol.g deleted file mode 100644 index 675e47849..000000000 --- a/bundles/org.scribble.protocol.parser/src/main/antlr3/org/scribble/protocol/parser/antlr/ScribbleProtocol.g +++ /dev/null @@ -1,197 +0,0 @@ -grammar ScribbleProtocol; - -options { - output=AST; - backtrack=true; -} - -tokens { - INTERACTION = 'interaction' ; - PLUS = '+' ; - MINUS = '-' ; - MULT = '*' ; - DIV = '/' ; - FULLSTOP = '.' ; -} - -@header { -package org.scribble.protocol.parser.antlr; -} - -@lexer::header { -package org.scribble.protocol.parser.antlr; -} - -@members { - private org.scribble.common.logging.Journal m_journal=null; - private String m_document=null; - private boolean m_errorOccurred=false; - - public static void main(String[] args) throws Exception { - ScribbleProtocolLexer lex = new ScribbleProtocolLexer(new ANTLRFileStream(args[0])); - CommonTokenStream tokens = new CommonTokenStream(lex); - - ScribbleProtocolParser parser = new ScribbleProtocolParser(tokens); - - ProtocolTreeAdaptor adaptor=new ProtocolTreeAdaptor(null, null); - adaptor.setParser(parser); - - parser.setTreeAdaptor(adaptor); - - try { - ScribbleProtocolParser.description_return r=parser.description(); - - //CommonTree t=(CommonTree)r.getTree(); - - //Tree t=(Tree)r.getTree(); - - //System.out.println(t.toStringTree()); - - } catch (RecognitionException e) { - e.printStackTrace(); - } - } - - public void setJournal(org.scribble.common.logging.Journal journal) { - m_journal = journal; - } - - public void setDocument(String doc) { - m_document = doc; - } - - public void emitErrorMessage(String mesg) { - if (m_journal == null) { - super.emitErrorMessage(mesg); - } else { - m_journal.error(ANTLRMessageUtil.getMessageText(mesg), - ANTLRMessageUtil.getProperties(mesg, m_document)); - } - m_errorOccurred = true; - } - - public boolean isErrorOccurred() { - return(m_errorOccurred); - } -} - -/*------------------------------------------------------------------ - * PARSER RULES - *------------------------------------------------------------------*/ - -description: ( ( ANNOTATION )* ( importProtocolStatement | importTypeStatement ) )* ( ANNOTATION )* protocolDef ; - -importProtocolStatement: 'import' 'protocol' importProtocolDef ( ','! importProtocolDef )* ';'! ; - -importProtocolDef: ID 'from'! StringLiteral; - -importTypeStatement: 'import' ( simpleName )? importTypeDef ( ','! importTypeDef )* ( 'from'! StringLiteral )? ';'! ; - -importTypeDef: ( dataTypeDef 'as'! )? ID ; - -dataTypeDef: StringLiteral ; - -simpleName: ID ; - -protocolDef: 'protocol'^ protocolName ( 'at' roleName )? ( parameterDefs )? '{'! protocolBlockDef ( ( ANNOTATION )* protocolDef )* '}'! ; - -protocolName: ID ; - -parameterDefs: '('! parameterDef ( ','! parameterDef )* ')'! ; - -parameterDef: ( typeReferenceDef | 'role' ) simpleName ; - -protocolBlockDef: activityListDef ; - -blockDef: '{'! activityListDef '}'! ; - -activityListDef: ( ( ANNOTATION )* activityDef )* ; - -activityDef: ( introducesDef | interactionDef | inlineDef | runDef | recursionDef | endDef ) ';'! | - choiceDef | directedChoiceDef | parallelDef | repeatDef | unorderedDef | - recBlockDef | globalEscapeDef ; - -introducesDef: roleDef 'introduces' roleDef ( ','! roleDef )* ; - -roleDef: ID ; - -roleName: ID ; - -typeReferenceDef: ID ; - -interactionSignatureDef: ( typeReferenceDef | ID '('! ( typeReferenceDef ( ','! typeReferenceDef )* )? ')'! ) ; - -interactionDef: interactionSignatureDef ( 'from' roleName ( 'to' roleName ( ','! roleName )* )? | - 'to' roleName ( ','! roleName )* ) ; - -choiceDef: 'choice'^ ( 'at' roleName )? blockDef ( 'or' blockDef )* ; - -directedChoiceDef: ( 'from' roleName )? ( 'to' roleName ( ','! roleName )* )? '{' ( onMessageDef )+ '}' ; - -onMessageDef: interactionSignatureDef ':' activityList ; - -activityList: ( ( ANNOTATION )* activityDef )* ; - -repeatDef: 'repeat'^ ( 'at' roleName ( ','! roleName )* )? blockDef ; - -recBlockDef: 'rec'^ labelName blockDef ; - -labelName: ID ; - -recursionDef: labelName ; - -endDef: 'end'^ ; - -runDef: 'run'^ protocolRefDef ( '('! parameter ( ','! parameter )* ')'! )? 'from' roleName ; - -protocolRefDef: ID ( 'at' roleName )? ; - -declarationName: ID ; - -parameter: declarationName ; - -inlineDef: 'inline'^ protocolRefDef ( '('! parameter ( ','! parameter )* ')'! )? ; - -parallelDef: 'parallel'^ blockDef ( 'and' blockDef )* ; - -globalEscapeDef: 'do'^ blockDef ( interruptDef )+ ; - -interruptDef: 'interrupt'^ blockDef ; - -unorderedDef: 'unordered'^ blockDef ; - - -/*----------------------------------------------- -TO DO: -Declaration (variables) possibly - but that may need -lookahead to avoid conflict with interactions. --------------------------------------------------*/ - -expr : term ( ( PLUS | MINUS ) term )* ; - -term : factor ( ( MULT | DIV ) factor )* ; - -factor : NUMBER ; - - -/*------------------------------------------------------------------ - * LEXER RULES - *------------------------------------------------------------------*/ - -ID : ('a'..'z'|'A'..'Z'|'_')('a'..'z'|'A'..'Z'|'0'..'9'|'_')* ; - -NUMBER : (DIGIT)+ ; - -WHITESPACE : ( '\t' | ' ' | '\r' | '\n'| '\u000C' )+ { $channel = HIDDEN; } ; - -fragment DIGIT : '0'..'9' ; - -ANNOTATION : '[[' (options {greedy=false;} : .)* ']]' ; - -ML_COMMENT - : '/*' (options {greedy=false;} : .)* '*/' {$channel=HIDDEN;} - ; - -LINE_COMMENT : '//' (options {greedy=false;} : .)* '\n' {$channel=HIDDEN;} ; - -StringLiteral: '"' ( ~('\\'|'"') )* '"' ; diff --git a/bundles/org.scribble.protocol.parser/src/main/java/org/scribble/protocol/parser/antlr/ANTLRMessageUtil.java b/bundles/org.scribble.protocol.parser/src/main/java/org/scribble/protocol/parser/antlr/ANTLRMessageUtil.java deleted file mode 100644 index 722e0fcab..000000000 --- a/bundles/org.scribble.protocol.parser/src/main/java/org/scribble/protocol/parser/antlr/ANTLRMessageUtil.java +++ /dev/null @@ -1,129 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.parser.antlr; - -import org.scribble.common.logging.Journal; - -/** - * ANTLR message utilities. - * - */ -public final class ANTLRMessageUtil { - - /** - * Private constructor. - */ - private ANTLRMessageUtil() { - } - - /** - * End location separator. - */ - private static final char END_LOCATION_SEPARATOR = ' '; - - /** - * Location prefix token. - */ - private static final String LOCATION_PREFIX_TOKEN = "line "; - - /** - * This method removes the message location prefix. - * - * @param mesg The message - * @return The message with the location information removed - */ - public static String getMessageText(String mesg) { - String ret=mesg; - - if (mesg != null && mesg.startsWith(LOCATION_PREFIX_TOKEN)) { - int index=mesg.indexOf(END_LOCATION_SEPARATOR, LOCATION_PREFIX_TOKEN.length()); - - if (index != -1) { - ret = mesg.substring(index+1); - } - } - - return (ret); - } - - /** - * This method returns the properties. - * - * @param mesg The message - * @param document The document - * @return The properties - */ - public static java.util.Map getProperties(String mesg, String document) { - java.util.Map ret=null; - - if (mesg != null && mesg.startsWith(LOCATION_PREFIX_TOKEN)) { - int index=mesg.indexOf(END_LOCATION_SEPARATOR, LOCATION_PREFIX_TOKEN.length()); - - if (index != -1) { - String lineDetails=mesg.substring(LOCATION_PREFIX_TOKEN.length(), index); - - String[] nums=lineDetails.split(":"); - - if (nums != null && nums.length == 2) { - ret = new java.util.HashMap(); - - Integer line=Integer.parseInt(nums[0]); - Integer col=Integer.parseInt(nums[1]); - - ret.put(Journal.START_LINE, line); - ret.put(Journal.START_COLUMN, col); - - // Determine the position within the document - int pos=0; - - for (int i=0; pos != -1 && i < line.intValue()-1; i++) { - pos = document.indexOf("\r\n", pos); - - if (pos != -1) { - pos += 2; - } - } - - if (pos != -1) { - pos += col.intValue(); - - ret.put(Journal.START_POSITION, new Integer(pos)); - - // Find next whitespace - int endpos=document.length(); - int nextpos=-1; - - for (int j=pos+1; nextpos == -1 && j < endpos; j++) { - char ch=document.charAt(j); - if (Character.isWhitespace(ch)) { - nextpos = j-1; - } - } - - if (nextpos == -1) { - nextpos = pos; - } - - ret.put(Journal.END_POSITION, new Integer(nextpos)); - } - } - } - } - - return (ret); - } -} diff --git a/bundles/org.scribble.protocol.parser/src/main/java/org/scribble/protocol/parser/antlr/ANTLRProtocolParser.java b/bundles/org.scribble.protocol.parser/src/main/java/org/scribble/protocol/parser/antlr/ANTLRProtocolParser.java deleted file mode 100644 index 3ca6f993e..000000000 --- a/bundles/org.scribble.protocol.parser/src/main/java/org/scribble/protocol/parser/antlr/ANTLRProtocolParser.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Copyright 2009 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.parser.antlr; - -import java.io.IOException; - -import org.antlr.runtime.ANTLRStringStream; -import org.antlr.runtime.CommonTokenStream; -import org.scribble.common.logging.Journal; -import org.scribble.common.resource.Content; -import org.scribble.protocol.ProtocolContext; -import org.scribble.protocol.model.ProtocolModel; -import org.scribble.protocol.parser.AnnotationProcessor; -import org.scribble.protocol.parser.ProtocolParser; - -/** - * This class provides the ANTLR implementation of the Protocol Parser - * interface. - * - */ -public class ANTLRProtocolParser implements ProtocolParser { - - private AnnotationProcessor _annotationProcessor=null; - - /** - * Default constructor. - */ - public ANTLRProtocolParser() { - } - - /** - * {@inheritDoc} - */ - public boolean isSupported(Content content) { - return (content.hasExtension(org.scribble.protocol.ProtocolDefinitions.PROTOCOL_TYPE)); - } - - /** - * {@inheritDoc} - */ - public ProtocolModel parse(ProtocolContext context, Content content, Journal journal) - throws IOException { - ProtocolModel ret=null; - - try { - java.io.InputStream is=content.getInputStream(); - - byte[] b=new byte[is.available()]; - is.read(b); - - is.close(); - - String document=new String(b); - - ScribbleProtocolLexer lex = new ScribbleProtocolLexer(new ANTLRStringStream(document)); - CommonTokenStream tokens = new CommonTokenStream(lex); - - ScribbleProtocolParser parser = new ScribbleProtocolParser(tokens); - - ProtocolTreeAdaptor adaptor=new ProtocolTreeAdaptor(_annotationProcessor, journal); - adaptor.setParser(parser); - - parser.setDocument(document); - parser.setTreeAdaptor(adaptor); - - parser.setJournal(journal); - - parser.description(); - - if (!parser.isErrorOccurred()) { - ret = adaptor.getProtocolModel(); - } - - } catch (Exception e) { - e.printStackTrace(); - } - - return (ret); - } - - /** - * This method sets an annotation processor. - * - * @param ap The annotation processor - */ - public void setAnnotationProcessor(AnnotationProcessor ap) { - _annotationProcessor = ap; - } -} diff --git a/bundles/org.scribble.protocol.parser/src/main/java/org/scribble/protocol/parser/antlr/ProtocolTreeAdaptor.java b/bundles/org.scribble.protocol.parser/src/main/java/org/scribble/protocol/parser/antlr/ProtocolTreeAdaptor.java deleted file mode 100644 index c9fcc29d9..000000000 --- a/bundles/org.scribble.protocol.parser/src/main/java/org/scribble/protocol/parser/antlr/ProtocolTreeAdaptor.java +++ /dev/null @@ -1,935 +0,0 @@ -/* - * Copyright 2009-11 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.parser.antlr; - -import java.beans.PropertyDescriptor; -import java.util.logging.Logger; - -import org.antlr.runtime.RecognitionException; -import org.antlr.runtime.Token; -import org.antlr.runtime.TokenStream; -import org.scribble.common.logging.Journal; -import org.scribble.common.model.Annotation; -import org.scribble.common.model.DefaultAnnotation; -import org.scribble.protocol.model.Activity; -import org.scribble.protocol.model.Block; -import org.scribble.protocol.model.Choice; -import org.scribble.protocol.model.DataType; -import org.scribble.protocol.model.DirectedChoice; -import org.scribble.protocol.model.Do; -import org.scribble.protocol.model.End; -import org.scribble.protocol.model.ImportList; -import org.scribble.protocol.model.Inline; -import org.scribble.protocol.model.Interaction; -import org.scribble.protocol.model.Interrupt; -import org.scribble.protocol.model.Introduces; -import org.scribble.protocol.model.MessageSignature; -import org.scribble.protocol.model.ModelObject; -import org.scribble.protocol.model.OnMessage; -import org.scribble.protocol.model.Parallel; -import org.scribble.protocol.model.Parameter; -import org.scribble.protocol.model.ParameterDefinition; -import org.scribble.protocol.model.Protocol; -import org.scribble.protocol.model.ProtocolImport; -import org.scribble.protocol.model.ProtocolImportList; -import org.scribble.protocol.model.ProtocolModel; -import org.scribble.protocol.model.ProtocolReference; -import org.scribble.protocol.model.RecBlock; -import org.scribble.protocol.model.Recursion; -import org.scribble.protocol.model.Repeat; -import org.scribble.protocol.model.Role; -import org.scribble.protocol.model.Run; -import org.scribble.protocol.model.TypeImport; -import org.scribble.protocol.model.TypeImportList; -import org.scribble.protocol.model.TypeReference; -import org.scribble.protocol.model.Unordered; -import org.scribble.protocol.parser.AnnotationProcessor; - -/** - * This class provides an implementation of the tree adapter. - * - */ -public class ProtocolTreeAdaptor implements org.antlr.runtime.tree.TreeAdaptor { - - private static final String ANNOTATIONS = "_annotations"; - private static final String ACTIVITY_RULE_NAME = "activityDef"; - private static final java.util.Map PROPERTY_TOKENS= - new java.util.HashMap(); - private static final java.util.Map> TOKEN_CLASS= - new java.util.HashMap>(); - private static final java.util.Map> LIST_CLASS= - new java.util.HashMap>(); - private static final java.util.Map> PARSER_GROUPING_RULE_CLASS= - new java.util.HashMap>(); - private static final java.util.List CLEAR_TOKEN_LIST_RULES= - new java.util.Vector(); - private static final java.util.List TOKENS_TO_IGNORE= - new java.util.Vector(); - private static final java.util.List STRING_LITERALS= - new java.util.Vector(); - - private ScribbleProtocolParser _parser=null; - private AnnotationProcessor _annotationProcessor=null; - private Journal _journal=null; - private Token _currentToken=null; - - private ProtocolModel _model=null; - - private static final Logger LOG=Logger.getLogger(ProtocolTreeAdaptor.class.getName()); - - static { - // The map of root tokens, that begin a grammer - // rule, and the model class they are associated - // with - //m_tokenClass.put("import", ImportList.class); - TOKEN_CLASS.put("protocol", Protocol.class); - //m_tokenClass.put("role", RoleList.class); - TOKEN_CLASS.put("choice", Choice.class); - TOKEN_CLASS.put("rec", RecBlock.class); - TOKEN_CLASS.put("parallel", Parallel.class); - TOKEN_CLASS.put("repeat", Repeat.class); - TOKEN_CLASS.put("do", Do.class); - TOKEN_CLASS.put("interrupt", Interrupt.class); - TOKEN_CLASS.put("run", Run.class); - TOKEN_CLASS.put("inline", Inline.class); - TOKEN_CLASS.put("unordered", Unordered.class); - TOKEN_CLASS.put("end", End.class); - - // Clear token list - determines whether prior to processing - // a list of tokens, the 'current token' should be cleared - CLEAR_TOKEN_LIST_RULES.add("parameter"); - CLEAR_TOKEN_LIST_RULES.add("dataTypeDef"); - CLEAR_TOKEN_LIST_RULES.add("importTypeStatement"); - CLEAR_TOKEN_LIST_RULES.add("importProtocolDef"); - CLEAR_TOKEN_LIST_RULES.add("introducesDef"); - CLEAR_TOKEN_LIST_RULES.add("directedChoiceDef"); - - // The list of tokens that should be ignored when processing - // the children of a parent node - TOKENS_TO_IGNORE.add("import"); - - // This may define the model object that should be - // created after processing the named grammer rule - PARSER_GROUPING_RULE_CLASS.put("importProtocolStatement", ProtocolImportList.class); - PARSER_GROUPING_RULE_CLASS.put("importTypeStatement", TypeImportList.class); - PARSER_GROUPING_RULE_CLASS.put("simpleName", String.class); - PARSER_GROUPING_RULE_CLASS.put("simpleName", String.class); - PARSER_GROUPING_RULE_CLASS.put("blockDef", Block.class); - PARSER_GROUPING_RULE_CLASS.put("protocolBlockDef", Block.class); - PARSER_GROUPING_RULE_CLASS.put("activityList", Block.class); - PARSER_GROUPING_RULE_CLASS.put("interactionDef", Interaction.class); - PARSER_GROUPING_RULE_CLASS.put("interactionSignatureDef", MessageSignature.class); - PARSER_GROUPING_RULE_CLASS.put("typeReferenceDef", TypeReference.class); - PARSER_GROUPING_RULE_CLASS.put("protocolName", String.class); - PARSER_GROUPING_RULE_CLASS.put("roleName", Role.class); - PARSER_GROUPING_RULE_CLASS.put("roleDef", Role.class); - PARSER_GROUPING_RULE_CLASS.put("importProtocolDef", ProtocolImport.class); - PARSER_GROUPING_RULE_CLASS.put("importTypeDef", TypeImport.class); - PARSER_GROUPING_RULE_CLASS.put("protocolRefDef", ProtocolReference.class); - PARSER_GROUPING_RULE_CLASS.put("parameter", Parameter.class); - PARSER_GROUPING_RULE_CLASS.put("inlineProtocolDef", Protocol.class); - PARSER_GROUPING_RULE_CLASS.put("declarationName", String.class); - PARSER_GROUPING_RULE_CLASS.put("labelName", String.class); - PARSER_GROUPING_RULE_CLASS.put("dataTypeDef", DataType.class); - PARSER_GROUPING_RULE_CLASS.put("recursionDef", Recursion.class); - PARSER_GROUPING_RULE_CLASS.put("parameterDef", ParameterDefinition.class); - PARSER_GROUPING_RULE_CLASS.put("introducesDef", Introduces.class); - PARSER_GROUPING_RULE_CLASS.put("directedChoiceDef", DirectedChoice.class); - PARSER_GROUPING_RULE_CLASS.put("onMessageDef", OnMessage.class); - - // When a particular class has multiple properties of the - // same type, then a preceding token must be used to - // determine which property to set. This map provides the - // mapping between the property name and the token. - PROPERTY_TOKENS.put("interactionDef:fromRole", "from"); - PROPERTY_TOKENS.put("directedChoiceDef:fromRole", "from"); - PROPERTY_TOKENS.put("choiceDef:role", "at"); - PROPERTY_TOKENS.put("interactionDef:toRoles", "to"); - PROPERTY_TOKENS.put("directedChoiceDef:toRoles", "to"); - PROPERTY_TOKENS.put("parameter:boundName", ""); - PROPERTY_TOKENS.put("parameter:localName", ":="); - PROPERTY_TOKENS.put("dataTypeDef:details", ""); // Needed to make sure property not used by default - PROPERTY_TOKENS.put("importTypeStatement:format", ""); - PROPERTY_TOKENS.put("importTypeStatement:location", "from"); - PROPERTY_TOKENS.put("importProtocolDef:name", ""); - PROPERTY_TOKENS.put("importProtocolDef:location", "from"); - PROPERTY_TOKENS.put("introducesDef:introducer", ""); - PROPERTY_TOKENS.put("introducesDef:introducedRoles", "introduces"); - - // Defines the list element base type associated with a - // property name - LIST_CLASS.put("imports", ImportList.class); - LIST_CLASS.put("contents", Activity.class); - LIST_CLASS.put("roles", Role.class); - LIST_CLASS.put("introducedRoles", Role.class); - LIST_CLASS.put("toRoles", Role.class); - LIST_CLASS.put("typeImports", TypeImport.class); - LIST_CLASS.put("protocolImports", ProtocolImport.class); - LIST_CLASS.put("typeReferences", TypeReference.class); - LIST_CLASS.put("blocks", Block.class); - LIST_CLASS.put("paths", Block.class); - LIST_CLASS.put("nestedProtocols", Protocol.class); - LIST_CLASS.put("onMessages", OnMessage.class); - LIST_CLASS.put("interrupts", Interrupt.class); - LIST_CLASS.put("parameters", Parameter.class); - LIST_CLASS.put("interactions", Interaction.class); - LIST_CLASS.put("parameterDefinitions", ParameterDefinition.class); - - STRING_LITERALS.add("dataTypeDef:details"); - STRING_LITERALS.add("importTypeStatement:location"); - STRING_LITERALS.add("importProtocolDef:location"); - } - - - /** - * This is the constructor for the protocol tree adapter. - * - * @param ap The annotation processor - * @param journal The journal - */ - public ProtocolTreeAdaptor(AnnotationProcessor ap, Journal journal) { - _annotationProcessor = ap; - _journal = journal; - } - - /** - * This method returns the protocol model. - * - * @return The protocol model - */ - public ProtocolModel getProtocolModel() { - return (_model); - } - - /** - * This method sets the parser. - * - * @param parser The parser - */ - public void setParser(ScribbleProtocolParser parser) { - _parser = parser; - } - - /** - * {@inheritDoc} - */ - public Object create(Token token) { - Object ret=token; - - Class cls=TOKEN_CLASS.get(token.getText()); - - LOG.fine("Token class for '"+token.getText() - +"' is: "+cls); - - if (cls != null) { - try { - ret = cls.newInstance(); - } catch (Exception e) { - e.printStackTrace(); - } - } - - if (ret == token && token.getType() != ScribbleProtocolParser.ID) { - LOG.fine("Set current token="+token); - _currentToken = token; - } - - // Check if positional information should be set - adjustLocationInfo(ret, token); - - return (ret); - } - - /** - * {@inheritDoc} - */ - public Object dupNode(Object arg0) { - LOG.finest("DUPNODE "+arg0); - return null; - } - - /** - * {@inheritDoc} - */ - public int getChildIndex(Object arg0) { - LOG.finest("GET CHILD INDEX "+arg0); - return 0; - } - - /** - * {@inheritDoc} - */ - public Object getParent(Object arg0) { - LOG.finest("GET PARENT "+arg0); - return null; - } - - /** - * {@inheritDoc} - */ - public Token getToken(Object arg0) { - LOG.finest("GET TOKEN "+arg0); - return null; - } - - /** - * {@inheritDoc} - */ - public int getTokenStartIndex(Object arg0) { - LOG.finest("GET TOKEN START INDEX "+arg0); - return 0; - } - - /** - * {@inheritDoc} - */ - public int getTokenStopIndex(Object arg0) { - LOG.finest("GET TOKEN STOP INDEX "+arg0); - return 0; - } - - /** - * {@inheritDoc} - */ - public void setChildIndex(Object arg0, int arg1) { - LOG.finest("SET CHILD INDEX "+arg0+" "+arg1); - } - - /** - * {@inheritDoc} - */ - public void replaceChildren(Object arg0, int arg1, int arg2, Object arg3) { - LOG.finest("REPLACE CHILD "+arg0+" "+arg1+" "+arg2+" "+arg3); - } - - /** - * {@inheritDoc} - */ - public void setParent(Object arg0, Object arg1) { - LOG.finest("SET PARENT "+arg0+" "+arg1); - } - - /** - * {@inheritDoc} - */ - public void setTokenBoundaries(Object arg0, Token arg1, Token arg2) { - LOG.finest("SET TOKEN BOUNDARIES "+arg0+" "+arg1+" "+arg2); - } - - /** - * {@inheritDoc} - */ - @SuppressWarnings("unchecked") - public void addChild(Object parent, Object child) { - boolean added=false; - - LOG.fine("Add child: parent="+parent+" child="+child); - - // Associate annotations with the protocol model - if ((parent instanceof ProtocolModel || parent instanceof Protocol) - && child instanceof Token && ((Token)child).getType() - == ScribbleProtocolParser.ANNOTATION) { - - // Add the annotation to a temporary location associated - // with the model, until the real target model object is - // identified - java.util.List annotations=(java.util.List) - ((ModelObject)parent).getProperties().get(ANNOTATIONS); - - if (annotations == null) { - annotations = new java.util.Vector(); - ((ModelObject)parent).getProperties().put(ANNOTATIONS, annotations); - } - - String annotation=((Token)child).getText(); - annotation = annotation.substring(2, annotation.length()-2); - - annotations.add(annotation); - - return; - } - - // Check if child is a list - if (isNil(child)) { - java.util.List nil= - (java.util.List)child; - String ruleName=null; - - if (_parser != null - && _parser.getRuleInvocationStack().size() > 0) { - ruleName = (String)_parser.getRuleInvocationStack().get( - _parser.getRuleInvocationStack().size()-1); - - // Before processing the sublist of tokens, clear - // the current token - needed for cases like the - // 'parameter' syntax rule - if (nil.size() > 0 && ruleName != null && CLEAR_TOKEN_LIST_RULES.contains(ruleName)) { - LOG.fine("Clear current token before processing sublist of tokens: rule="+ruleName); - _currentToken = null; - } - } - - // Check if ID token - StringBuffer buf=new StringBuffer(); - java.util.List annotations=new java.util.Vector(); - - for (int i=0; i < nil.size(); i++) { - - if (nil.get(i) instanceof Token - && (((Token)nil.get(i)).getType() == ScribbleProtocolParser.ID - || ((Token)nil.get(i)).getType() == ScribbleProtocolParser.FULLSTOP)) { - buf.append(((Token)nil.get(i)).getText()); - } else { - if (buf.length() > 0) { - addChild(parent, buf.toString()); - - buf = new StringBuffer(); - } - - if (nil.get(i) instanceof Token - && !TOKENS_TO_IGNORE.contains(((Token)nil.get(i)).getText())) { - _currentToken = (Token)nil.get(i); - LOG.fine("Set current token: "+_currentToken); - } - - if (nil.get(i) instanceof Token && ((Token)nil.get(i)).getType() == ScribbleProtocolParser.ANNOTATION) { - annotations.add((Token)nil.get(i)); - } else { - addChild(parent, nil.get(i)); - - if (nil.get(i) instanceof ModelObject) { - for (Token annotationToken : annotations) { - String text=annotationToken.getText(); - text = text.substring(2, text.length()-2); - - Annotation annotation=null; - if (_annotationProcessor != null) { - annotation = _annotationProcessor.getAnnotation(text, - ((ModelObject)nil.get(i)).getProperties(), _journal); - } - - if (annotation == null) { - annotation = new DefaultAnnotation(text); - } - - ((ModelObject)nil.get(i)).getAnnotations().add(annotation); - } - - annotations.clear(); - } - } - } - - adjustLocationInfo(parent, nil.get(i)); - } - - if (buf.length() > 0) { - addChild(parent, buf.toString()); - } - } else if (parent != null && child != null) { - - added = addChildNonList(parent, child); - } - - if (added && parent instanceof ModelObject && child instanceof ModelObject) { - - // See if child's textual location can be used to increase the scope of the - // parent model object - int parEndLine=-1; - int parEndCol=-1; - int chEndLine=-1; - int chEndCol=-1; - - ModelObject parmobj=(ModelObject)parent; - ModelObject chmobj=(ModelObject)child; - - if (parmobj.getProperties().containsKey(Journal.END_LINE)) { - parEndLine = (Integer)parmobj.getProperties().get(Journal.END_LINE); - } - - if (parmobj.getProperties().containsKey(Journal.END_LINE)) { - parEndCol = (Integer)parmobj.getProperties().get(Journal.END_COLUMN); - } - - if (chmobj.getProperties().containsKey(Journal.END_LINE)) { - chEndLine = (Integer)chmobj.getProperties().get(Journal.END_LINE); - } - - if (chmobj.getProperties().containsKey(Journal.END_COLUMN)) { - chEndCol = (Integer)chmobj.getProperties().get(Journal.END_COLUMN); - } - - if (chEndLine > parEndLine || chEndCol > parEndCol) { - parmobj.getProperties().put(Journal.END_LINE, chEndLine); - parmobj.getProperties().put(Journal.END_COLUMN, chEndCol); - } - } - } - - /** - * Add child not associated with a list. - * - * @param parent The parent - * @param child The child - * @return Whether child added - */ - @SuppressWarnings("unchecked") - protected boolean addChildNonList(Object parent, Object child) { - boolean added=false; - - if (isNil(parent)) { - java.util.List nil= - (java.util.List)parent; - - LOG.finest("Add child: "+child); - nil.add(child); - - } else { - LOG.finest("Determine if can be set by property descriptor"); - - // Check if annotations should be associated with the protocol model child - if ((parent instanceof ProtocolModel || parent instanceof Protocol) - && child instanceof ModelObject) { - java.util.List annotations=(java.util.List) - ((ModelObject)parent).getProperties().get(ANNOTATIONS); - - if (annotations != null) { - - for (String text : annotations) { - Annotation annotation=null; - if (_annotationProcessor != null) { - annotation = _annotationProcessor.getAnnotation(text, - ((ModelObject)child).getProperties(), _journal); - } - - if (annotation == null) { - annotation = new DefaultAnnotation(text); - } - - ((ModelObject)child).getAnnotations().add(annotation); - } - } - - // Clear existing properties - ((ModelObject)parent).getProperties().remove(ANNOTATIONS); - } - - // Check if child is a string literal - boolean stringLiteral=false; - - if (child instanceof Token - && ((Token)child).getType() == ScribbleProtocolParser.StringLiteral) { - String strlit = ((Token)child).getText(); - - if (((Token)child).getType() == ScribbleProtocolParser.StringLiteral - && strlit.length() >= 2) { - // Strip the quotes - child = strlit.substring(1, strlit.length()-1); - } else { - child = strlit; - } - - stringLiteral = true; - } - - String ruleName=""; - - if (_parser != null - && _parser.getRuleInvocationStack().size() > 0) { - ruleName = (String)_parser.getRuleInvocationStack().get( - _parser.getRuleInvocationStack().size()-1); - } - - try { - // Get property descriptors for parent class - java.beans.BeanInfo bi= - java.beans.Introspector.getBeanInfo(parent.getClass()); - - PropertyDescriptor[] pds=bi.getPropertyDescriptors(); - PropertyDescriptor pd=null; - - for (int i=0; pd == null && i < pds.length; i++) { - - String token=PROPERTY_TOKENS.get(ruleName+":"+pds[i].getName()); - - if (pds[i].getPropertyType().isAssignableFrom(child.getClass()) - && !pds[i].getName().equals("parent")) { - - String ruleprop=ruleName+":"+pds[i].getName(); - - if (stringLiteral) { - if (STRING_LITERALS.contains(ruleprop) - && pds[i].getWriteMethod() != null) { - pd = pds[i]; - } - } else if ((token == null - || (token.length() == 0 && _currentToken == null) - || (_currentToken != null - && token.equals(_currentToken.getText()))) - && pds[i].getWriteMethod() != null) { - pd = pds[i]; - } - } else if (pds[i].getPropertyType() == java.util.List.class) { - - Class listElementCls=LIST_CLASS.get(pds[i].getName()); - - if ((token == null - || (token.length() == 0 && _currentToken == null) - || (_currentToken != null - && token.equals(_currentToken.getText()))) - && listElementCls != null - && listElementCls.isAssignableFrom(child.getClass())) { - java.util.List list=(java.util.List) - pds[i].getReadMethod().invoke(parent); - - LOG.fine("Adding "+child+" to list: " - +list+" on parent "+parent); - list.add(child); - - added = true; - } - } - } - - // If property descriptor is not for 'parent' property, - // as this would match any 'child', and the property - // must have a set method - if (pd != null && pd.getWriteMethod() != null) { - - LOG.fine("Set property '"+pd.getName() - +"' on="+parent+" (class="+parent.getClass()+") to="+child); - - pd.getWriteMethod().invoke(parent, child); - - added = true; - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - return (added); - } - - /** - * This method adjusts the location information. - * - * @param parent Parent - * @param child Child - */ - protected void adjustLocationInfo(Object parent, Object child) { - if (parent instanceof ModelObject) { - ModelObject mobj=(ModelObject)parent; - - if (child instanceof Token) { - Token token=(Token)child; - - if (!mobj.getProperties().containsKey(Journal.START_LINE) - || token.getLine() < ((Integer)mobj.getProperties().get(Journal.START_LINE))) { - mobj.getProperties().put(Journal.START_LINE, token.getLine()); - mobj.getProperties().put(Journal.START_COLUMN, token.getCharPositionInLine()); - } else if (token.getLine() == ((Integer)mobj.getProperties().get(Journal.START_LINE)) - && token.getCharPositionInLine() < ((Integer)mobj.getProperties().get(Journal.START_COLUMN))) { - mobj.getProperties().put(Journal.START_COLUMN, token.getCharPositionInLine()); - } - - if (!mobj.getProperties().containsKey(Journal.END_LINE) - || token.getLine() > ((Integer)mobj.getProperties().get(Journal.END_LINE))) { - mobj.getProperties().put(Journal.END_LINE, token.getLine()); - mobj.getProperties().put(Journal.END_COLUMN, token.getCharPositionInLine() - +token.getText().length()); - } else if (token.getLine() == ((Integer)mobj.getProperties().get(Journal.END_LINE)) - && (token.getCharPositionInLine()+token.getText().length()) - < ((Integer)mobj.getProperties().get(Journal.END_COLUMN))) { - mobj.getProperties().put(Journal.END_COLUMN, token.getCharPositionInLine() - +token.getText().length()); - } - } else if (child instanceof ModelObject) { - ModelObject chobj=(ModelObject)child; - - if (chobj.getProperties().containsKey(Journal.START_LINE) - && chobj.getProperties().containsKey(Journal.START_COLUMN)) { - - if (!mobj.getProperties().containsKey(Journal.START_LINE) - || ((Integer)chobj.getProperties().get(Journal.START_LINE)) - < ((Integer)mobj.getProperties().get(Journal.START_LINE))) { - mobj.getProperties().put(Journal.START_LINE, chobj.getProperties().get(Journal.START_LINE)); - mobj.getProperties().put(Journal.START_COLUMN, chobj.getProperties().get(Journal.START_COLUMN)); - } else if (((Integer)chobj.getProperties().get(Journal.START_LINE)) - == ((Integer)mobj.getProperties().get(Journal.START_LINE)) - && ((Integer)chobj.getProperties().get(Journal.START_COLUMN)) - < ((Integer)mobj.getProperties().get(Journal.START_COLUMN))) { - mobj.getProperties().put(Journal.START_COLUMN, chobj.getProperties().get(Journal.START_COLUMN)); - } - } - - if (chobj.getProperties().containsKey(Journal.END_LINE) - && chobj.getProperties().containsKey(Journal.END_COLUMN)) { - - if (!mobj.getProperties().containsKey(Journal.END_LINE) - || ((Integer)chobj.getProperties().get(Journal.END_LINE)) - < ((Integer)mobj.getProperties().get(Journal.END_LINE))) { - mobj.getProperties().put(Journal.END_LINE, chobj.getProperties().get(Journal.END_LINE)); - mobj.getProperties().put(Journal.END_COLUMN, chobj.getProperties().get(Journal.END_COLUMN)); - } else if (((Integer)chobj.getProperties().get(Journal.END_LINE)) - == ((Integer)mobj.getProperties().get(Journal.END_LINE)) - && ((Integer)chobj.getProperties().get(Journal.END_COLUMN)) - < ((Integer)mobj.getProperties().get(Journal.END_COLUMN))) { - mobj.getProperties().put(Journal.END_COLUMN, chobj.getProperties().get(Journal.END_COLUMN)); - } - } - } - } - } - - /** - * {@inheritDoc} - */ - public Object becomeRoot(Object newRoot, Object oldRoot) { - LOG.finest("Become root "+newRoot+" "+oldRoot); - - if (oldRoot != null) { - addChild(newRoot, oldRoot); - - if (isNil(newRoot)) { - java.util.List nil= - (java.util.Vector)newRoot; - - if (nil.size() == 1) { - newRoot = nil.get(0); - } - } - } - - return (newRoot); - } - - /** - * {@inheritDoc} - */ - public Object becomeRoot(Token arg0, Object arg1) { - LOG.finest("BECOME_ROOT2 "+arg0+" "+arg1); - return null; - } - - /** - * {@inheritDoc} - */ - public Object create(int arg0, Token arg1) { - LOG.finest("CREATE "+arg0+" TOKEN "+arg1); - return null; - } - - /** - * {@inheritDoc} - */ - public Object create(int arg0, String arg1) { - LOG.finest("CREATE2 "+arg0+" STR "+arg1); - return null; - } - - /** - * {@inheritDoc} - */ - public Object create(int arg0, Token arg1, String arg2) { - LOG.finest("CREATE3 "+arg0+" TOKEN "+arg1+" STR "+arg2); - return null; - } - - /** - * {@inheritDoc} - */ - public Object deleteChild(Object arg0, int arg1) { - LOG.finest("DELETE "+arg0+" "+arg1); - return null; - } - - - /** - * {@inheritDoc} - */ - public Object dupTree(Object arg0) { - LOG.finest("DUPTREE "+arg0); - return null; - } - - /** - * {@inheritDoc} - */ - public Object errorNode(TokenStream arg0, Token arg1, Token arg2, - RecognitionException arg3) { - LOG.finest("ERRORNODE "+arg0+" "+arg1+" "+arg2+" "+arg3); - return null; - } - - /** - * {@inheritDoc} - */ - public Object getChild(Object arg0, int arg1) { - LOG.finest("GET CHILD "+arg0+" "+arg1); - return null; - } - - /** - * {@inheritDoc} - */ - public int getChildCount(Object arg0) { - LOG.finest("GET CHILD COUNT "+arg0); - return 0; - } - - /** - * {@inheritDoc} - */ - public String getText(Object arg0) { - LOG.finest("GET TEXT "+arg0); - return null; - } - - /** - * {@inheritDoc} - */ - public int getType(Object arg0) { - LOG.finest("GET TYPE "+arg0); - return 0; - } - - /** - * {@inheritDoc} - */ - public int getUniqueID(Object arg0) { - LOG.finest("GET UNIQUE ID "+arg0); - return 0; - } - - /** - * {@inheritDoc} - */ - public boolean isNil(Object obj) { - return (obj instanceof java.util.List); - } - - /** - * {@inheritDoc} - */ - public Object nil() { - Object ret=null; - - if (_model == null) { - _model = new ProtocolModel(); - ret = _model; - } else { - ret = new java.util.Vector(); - } - - return (ret); - } - - /** - * {@inheritDoc} - */ - public Object rulePostProcessing(Object root) { - Object ret=root; - - LOG.finest("RULE POST PROCESSING "+root); - - // Check if intermediate node required - if (_parser != null - && _parser.getRuleInvocationStack().size() > 0) { - String ruleName=(String)_parser.getRuleInvocationStack().get( - _parser.getRuleInvocationStack().size()-1); - - Class cls = PARSER_GROUPING_RULE_CLASS.get(ruleName); - - LOG.finest("Parser grouping rule for name '"+ruleName+"' is class="+cls); - - // Check if rule invocation is associated with activity - if (ruleName.equals(ACTIVITY_RULE_NAME) || CLEAR_TOKEN_LIST_RULES.contains(ruleName)) { - LOG.fine("Reset current token"); - _currentToken = null; - } - - if (cls != null) { - - if (cls == String.class) { - - if (isNil(root)) { - java.util.List nil= - (java.util.List)root; - StringBuffer buf=new StringBuffer(); - - for (int i=0; i < nil.size(); i++) { - if (nil.get(i) instanceof Token) { - buf.append(((Token)nil.get(i)).getText()); - } else { - buf.append(nil.get(i).toString()); - } - } - - ret = buf.toString(); - } - } else { - try { - Object newRoot=cls.newInstance(); - - LOG.finest("New root is: "+newRoot); - - addChild(newRoot, root); - - ret = newRoot; - - } catch (Exception e) { - e.printStackTrace(); - } - } - } - } - - if (isNil(ret)) { - java.util.List nil= - (java.util.List)ret; - - if (nil.size() == 1) { - return (nil.get(0)); - } else { - return (nil); - } - } - - return (ret); - } - - /** - * {@inheritDoc} - */ - public void setChild(Object arg0, int arg1, Object arg2) { - LOG.finest("SET CHILD "+arg0+" "+arg1+" "+arg2); - } - - /** - * {@inheritDoc} - */ - public void setText(Object arg0, String arg1) { - LOG.finest("SET TEXT "+arg0+" "+arg1); - } - - /** - * {@inheritDoc} - */ - public void setType(Object arg0, int arg1) { - LOG.finest("SET TYPE "+arg0+" "+arg1); - } -} diff --git a/bundles/org.scribble.protocol.parser/src/main/java/org/scribble/protocol/parser/osgi/Activator.java b/bundles/org.scribble.protocol.parser/src/main/java/org/scribble/protocol/parser/osgi/Activator.java deleted file mode 100644 index 4cc19abd6..000000000 --- a/bundles/org.scribble.protocol.parser/src/main/java/org/scribble/protocol/parser/osgi/Activator.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright 2009-11 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.parser.osgi; - -import java.util.Properties; -import java.util.logging.Level; -import java.util.logging.Logger; - -import org.osgi.framework.BundleActivator; -import org.osgi.framework.BundleContext; -import org.scribble.protocol.parser.ProtocolParser; -import org.scribble.protocol.parser.antlr.ANTLRProtocolParser; - -/** - * Activator. - * - */ -public class Activator implements BundleActivator { - - private static final Logger LOG=Logger.getLogger(Activator.class.getName()); - - /** - * {@inheritDoc} - */ - public void start(BundleContext context) throws Exception { - Properties props = new Properties(); - - ANTLRProtocolParser pp=new ANTLRProtocolParser(); - - context.registerService(ProtocolParser.class.getName(), - pp, props); - - if (LOG.isLoggable(Level.FINE)) { - LOG.fine("Protocol parser registered"); - } - } - - /** - * {@inheritDoc} - */ - public void stop(BundleContext context) throws Exception { - } - -} diff --git a/bundles/org.scribble.protocol.parser/src/main/resources/lib/antlr-3.2.jar b/bundles/org.scribble.protocol.parser/src/main/resources/lib/antlr-3.2.jar deleted file mode 100644 index fdd167d44..000000000 Binary files a/bundles/org.scribble.protocol.parser/src/main/resources/lib/antlr-3.2.jar and /dev/null differ diff --git a/bundles/org.scribble.protocol.parser/src/test/java/org/scribble/protocol/parser/antlr/ANTLRMessageUtilTest.java b/bundles/org.scribble.protocol.parser/src/test/java/org/scribble/protocol/parser/antlr/ANTLRMessageUtilTest.java deleted file mode 100644 index dac23f4e6..000000000 --- a/bundles/org.scribble.protocol.parser/src/test/java/org/scribble/protocol/parser/antlr/ANTLRMessageUtilTest.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.parser.antlr; - -import static org.junit.Assert.*; - -import org.scribble.common.logging.Journal; - -public class ANTLRMessageUtilTest { - - @org.junit.Test - public void testGetMessageText() { - String message="Hello World"; - String text="line 1:1 "+message; - - String result=ANTLRMessageUtil.getMessageText(text); - - if (result == null) { - fail("Result is null"); - } - - if (result.equals(message) == false) { - fail("Message mismatch, '"+result+"' against expected '"+message+"'"); - } - } - - @org.junit.Test - public void testGetProperties() { - String first="namespace x.y.z;\r\nimport a.b.c;\r\n\r\nprotocol Test {\r\n\t"; - String second="roleX A, B;\r\n;\r\n"; - String document=first+second; - - String message="Don't understand roleX"; - String line="5"; - String col="1"; - String text="line "+line+":"+col+" "+message; - - java.util.Map result=ANTLRMessageUtil.getProperties(text, document); - - if (result == null) { - fail("Result is null"); - } - - Integer lineProp=(Integer)result.get(Journal.START_LINE); - Integer colProp=(Integer)result.get(Journal.START_COLUMN); - Integer posProp=(Integer)result.get(Journal.START_POSITION); - - if (lineProp == null) { - fail("Line not found"); - } - - if (lineProp.intValue() != 5) { - fail("Line is not 5: "+lineProp); - } - - if (colProp == null) { - fail("Column not found"); - } - - if (colProp.intValue() != 1) { - fail("Column is not 1: "+colProp); - } - - if (posProp == null) { - fail("Position not found"); - } - - if (posProp.intValue() != first.length()) { - fail("Position is not "+first.length()+": "+posProp); - } - } -} diff --git a/bundles/org.scribble.protocol.parser/src/test/java/org/scribble/protocol/parser/antlr/ANTLRProtocolParserTest.java b/bundles/org.scribble.protocol.parser/src/test/java/org/scribble/protocol/parser/antlr/ANTLRProtocolParserTest.java deleted file mode 100644 index bd596672b..000000000 --- a/bundles/org.scribble.protocol.parser/src/test/java/org/scribble/protocol/parser/antlr/ANTLRProtocolParserTest.java +++ /dev/null @@ -1,357 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.parser.antlr; - -import static org.junit.Assert.*; - -import org.scribble.common.logging.CachedJournal; -import org.scribble.common.logging.CachedJournal.IssueDetails; -import org.scribble.common.logging.CachedJournal.IssueType; -import org.scribble.common.logging.Journal; -import org.scribble.common.model.Annotation; -import org.scribble.common.resource.ByteArrayContent; -import org.scribble.protocol.model.ModelObject; -import org.scribble.protocol.model.ProtocolModel; -import org.scribble.protocol.model.Visitor; -import org.scribble.protocol.parser.AnnotationProcessor; - -public class ANTLRProtocolParserTest { - - @org.junit.Test - public void testDetectCorrectPosition() { - String first="import MT;\r\n\r\nprotocol Test {\r\n\t"; - String second="roleX"; - String third=" "; - String fourth="A"; - //String fifth=";\r\n}\r\n"; - String protocol=first+second+third+fourth; - - ByteArrayContent content=new ByteArrayContent(protocol.getBytes()); - - ANTLRProtocolParser parser=new ANTLRProtocolParser(); - - CachedJournal journal=new CachedJournal(); - - try { - ProtocolModel pm=parser.parse(null, content, journal); - - if (pm != null) { - fail("Returned protocol model should be null due to error"); - } - } catch (Exception e) { - fail("Failed to parse protocol"); - } - - if (journal.getIssues().size() != 1) { - fail("Issue count not 1: "+journal.getIssues().size()); - } - - IssueDetails id=journal.getIssues().get(0); - - if (id.getIssueType() != IssueType.Error) { - fail("Issue was not an error"); - } - - Integer lineProp=(Integer)id.getProperties().get(Journal.START_LINE); - Integer colProp=(Integer)id.getProperties().get(Journal.START_COLUMN); - Integer posProp=(Integer)id.getProperties().get(Journal.START_POSITION); - Integer endposProp=(Integer)id.getProperties().get(Journal.END_POSITION); - - if (lineProp == null) { - fail("Line not found"); - } - - if (lineProp.intValue() != 4) { - fail("Line is not 4: "+lineProp); - } - - if (colProp == null) { - fail("Column not found"); - } - - if (colProp.intValue() != 1) { - fail("Column is not 1: "+colProp); - } - - if (posProp == null) { - fail("Start Position not found"); - } - - if (posProp.intValue() != first.length()) { //+second.length()+third.length()) { - fail("Start Position is not "+(first.length())+": "+posProp); - //fail("Start Position is not "+(first.length()+second.length()+third.length())+": "+posProp); - } - - if (endposProp == null) { - fail("End Position not found"); - } - - //int endpos=first.length()+second.length()+third.length()+fourth.length()-1; // -1 because we want the last character - int endpos=first.length()+second.length()-1; // -1 because we want the last character - - if (endposProp.intValue() != endpos) { - fail("End Position is not "+endpos+": "+endposProp); - } - } - - @org.junit.Test - public void testExtensionChoice() { - String first="protocol Test {\r\n[["; - String comment1=" Comment 1 "; - String second="]]\r\n\tchoice at Buyer {\r\n[["; - String comment2=" Comment 2 "; - String third="]]\r\n\t\top1(M1) from Buyer to Seller;\r\n\t} or {\r\n[["; - String comment3=" Comment 3 "; - String fourth="]]\r\n\t\top2(M2) from Buyer to Seller;\r\n"; - String fifth="\t}\r\n"; - String sixth="}\r\n"; - String protocol=first+comment1+second+comment2+third+comment3+fourth+fifth+sixth; - - ByteArrayContent content=new ByteArrayContent(protocol.getBytes()); - - ANTLRProtocolParser parser=new ANTLRProtocolParser(); - - TestAnnotationProcessor ext=new TestAnnotationProcessor(); - parser.setAnnotationProcessor(ext); - - CachedJournal journal=new CachedJournal(); - - try { - ProtocolModel pm=parser.parse(null, content, journal); - - if (pm == null) { - fail("Protocol Model should not be null"); - } - } catch (Exception e) { - fail("Failed to parse protocol"); - } - - if (journal.getIssues().size() != 0) { - fail("No issues should have been reported: "+journal.getIssues().size()); - } - - if (ext.getAnnotations().size() != 3) { - fail("Annotations expected: "+ext.getAnnotations().size()); - } - - /* - if (ext.getModelObjects().size() != 3) { - fail("ModelObjects expected: "+ext.getModelObjects().size()); - } - */ - - if (ext.getAnnotations().get(0).equals(comment2) == false) { - fail("Annotation 0 not expected"); - } - - if (ext.getAnnotations().get(1).equals(comment3) == false) { - fail("Annotation 1 not expected"); - } - - if (ext.getAnnotations().get(2).equals(comment1) == false) { - fail("Annotation 2 not expected"); - } - - /* - if ((ext.getModelObjects().get(0) instanceof When) == false) { - fail("ModelObject 0 not when"); - } - - if (((When)ext.getModelObjects().get(0)).getMessageSignature().getOperation().equals("op1") == false) { - fail("ModelObject 0 not op1"); - } - - if ((ext.getModelObjects().get(1) instanceof When) == false) { - fail("ModelObject 1 not when"); - } - - if (((When)ext.getModelObjects().get(1)).getMessageSignature().getOperation().equals("op2") == false) { - fail("ModelObject 1 not op2"); - } - - if ((ext.getModelObjects().get(2) instanceof Choice) == false) { - fail("ModelObject 2 not choice"); - } - */ - } - - @org.junit.Test - public void testProtocolAnnotation() { - String first="[["; - String comment1=" Comment 1 "; - String second="]]\r\nimport Order;\r\n[["; - String comment2=" Comment 2 "; - String third="]]\r\nprotocol Test {\r\n"; - String fourth="}\r\n"; - String protocol=first+comment1+second+comment2+third+fourth; - - ByteArrayContent content=new ByteArrayContent(protocol.getBytes()); - - ANTLRProtocolParser parser=new ANTLRProtocolParser(); - - TestAnnotationProcessor ext=new TestAnnotationProcessor(); - parser.setAnnotationProcessor(ext); - - CachedJournal journal=new CachedJournal(); - - try { - ProtocolModel pm=parser.parse(null, content, journal); - - if (pm == null) { - fail("Protocol Model should not be null"); - } - } catch (Exception e) { - fail("Failed to parse protocol"); - } - - if (journal.getIssues().size() != 0) { - fail("No issues should have been reported: "+journal.getIssues().size()); - } - - if (ext.getAnnotations().size() != 2) { - fail("2 Annotations expected: got "+ext.getAnnotations().size()); - } - - /* - if (ext.getModelObjects().size() != 2) { - fail("2 ModelObjects expected: got "+ext.getModelObjects().size()); - } - */ - - if (ext.getAnnotations().get(0).equals(comment1) == false) { - fail("Annotation 0 not expected"); - } - - /* - if ((ext.getModelObjects().get(0) instanceof TypeImportList) == false) { - fail("ModelObject 0 not TypeImportList"); - } - */ - - if (ext.getAnnotations().get(1).equals(comment2) == false) { - fail("Annotation 1 not expected"); - } - - /* - if ((ext.getModelObjects().get(1) instanceof Protocol) == false) { - fail("ModelObject 1 not Protocol"); - } - */ - } - - - @org.junit.Test - public void testNestedProtocolAnnotation() { - String first="[["; - String comment1=" Comment 1 "; - String second="]]\r\nimport Order;\r\n[["; - String comment2=" Comment 2 "; - String third="]]\r\nprotocol Test {\r\n[["; - String comment3=" Comment 3 "; - String fourth="]]\r\n\tprotocol Nested {\r\n\t}\r\n}\r\n"; - String protocol=first+comment1+second+comment2+third+comment3+fourth; - - ByteArrayContent content=new ByteArrayContent(protocol.getBytes()); - - ANTLRProtocolParser parser=new ANTLRProtocolParser(); - - TestAnnotationProcessor ext=new TestAnnotationProcessor(); - parser.setAnnotationProcessor(ext); - - CachedJournal journal=new CachedJournal(); - - try { - ProtocolModel pm=parser.parse(null, content, journal); - - if (pm == null) { - fail("Protocol Model should not be null"); - } - } catch (Exception e) { - fail("Failed to parse protocol"); - } - - if (journal.getIssues().size() != 0) { - fail("No issues should have been reported: "+journal.getIssues().size()); - } - - if (ext.getAnnotations().size() != 3) { - fail("3 Annotations expected: got "+ext.getAnnotations().size()); - } - - if (ext.getAnnotations().get(0).equals(comment1) == false) { - fail("Annotation 0 not expected"); - } - - /* - if ((ext.getModelObjects().get(0) instanceof TypeImportList) == false) { - fail("ModelObject 0 not TypeImportList"); - } - */ - - // NOTE: Nested protocols processed before top level, so the comments - // associated with the protocols are reversed - - if (ext.getAnnotations().get(1).equals(comment3) == false) { - fail("Annotation 1 not expected"); - } - - /* - if ((ext.getModelObjects().get(1) instanceof Protocol) == false) { - fail("ModelObject 1 not Protocol"); - } - */ - - if (ext.getAnnotations().get(2).equals(comment2) == false) { - fail("Annotation 2 not expected"); - } - - /* - if ((ext.getModelObjects().get(2) instanceof Protocol) == false) { - fail("ModelObject 2 not Protocol"); - } - */ - } - - public class TestComment extends ModelObject { - private String m_comment=null; - - public TestComment(String comment) { - m_comment = comment; - } - - public String getComment() { - return (m_comment); - } - - public void visit(Visitor visitor) { - } - } - - public class TestAnnotationProcessor implements AnnotationProcessor { - - private java.util.List m_annotations=new java.util.Vector(); - - public Annotation getAnnotation(String annotation, java.util.Map properties, - Journal journal) { - m_annotations.add(annotation); - return (null); - } - - public java.util.List getAnnotations() { - return (m_annotations); - } - } -} diff --git a/bundles/org.scribble.protocol.projection/LICENSE.txt b/bundles/org.scribble.protocol.projection/LICENSE.txt deleted file mode 100644 index 29f81d812..000000000 --- a/bundles/org.scribble.protocol.projection/LICENSE.txt +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - 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 - - http://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. diff --git a/bundles/org.scribble.protocol.projection/META-INF/MANIFEST.MF b/bundles/org.scribble.protocol.projection/META-INF/MANIFEST.MF deleted file mode 100644 index fe95c8889..000000000 --- a/bundles/org.scribble.protocol.projection/META-INF/MANIFEST.MF +++ /dev/null @@ -1,19 +0,0 @@ -Manifest-Version: 1.0 -Bundle-ManifestVersion: 2 -Bundle-Name: Scribble Protocol Projection -Bundle-SymbolicName: org.scribble.protocol.projection;singleton:=true -Bundle-Version: 2.1.0.SNAPSHOT -Bundle-Vendor: www.scribble.org -Import-Package: org.osgi.framework, - org.osgi.util.tracker, - org.scribble.common.logging, - org.scribble.protocol, - org.scribble.protocol.model, - org.scribble.protocol.projection, - org.scribble.protocol.validation, - org.scribble.protocol.util -Export-Package: org.scribble.protocol.projection.impl, - org.scribble.protocol.projection.util -Bundle-RequiredExecutionEnvironment: JavaSE-1.6 -Bundle-ActivationPolicy: lazy -Bundle-Activator: org.scribble.protocol.projection.osgi.Activator diff --git a/bundles/org.scribble.protocol.projection/build.properties b/bundles/org.scribble.protocol.projection/build.properties deleted file mode 100644 index df02314e5..000000000 --- a/bundles/org.scribble.protocol.projection/build.properties +++ /dev/null @@ -1,13 +0,0 @@ -source.. = src/main/java/,\ - src/main/resources/ -output.. = bin/ -bin.includes = META-INF/,\ - .,\ - LICENSE.txt -src.includes = .classpath,\ - .project,\ - LICENSE.txt,\ - META-INF/,\ - build.properties,\ - pom.xml,\ - src/ diff --git a/bundles/org.scribble.protocol.projection/pom.xml b/bundles/org.scribble.protocol.projection/pom.xml deleted file mode 100644 index 28024b36c..000000000 --- a/bundles/org.scribble.protocol.projection/pom.xml +++ /dev/null @@ -1,44 +0,0 @@ - - 4.0.0 - org.scribble.bundles - org.scribble.protocol.projection - jar - 2.1.0-SNAPSHOT - Scribble::Bundles::ProtocolProjection - - - org.scribble - bundles - 2.1.0-SNAPSHOT - - - - - org.scribble.bundles - org.scribble.common - ${scribble.bundles.version} - - - org.scribble.bundles - org.scribble.protocol - ${scribble.bundles.version} - - - org.osgi - org.osgi.core - ${osgi.version} - - - org.osgi - org.osgi.compendium - ${osgi.version} - - - junit - junit - test - - - - diff --git a/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/AbstractBlockProjectorRule.java b/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/AbstractBlockProjectorRule.java deleted file mode 100644 index 833f6d920..000000000 --- a/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/AbstractBlockProjectorRule.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.projection.impl; - -import java.util.logging.Logger; - -import org.scribble.common.logging.Journal; -import org.scribble.protocol.model.Activity; -import org.scribble.protocol.model.Block; -import org.scribble.protocol.model.ModelObject; -import org.scribble.protocol.model.Role; -import org.scribble.protocol.util.ActivityUtil; - -/** - * This class provides the Block implementation of the - * projector rule. - */ -public abstract class AbstractBlockProjectorRule implements ProjectorRule { - - private static final Logger LOG=Logger.getLogger(AbstractBlockProjectorRule.class.getName()); - - /** - * This method creates a new block of the appropriate - * type. - * - * @return The block - */ - protected abstract Block createBlock(); - - /** - * This method projects the supplied model object based on the - * specified role. - * - * @param context The projector context - * @param model The model object - * @param role The role - * @param l The model listener - * @return The projected model object - */ - public ModelObject project(ProtocolProjectorContext context, ModelObject model, - Role role, Journal l) { - Block ret=createBlock(); - Block source=(Block)model; - - ret.derivedFrom(source); - - context.pushState(); - - for (int i=0; i < source.getContents().size(); i++) { - Object act=context.project(source.getContents().get(i), role, l); - - if (act instanceof Activity) { - ret.getContents().add((Activity)act); - } else if (act instanceof java.util.List) { - - for (Object a2 : (java.util.List)act) { - if (a2 instanceof Activity) { - ret.getContents().add((Activity)a2); - } else { - LOG.severe("Unexpected element returns from block projection: "+a2); - } - } - } - } - - context.popState(); - - // Only return block if it contains atleast one behavioural activity - if (isFilterOutEmptyContent()) { - int behaviourCount=0; - for (Activity act : ret.getContents()) { - if (ActivityUtil.isBehaviour(act)) { - behaviourCount++; - } - } - if (behaviourCount == 0) { - ret = null; - } - } - - return (ret); - } - - /** - * This method determines whether a block with empty content should be - * filtered out. - * - * @return Whether an empty block should be filtered out - */ - protected boolean isFilterOutEmptyContent() { - return (true); - } -} diff --git a/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/BlockProjectorRule.java b/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/BlockProjectorRule.java deleted file mode 100644 index 7a9e4799d..000000000 --- a/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/BlockProjectorRule.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.projection.impl; - -import org.scribble.protocol.model.Block; -import org.scribble.protocol.model.ModelObject; - -/** - * This class provides the Block implementation of the - * projector rule. - */ -public class BlockProjectorRule extends AbstractBlockProjectorRule { - - /** - * This method determines whether the projection rule is - * appropriate for the supplied model object. - * - * @param obj The model object to be projected - * @return Whether the rule is relevant for the - * model object - */ - public boolean isSupported(ModelObject obj) { - return (obj.getClass() == Block.class); - } - - /** - * This method creates a new block of the appropriate - * type. - * - * @return The block - */ - protected Block createBlock() { - return (new Block()); - } -} diff --git a/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/ChoiceProjectorRule.java b/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/ChoiceProjectorRule.java deleted file mode 100644 index 8602905b6..000000000 --- a/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/ChoiceProjectorRule.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.projection.impl; - -import org.scribble.common.logging.Journal; -import org.scribble.protocol.model.Block; -import org.scribble.protocol.model.Choice; -import org.scribble.protocol.model.ModelObject; -import org.scribble.protocol.model.Role; -import org.scribble.protocol.projection.util.ChoiceMergingUtil; - -/** - * This class provides the Choice implementation of the - * projector rule. - */ -public class ChoiceProjectorRule implements ProjectorRule { - - /** - * System property: should choice constructs be permitted to have empty paths - * and therefore be optional? - */ - public static final String ALLOW_OPTIONAL = "scribble.choice.allowOptional"; - - /** - * This method determines whether the projection rule is - * appropriate for the supplied model object. - * - * @param obj The model object to be projected - * @return Whether the rule is relevant for the - * model object - */ - public boolean isSupported(ModelObject obj) { - return (obj.getClass() == Choice.class); - } - - /** - * This method projects the supplied model object based on the - * specified role. - * - * @param context The projector context - * @param model The model object - * @param role The role - * @param l The model listener - * @return The projected model object - */ - public Object project(ProtocolProjectorContext context, ModelObject model, - Role role, Journal l) { - Choice projected=new Choice(); - Choice source=(Choice)model; - boolean optional=false; - - projected.derivedFrom(source); - - // Only project role if the same as the located role. Otherwise description - // should just indicate that the decision is being made at another role - if (source.getRole() != null && source.getRole().equals(role)) { - projected.setRole(new Role(source.getRole())); - } - - for (int i=0; i < source.getPaths().size(); i++) { - Block block=(Block) - context.project(source.getPaths().get(i), role, - l); - - if (block != null) { - if (block.getContents().size() == 1 - && block.getContents().get(0) instanceof Choice - && isSameRole(projected, (Choice)block.getContents().get(0))) { - projected.getPaths().addAll(((Choice)block.getContents().get(0)).getPaths()); - } else { - projected.getPaths().add(block); - } - } else { - optional = true; - } - } - - return (ChoiceMergingUtil.merge(projected, role, l, optional)); - } - - /** - * Check whether roles are the same. - * - * @param c1 First choice - * @param c2 Second choice - * @return Whether roles are same - */ - protected boolean isSameRole(Choice c1, Choice c2) { - if (c1.getRole() == null && c2.getRole() == null) { - return (true); - } else if (c1.getRole() == null || c2.getRole() == null) { - return (false); - } else { - return (c1.getRole().equals(c2.getRole())); - } - } -} diff --git a/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/DataTypeProjectorRule.java b/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/DataTypeProjectorRule.java deleted file mode 100644 index 0c18b383b..000000000 --- a/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/DataTypeProjectorRule.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.projection.impl; - -import org.scribble.common.logging.Journal; -import org.scribble.protocol.model.DataType; -import org.scribble.protocol.model.ModelObject; -import org.scribble.protocol.model.Role; - -/** - * This class provides the DataType implementation of the - * projector rule. - */ -public class DataTypeProjectorRule implements ProjectorRule { - - /** - * This method determines whether the projection rule is - * appropriate for the supplied model object. - * - * @param obj The model object to be projected - * @return Whether the rule is relevant for the - * model object - */ - public boolean isSupported(ModelObject obj) { - return (obj.getClass() == DataType.class); - } - - /** - * This method projects the supplied model object based on the - * specified role. - * - * @param context The context - * @param model The model object - * @param role The role - * @param l The model listener - * @return The projected model object - */ - public Object project(ProtocolProjectorContext context, ModelObject model, - Role role, Journal l) { - DataType ret=new DataType(); - DataType source=(DataType)model; - - ret.derivedFrom(source); - - ret.setDetails(source.getDetails()); - - return (ret); - } -} diff --git a/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/DefaultProjectorContext.java b/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/DefaultProjectorContext.java deleted file mode 100644 index 4fdc9a319..000000000 --- a/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/DefaultProjectorContext.java +++ /dev/null @@ -1,264 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.projection.impl; - -import java.util.logging.Logger; - -import org.scribble.common.logging.Journal; -import org.scribble.protocol.ProtocolContext; -import org.scribble.protocol.model.ModelObject; -import org.scribble.protocol.model.Protocol; -import org.scribble.protocol.model.Role; -import org.scribble.protocol.validation.ProtocolValidationManager; - -/** - * This class represents the default projection context. - */ -public class DefaultProjectorContext implements ProtocolProjectorContext { - - private static Logger logger = Logger.getLogger(DefaultProjectorContext.class.getName()); - - private final static java.util.List RULES=new java.util.Vector(); - - private java.util.List _customRules=null; - - private ProtocolContext _context=null; - private ProtocolValidationManager _pvm=null; - private Scope _scope=new Scope(); - private java.util.List _scopeStack=new java.util.Vector(); - private java.util.Map> _definitionRoleMap= - new java.util.HashMap>(); - - static { - RULES.add(new BlockProjectorRule()); - RULES.add(new InterruptProjectorRule()); - RULES.add(new ChoiceProjectorRule()); - RULES.add(new DirectedChoiceProjectorRule()); - RULES.add(new OnMessageProjectorRule()); - RULES.add(new ProtocolImportListProjectorRule()); - RULES.add(new ProtocolImportProjectorRule()); - RULES.add(new TypeImportListProjectorRule()); - RULES.add(new TypeImportProjectorRule()); - RULES.add(new InteractionProjectorRule()); - RULES.add(new MessageSignatureProjectorRule()); - RULES.add(new ParallelProjectorRule()); - RULES.add(new IntroducesProjectorRule()); - RULES.add(new RoleProjectorRule()); - RULES.add(new ProtocolModelProjectorRule()); - RULES.add(new ProtocolProjectorRule()); - RULES.add(new ParameterProjectorRule()); - RULES.add(new ProtocolReferenceProjectorRule()); - RULES.add(new RepeatProjectorRule()); - RULES.add(new RecBlockProjectorRule()); - RULES.add(new RecursionProjectorRule()); - RULES.add(new RunProjectorRule()); - RULES.add(new InlineProjectorRule()); - RULES.add(new DoProjectorRule()); - RULES.add(new DataTypeProjectorRule()); - RULES.add(new TypeReferenceProjectorRule()); - RULES.add(new UnorderedProjectorRule()); - RULES.add(new EndProjectorRule()); - } - - /** - * This is the default constructor for the projection context. - * - * @param context The protocol context - * @param pvm The protocol validation manager - */ - public DefaultProjectorContext(ProtocolContext context, ProtocolValidationManager pvm) { - _context = context; - _pvm = pvm; - } - - /** - * This is the default constructor for the projection context. - * - * @param context The protocol context - * @param pvm The protocol validation manager - * @param customRules The optional list of custom rules - */ - public DefaultProjectorContext(ProtocolContext context, ProtocolValidationManager pvm, - java.util.List customRules) { - this(context, pvm); - _customRules = customRules; - } - - /** - * This method returns the protocol context. - * - * @return The protocol context - */ - public ProtocolContext getProtocolContext() { - return (_context); - } - - /** - * This method returns the protocol validation manager. - * - * @return The protocol validation manager - */ - public ProtocolValidationManager getProtocolValidationManager() { - return (_pvm); - } - - /** - * This method projects the supplied model object based on the - * specified role. - * - * @param model The model object - * @param role The role - * @param l The model listener - * @return The projected model object - */ - public Object project(ModelObject model, Role role, - Journal l) { - Object ret=null; - - for (int i=0; model != null && ret == null && i < getRules().size(); i++) { - if (getRules().get(i).isSupported(model)) { - ret = getRules().get(i).project(this, model, role, - l); - } - } - - if (ret == null && _customRules != null) { - for (int i=0; model != null && ret == null && i < getCustomRules().size(); i++) { - if (getCustomRules().get(i).isSupported(model)) { - ret = getCustomRules().get(i).project(this, model, role, - l); - } - } - } - - return (ret); - } - - /** - * This method returns a list of projection rules. - * - * @return The list of projection rules - */ - public java.util.List getRules() { - return (RULES); - } - - /** - * This method returns a list of custom projection rules. - * - * @return The list of custom projection rules - */ - public java.util.List getCustomRules() { - return (_customRules); - } - - /** - * This method returns the named state from the current - * scope. - * - * @param name The state name - * @return The state value, or null if not found - */ - public Object getState(String name) { - return (_scope.getState(name)); - } - - /** - * This method sets the value associated with the supplied - * name in the current state scope. - * - * @param name The state name - * @param value The state value - */ - public void setState(String name, Object value) { - _scope.setState(name, value); - } - - /** - * This method pushes the current state onto a stack. - */ - public void pushState() { - _scope.pushState(); - } - - /** - * This method pops the current state from the stack. - */ - public void popState() { - _scope.popState(); - } - - /** - * This method pushes the current scope onto a stack. - */ - public void pushScope() { - _scopeStack.add(0, _scope); - _scope = new Scope(); - } - - /** - * This method pops the current scope from the stack. - */ - public void popScope() { - if (_scopeStack.size() > 0) { - _scope = _scopeStack.remove(0); - } else { - logger.severe("No state entry to pop from stack"); - } - } - - /** - * This method determines whether the context is associated - * with the outer scope. - * - * @return Whether the context is for the outer scope - */ - public boolean isOuterScope() { - return (_scopeStack.size() < 1); - } - - /** - * This method registers an interest in the projected role - * associated with the supplied definition. - * - * @param defn The definition - * @param role The projected role of interest - */ - public void registerInterest(Protocol defn, Role role) { - java.util.List roles=_definitionRoleMap.get(defn); - - if (roles == null) { - roles = new java.util.Vector(); - _definitionRoleMap.put(defn, roles); - } - - if (!roles.contains(role)) { - roles.add(role); - } - } - - /** - * This method returns the list of roles of interest - * for the supplied definition. - * - * @param defn The definition - * @return The list of roles, or null if no roles have - * registered interest in the definition - */ - public java.util.List getRolesOfInterestForDefinition(Protocol defn) { - return (_definitionRoleMap.get(defn)); - } -} diff --git a/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/DirectedChoiceProjectorRule.java b/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/DirectedChoiceProjectorRule.java deleted file mode 100644 index fd53a8e57..000000000 --- a/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/DirectedChoiceProjectorRule.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Copyright 2009-11 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.projection.impl; - -import java.text.MessageFormat; - -import org.scribble.common.logging.Journal; -import org.scribble.protocol.model.DirectedChoice; -import org.scribble.protocol.model.ModelObject; -import org.scribble.protocol.model.OnMessage; -import org.scribble.protocol.model.Role; -import org.scribble.protocol.util.RoleUtil; - -/** - * This class provides the DirectedChoice implementation of the - * projector rule. - */ -public class DirectedChoiceProjectorRule implements ProjectorRule { - - /** - * This method determines whether the projection rule is - * appropriate for the supplied model object. - * - * @param obj The model object to be projected - * @return Whether the rule is relevant for the - * model object - */ - public boolean isSupported(ModelObject obj) { - return (obj.getClass() == DirectedChoice.class); - } - - /** - * This method projects the supplied model object based on the - * specified role. - * - * @param context The context - * @param model The model object - * @param role The role - * @param l The model listener - * @return The projected model object - */ - public Object project(ProtocolProjectorContext context, ModelObject model, - Role role, Journal l) { - DirectedChoice ret=new DirectedChoice(); - DirectedChoice source=(DirectedChoice)model; - boolean merge=false; - boolean allpaths=true; - - ret.derivedFrom(source); - - if (source.getFromRole() != null && source.getFromRole().equals(role)) { - for (Role r : source.getToRoles()) { - ret.getToRoles().add(new Role(r.getName())); - } - } else if (source.getFromRole() != null && source.getToRoles().contains(role)) { - ret.setFromRole(new Role(source.getFromRole())); - } else { - merge = true; - } - - if (ret != null) { - for (int i=0; i < source.getOnMessages().size(); i++) { - OnMessage om=(OnMessage) - context.project(source.getOnMessages().get(i), role, - l); - - if (om != null) { - ret.getOnMessages().add(om); - - if (merge) { - // Check if role involved in path - java.util.Set roles=RoleUtil.getUsedRoles(source.getOnMessages().get(i)); - - if (roles == null || !roles.contains(role)) { - allpaths = false; - - // Remove path - ret.getOnMessages().remove(om); - } - } - } else { - allpaths = false; - } - } - - if (merge) { - if (ret.getOnMessages().size() == 0) { - // Not projected to this role - ret = null; - - } else if (!allpaths) { - l.error(MessageFormat.format( - java.util.PropertyResourceBundle.getBundle( - "org.scribble.protocol.projection.impl.Messages"). - getString("_CHOICE_EMPTY_PATH"), - role.getName()), source.getProperties()); - } - } - } - - return (ret); - } -} diff --git a/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/DoProjectorRule.java b/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/DoProjectorRule.java deleted file mode 100644 index f42030991..000000000 --- a/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/DoProjectorRule.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.projection.impl; - -import org.scribble.common.logging.Journal; -import org.scribble.protocol.model.Block; -import org.scribble.protocol.model.Do; -import org.scribble.protocol.model.Interrupt; -import org.scribble.protocol.model.ModelObject; -import org.scribble.protocol.model.Role; - -/** - * This class provides the Do implementation of the - * projector rule. - */ -public class DoProjectorRule implements ProjectorRule { - - /** - * This method determines whether the projection rule is - * appropriate for the supplied model object. - * - * @param obj The model object to be projected - * @return Whether the rule is relevant for the - * model object - */ - public boolean isSupported(ModelObject obj) { - return (obj.getClass() == Do.class); - } - - /** - * This method projects the supplied model object based on the - * specified role. - * - * @param context The context - * @param model The model object - * @param role The role - * @param l The model listener - * @return The projected model object - */ - public Object project(ProtocolProjectorContext context, ModelObject model, - Role role, Journal l) { - Do ret=new Do(); - Do source=(Do)model; - - ret.derivedFrom(source); - - ret.setBlock((Block)context.project(source.getBlock(), role, l)); - - for (int i=0; i < source.getInterrupts().size(); i++) { - Interrupt c=(Interrupt) - context.project(source.getInterrupts().get(i), - role, l); - - if (c != null) { - ret.getInterrupts().add(c); - } - } - - // Shouldn't project try/escape if main block has no activities - if (ret.getBlock().getContents().size() == 0) { - ret = null; - } - - return (ret); - } -} diff --git a/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/EndProjectorRule.java b/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/EndProjectorRule.java deleted file mode 100644 index 09d9da776..000000000 --- a/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/EndProjectorRule.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.projection.impl; - -import org.scribble.common.logging.Journal; -import org.scribble.protocol.model.End; -import org.scribble.protocol.model.ModelObject; -import org.scribble.protocol.model.Role; - -/** - * This class provides the End implementation of the - * projector rule. - */ -public class EndProjectorRule implements ProjectorRule { - - /** - * This method determines whether the projection rule is - * appropriate for the supplied model object. - * - * @param obj The model object to be projected - * @return Whether the rule is relevant for the - * model object - */ - public boolean isSupported(ModelObject obj) { - return (obj.getClass() == End.class); - } - - /** - * This method projects the supplied model object based on the - * specified role. - * - * @param context The context - * @param model The model object - * @param role The role - * @param l The model listener - * @return The projected model object - */ - public Object project(ProtocolProjectorContext context, ModelObject model, - Role role, Journal l) { - End ret=new End(); - End end=(End)model; - - ret.derivedFrom(end); - - return (ret); - } -} diff --git a/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/InlineProjectorRule.java b/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/InlineProjectorRule.java deleted file mode 100644 index 612a9ae54..000000000 --- a/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/InlineProjectorRule.java +++ /dev/null @@ -1,137 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.projection.impl; - -import org.scribble.common.logging.Journal; -import org.scribble.protocol.model.Inline; -import org.scribble.protocol.model.ModelObject; -import org.scribble.protocol.model.Parameter; -import org.scribble.protocol.model.ParameterDefinition; -import org.scribble.protocol.model.Protocol; -import org.scribble.protocol.model.ProtocolImport; -import org.scribble.protocol.model.ProtocolModel; -import org.scribble.protocol.model.ProtocolReference; -import org.scribble.protocol.model.Role; -import org.scribble.protocol.util.ProtocolModelUtil; - -/** - * This class provides the Inline implementation of the - * projector rule. - */ -public class InlineProjectorRule implements ProjectorRule { - - /** - * This method determines whether the projection rule is - * appropriate for the supplied model object. - * - * @param obj The model object to be projected - * @return Whether the rule is relevant for the - * model object - */ - public boolean isSupported(ModelObject obj) { - return (obj.getClass() == Inline.class); - } - - /** - * This method projects the supplied model object based on the - * specified role. - * - * @param context The context - * @param model The model object - * @param role The role - * @param l The model listener - * @return The projected model object - */ - public Object project(ProtocolProjectorContext context, ModelObject model, - Role role, Journal l) { - Inline ret=new Inline(); - Inline source=(Inline)model; - - ret.derivedFrom(source); - - java.util.List params= - source.getParameters(); - int mappedIndex=-1; - - for (int i=0; i < params.size(); i++) { - Parameter db=params.get(i); - - // Don't project declaration if same as role - this - // will be done in the model include statement, - // not the bindings - if (!db.getName().equals(role.getName())) { - - Parameter dbcopy= - new Parameter(db.getName()); - - dbcopy.derivedFrom(db); - - ret.getParameters().add(dbcopy); - } else { - mappedIndex = i; - } - } - - if (source.getProtocolReference() != null) { - Protocol defn=null; - - // Check if protocol import defined for protocol - ProtocolImport pi=ProtocolModelUtil.getProtocolImport(source.getModel(), - source.getProtocolReference()); - - if (pi == null) { - l.error("Referenced protocol '"+source.getProtocolReference().getName() - + "' not found within model or in import statements", source.getProperties()); - } else { - ProtocolModel pm=context.getProtocolContext().getProtocolModel(pi, l); - - if (pm != null) { - defn = pm.getProtocol(); - } else { - l.error("Referenced protocol '"+source.getProtocolReference().getName() - +"' could not be loaded from location '"+pi.getLocation()+"'", - source.getProperties()); - } - } - - if (defn != null && mappedIndex != -1) { - - Role mappedRole=null; - - if (mappedIndex < defn.getParameterDefinitions().size()) { - ParameterDefinition pd=defn.getParameterDefinitions().get(mappedIndex); - - if (pd.getType() != null) { - l.error("Include parameter is not a role", source.getProperties()); - } else { - mappedRole = new Role(pd.getName()); - } - } else { - l.error("Include parameter is not a role", source.getProperties()); - } - - if (mappedRole != null) { - ret.setProtocolReference((ProtocolReference)context.project( - source.getProtocolReference(), mappedRole, l)); - } - } else { - ret = null; - } - } - - return (ret); - } -} diff --git a/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/InteractionProjectorRule.java b/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/InteractionProjectorRule.java deleted file mode 100644 index 7ddb6f5ab..000000000 --- a/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/InteractionProjectorRule.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.projection.impl; - -import org.scribble.common.logging.Journal; -import org.scribble.protocol.model.Interaction; -import org.scribble.protocol.model.MessageSignature; -import org.scribble.protocol.model.ModelObject; -import org.scribble.protocol.model.Role; - -/** - * This class provides the Interaction implementation of the - * projector rule. - */ -public class InteractionProjectorRule implements ProjectorRule { - - /** - * This method determines whether the projection rule is - * appropriate for the supplied model object. - * - * @param obj The model object to be projected - * @return Whether the rule is relevant for the - * model object - */ - public boolean isSupported(ModelObject obj) { - return (obj.getClass() == Interaction.class); - } - - /** - * This method returns a new instance of the interaction model - * object. - * - * @return The new interaction - */ - protected Interaction createInteraction() { - return (new Interaction()); - } - - /** - * This method projects the supplied model object based on the - * specified role.

- * - * @param context The context - * @param model The model object - * @param role The role - * @param l The model listener - * @return The projected model object - */ - public Object project(ProtocolProjectorContext context, ModelObject model, - Role role, Journal l) { - Interaction ret=createInteraction(); - Interaction source=(Interaction)model; - boolean roleFound=false; - - ret.derivedFrom(source); - - if (source.getFromRole() != null) { - - if (source.getFromRole().equals(role)) { - roleFound = true; - } else { - // Only set role if not projected role - // Find role in state - Object state=context.getState(source.getFromRole().getName()); - - if (state instanceof Role) { - Role r=new Role(); - r.setName(source.getFromRole().getName()); - - r.derivedFrom(source.getFromRole()); - - ret.setFromRole(r); - } - } - } - - if (source.getToRoles().size() > 0) { - - if (source.getToRoles().contains(role)) { - roleFound = true; - } else { - for (Role sr : source.getToRoles()) { - // Only set role if not projected role - // Find role in state - Object state=context.getState(sr.getName()); - - if (state instanceof Role) { - Role r=new Role(); - r.setName(sr.getName()); - - r.derivedFrom(sr); - - ret.getToRoles().add(r); - } - } - } - } - - // Check if role found - if (roleFound) { - ret.setMessageSignature((MessageSignature) - context.project(source.getMessageSignature(), - role, l)); - } else { - // Role not associated with the interaction - ret = null; - } - - return (ret); - } -} diff --git a/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/InterruptProjectorRule.java b/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/InterruptProjectorRule.java deleted file mode 100644 index 4a587d434..000000000 --- a/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/InterruptProjectorRule.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.projection.impl; - -import org.scribble.common.logging.Journal; -import org.scribble.protocol.model.Block; -import org.scribble.protocol.model.Interrupt; -import org.scribble.protocol.model.ModelObject; -import org.scribble.protocol.model.Role; - -/** - * This class provides the Interrupt implementation of the - * projector rule. - */ -public class InterruptProjectorRule implements ProjectorRule { - - /** - * This method determines whether the projection rule is - * appropriate for the supplied model object. - * - * @param obj The model object to be projected - * @return Whether the rule is relevant for the - * model object - */ - public boolean isSupported(ModelObject obj) { - return (obj.getClass() == Interrupt.class); - } - - /** - * This method projects the supplied model object based on the - * specified role. - * - * @param context The context - * @param model The model object - * @param role The role - * @param l The model listener - * @return The projected model object - */ - public Object project(ProtocolProjectorContext context, ModelObject model, - Role role, Journal l) { - Interrupt ret=(Interrupt)new Interrupt(); - Interrupt source=(Interrupt)model; - - ret.derivedFrom(source); - - if (source.getBlock() != null) { - - // Project the block - ret.setBlock((Block)context.project(source.getBlock(), - role, l)); - ret.getBlock().setParent(ret); - } - - if (ret.getBlock().getContents().size() == 0) { - // Don't return interrupt, as the block - // content is not relevant for the projected role - ret = null; - } - - return (ret); - } -} diff --git a/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/IntroducesProjectorRule.java b/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/IntroducesProjectorRule.java deleted file mode 100644 index 177f4c257..000000000 --- a/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/IntroducesProjectorRule.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.projection.impl; - -import org.scribble.common.logging.Journal; -import org.scribble.protocol.model.Introduces; -import org.scribble.protocol.model.ModelObject; -import org.scribble.protocol.model.Role; - -/** - * This class provides the Introduces implementation of the - * projector rule. - */ -public class IntroducesProjectorRule implements ProjectorRule { - - /** - * This method determines whether the projection rule is - * appropriate for the supplied model object. - * - * @param obj The model object to be projected - * @return Whether the rule is relevant for the - * model object - */ - public boolean isSupported(ModelObject obj) { - return (obj.getClass() == Introduces.class); - } - - /** - * This method projects the supplied model object based on the - * specified role. - * - * @param context The context - * @param model The model object - * @param role The role - * @param l The model listener - * @return The projected model object - */ - public Object project(ProtocolProjectorContext context, ModelObject model, - Role role, Journal l) { - Introduces ret=new Introduces(); - Introduces source=(Introduces)model; - - ret.derivedFrom(source); - - if (source.getIntroducer().equals(role)) { - - // Project introducer - ret.setIntroducer((Role)context.project(source.getIntroducer(), role, l)); - - // Project as is - for (int i=0; i < source.getIntroducedRoles().size(); i++) { - Role p=(Role)context.project(source.getIntroducedRoles().get(i), role, l); - - if (p != null) { - ret.getIntroducedRoles().add(p); - } - } - } else { - // Don't project, as not relevant to introduced roles - ret = null; - - if (source.getIntroducedRoles().contains(role)) { - // If introducer not in context, then add - if (context.getState(source.getIntroducer().getName()) == null) { - - // Add to context - Role ir=(Role)context.project(source.getIntroducer(), role, l); - - context.setState(ir.getName(), ir); - } - } - } - - return (ret); - } -} diff --git a/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/MessageSignatureProjectorRule.java b/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/MessageSignatureProjectorRule.java deleted file mode 100644 index 56d65dba3..000000000 --- a/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/MessageSignatureProjectorRule.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.projection.impl; - -import org.scribble.common.logging.Journal; -import org.scribble.protocol.model.MessageSignature; -import org.scribble.protocol.model.ModelObject; -import org.scribble.protocol.model.Role; -import org.scribble.protocol.model.TypeReference; - -/** - * This class provides the MessageSignature implementation of the - * projector rule. - */ -public class MessageSignatureProjectorRule implements ProjectorRule { - - /** - * This method determines whether the projection rule is - * appropriate for the supplied model object. - * - * @param obj The model object to be projected - * @return Whether the rule is relevant for the - * model object - */ - public boolean isSupported(ModelObject obj) { - return (obj.getClass() == MessageSignature.class); - } - - /** - * This method projects the supplied model object based on the - * specified role. - * - * @param context The context - * @param model The model object - * @param role The role - * @param l The model listener - * @return The projected model object - */ - public Object project(ProtocolProjectorContext context, ModelObject model, - Role role, Journal l) { - MessageSignature ret=new MessageSignature(); - MessageSignature source=(MessageSignature)model; - - ret.derivedFrom(source); - - ret.setOperation(source.getOperation()); - - for (int i=0; i < source.getTypeReferences().size(); i++) { - TypeReference ref=(TypeReference) - context.project(source.getTypeReferences().get(i), - role, l); - - if (ref != null) { - ret.getTypeReferences().add(ref); - } - } - - return (ret); - } -} diff --git a/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/OnMessageProjectorRule.java b/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/OnMessageProjectorRule.java deleted file mode 100644 index 069b6931f..000000000 --- a/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/OnMessageProjectorRule.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.projection.impl; - -import org.scribble.common.logging.Journal; -import org.scribble.protocol.model.Block; -import org.scribble.protocol.model.MessageSignature; -import org.scribble.protocol.model.ModelObject; -import org.scribble.protocol.model.OnMessage; -import org.scribble.protocol.model.Role; - -/** - * This class provides the OnMessage implementation of the - * projector rule. - */ -public class OnMessageProjectorRule implements ProjectorRule { - - /** - * This method determines whether the projection rule is - * appropriate for the supplied model object. - * - * @param obj The model object to be projected - * @return Whether the rule is relevant for the - * model object - */ - public boolean isSupported(ModelObject obj) { - return (obj.getClass() == OnMessage.class); - } - - /** - * This method projects the supplied model object based on the - * specified role. - * - * @param context The context - * @param model The model object - * @param role The role - * @param l The model listener - * @return The projected model object - */ - public Object project(ProtocolProjectorContext context, ModelObject model, - Role role, Journal l) { - OnMessage ret=(OnMessage)new OnMessage(); - OnMessage source=(OnMessage)model; - - ret.derivedFrom(source); - - ret.setMessageSignature((MessageSignature)context.project(source.getMessageSignature(), - role, l)); - - if (source.getBlock() != null) { - - // Project the block - Block b=(Block)context.project(source.getBlock(), - role, l); - if (b != null) { - ret.setBlock(b); - } - } - - return (ret); - } -} diff --git a/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/ParallelProjectorRule.java b/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/ParallelProjectorRule.java deleted file mode 100644 index 98d92f084..000000000 --- a/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/ParallelProjectorRule.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.projection.impl; - -import org.scribble.common.logging.Journal; -import org.scribble.protocol.model.Block; -import org.scribble.protocol.model.ModelObject; -import org.scribble.protocol.model.Parallel; -import org.scribble.protocol.model.Role; - -/** - * This class provides the Parallel implementation of the - * projector rule. - */ -public class ParallelProjectorRule implements ProjectorRule { - - /** - * This method determines whether the projection rule is - * appropriate for the supplied model object. - * - * @param obj The model object to be projected - * @return Whether the rule is relevant for the - * model object - */ - public boolean isSupported(ModelObject obj) { - return (obj.getClass() == Parallel.class); - } - - /** - * This method projects the supplied model object based on the - * specified role. - * - * @param context The context - * @param model The model object - * @param role The role - * @param l The model listener - * @return The projected model object - */ - public Object project(ProtocolProjectorContext context, ModelObject model, - Role role, Journal l) { - Object ret=null; - Parallel parallel=new Parallel(); - Parallel source=(Parallel)model; - - parallel.derivedFrom(source); - - for (int i=0; i < source.getPaths().size(); i++) { - Block block=(Block) - context.project(source.getPaths().get(i), - role, l); - - if (block != null) { - parallel.getPaths().add(block); - } - } - - // Check if parallel has atleast one path - if (parallel.getPaths().size() > 0) { - ret = parallel; - - // If parallel only has one path, then - // return block - if (parallel.getPaths().size() == 1) { - ret = parallel.getPaths().get(0).getContents(); - } - } - - return (ret); - } -} diff --git a/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/ParameterProjectorRule.java b/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/ParameterProjectorRule.java deleted file mode 100644 index 86a82a460..000000000 --- a/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/ParameterProjectorRule.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.projection.impl; - -import org.scribble.common.logging.Journal; -import org.scribble.protocol.model.ModelObject; -import org.scribble.protocol.model.ParameterDefinition; -import org.scribble.protocol.model.Role; - -/** - * This class provides the Parameter implementation of the - * projector rule. - */ -public class ParameterProjectorRule implements ProjectorRule { - - /** - * This method determines whether the projection rule is - * appropriate for the supplied model object. - * - * @param obj The model object to be projected - * @return Whether the rule is relevant for the - * model object - */ - public boolean isSupported(ModelObject obj) { - return (obj.getClass() == ParameterDefinition.class); - } - - /** - * This method projects the supplied model object based on the - * specified role. - * - * @param context The context - * @param model The model object - * @param role The role - * @param l The model listener - * @return The projected model object - */ - public Object project(ProtocolProjectorContext context, ModelObject model, - Role role, Journal l) { - ParameterDefinition ret=new ParameterDefinition(); - ParameterDefinition source=(ParameterDefinition)model; - - ret.derivedFrom(source); - - ret.setName(source.getName()); - ret.setType(source.getType()); - - - if (!ret.isRole()) { - // Add to state - context.setState(ret.getName(), ret); - } else { - Role r=ret.getRole(); - - if (role.equals(r)) { - ret = null; - } else { - // Register role associated with the parameter - context.setState(r.getName(), r); - } - } - - return (ret); - } -} diff --git a/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/ProjectorRule.java b/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/ProjectorRule.java deleted file mode 100644 index 2cec00488..000000000 --- a/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/ProjectorRule.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.projection.impl; - -import org.scribble.common.logging.Journal; -import org.scribble.protocol.model.ModelObject; -import org.scribble.protocol.model.Role; - -/** - * This interface represents the projection rule used to - * derive another model object associated with a role. - */ -public interface ProjectorRule { - - /** - * This method determines whether the projection rule is - * appropriate for the supplied model object. - * - * @param obj The model object to be projected - * @return Whether the rule is relevant for the - * model object - */ - public boolean isSupported(ModelObject obj); - - /** - * This method projects the supplied model object based on the - * specified role. - * - * @param context The context - * @param model The model object - * @param role The role - * @param l The model listener - * @return The projected model object, or list of model objects - */ - public Object project(ProtocolProjectorContext context, ModelObject model, - Role role, Journal l); -} diff --git a/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/ProtocolImportListProjectorRule.java b/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/ProtocolImportListProjectorRule.java deleted file mode 100644 index aabed643e..000000000 --- a/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/ProtocolImportListProjectorRule.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.projection.impl; - -import org.scribble.common.logging.Journal; -import org.scribble.protocol.model.ModelObject; -import org.scribble.protocol.model.ProtocolImport; -import org.scribble.protocol.model.ProtocolImportList; -import org.scribble.protocol.model.Role; - -/** - * This class provides the ImportList implementation of the - * projector rule. - */ -public class ProtocolImportListProjectorRule implements ProjectorRule { - - /** - * This method determines whether the projection rule is - * appropriate for the supplied model object. - * - * @param obj The model object to be projected - * @return Whether the rule is relevant for the - * model object - */ - public boolean isSupported(ModelObject obj) { - return (obj.getClass() == ProtocolImportList.class); - } - - /** - * This method projects the supplied model object based on the - * specified role. - * - * @param context The context - * @param model The model object - * @param role The role - * @param l The model listener - * @return The projected model object - */ - public Object project(ProtocolProjectorContext context, ModelObject model, - Role role, Journal l) { - ProtocolImportList ret=new ProtocolImportList(); - ProtocolImportList source=(ProtocolImportList)model; - - ret.derivedFrom(source); - - for (int i=0; i < source.getProtocolImports().size(); i++) { - ProtocolImport p=(ProtocolImport)context.project(source.getProtocolImports().get(i), role, l); - - if (p != null) { - ret.getProtocolImports().add(p); - } - } - - return (ret); - } -} diff --git a/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/ProtocolImportProjectorRule.java b/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/ProtocolImportProjectorRule.java deleted file mode 100644 index 29320f8ed..000000000 --- a/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/ProtocolImportProjectorRule.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.projection.impl; - -import org.scribble.common.logging.Journal; -import org.scribble.protocol.model.ModelObject; -import org.scribble.protocol.model.ProtocolImport; -import org.scribble.protocol.model.Role; - -/** - * This class provides the ProtocolImpl implementation of the - * projector rule. - */ -public class ProtocolImportProjectorRule implements ProjectorRule { - - /** - * This method determines whether the projection rule is - * appropriate for the supplied model object. - * - * @param obj The model object to be projected - * @return Whether the rule is relevant for the - * model object - */ - public boolean isSupported(ModelObject obj) { - return (obj.getClass() == ProtocolImport.class); - } - - /** - * This method projects the supplied model object based on the - * specified role. - * - * @param context The context - * @param model The model object - * @param role The role - * @param l The model listener - * @return The projected model object - */ - public Object project(ProtocolProjectorContext context, ModelObject model, - Role role, Journal l) { - ProtocolImport ret=new ProtocolImport(); - ProtocolImport source=(ProtocolImport)model; - - ret.derivedFrom(source); - - ret.setName(source.getName()); - ret.setLocation(source.getLocation()); - - return (ret); - } -} diff --git a/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/ProtocolModelProjectorRule.java b/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/ProtocolModelProjectorRule.java deleted file mode 100644 index 5006e3633..000000000 --- a/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/ProtocolModelProjectorRule.java +++ /dev/null @@ -1,197 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.projection.impl; - -import java.text.MessageFormat; - -import org.scribble.common.logging.Journal; -import org.scribble.protocol.model.Block; -import org.scribble.protocol.model.ImportList; -import org.scribble.protocol.model.ModelObject; -import org.scribble.protocol.model.ParameterDefinition; -import org.scribble.protocol.model.Protocol; -import org.scribble.protocol.model.ProtocolModel; -import org.scribble.protocol.model.RecBlock; -import org.scribble.protocol.model.Role; -import org.scribble.protocol.util.RoleUtil; - -/** - * This class provides the ProtocolModel implementation of the - * projector rule. - */ -public class ProtocolModelProjectorRule implements ProjectorRule { - - /** - * This method determines whether the projection rule is - * appropriate for the supplied model object. - * - * @param obj The model object to be projected - * @return Whether the rule is relevant for the - * model object - */ - public boolean isSupported(ModelObject obj) { - return (obj.getClass() == ProtocolModel.class); - } - - /** - * This method projects the supplied model object based on the - * specified role. - * - * @param context The context - * @param model The model object - * @param role The role - * @param l The model listener - * @return The projected model object - */ - public Object project(ProtocolProjectorContext context, ModelObject model, - Role role, Journal l) { - ProtocolModel ret=new ProtocolModel(); - ProtocolModel source=(ProtocolModel)model; - - ret.derivedFrom(source); - - // Project import statements - for (int i=0; i < source.getImports().size(); i++) { - - ImportList newImport=(ImportList) - context.project(source.getImports().get(i), - role, l); - - if (newImport != null) { - ret.getImports().add(newImport); - } - } - - Protocol protocol=null; - - // Get enclosing protocol for the supplied role - Role roleDefn=null; - for (Role sr : source.getRoles()) { - if (sr.equals(role)) { - roleDefn = sr; - break; - } - } - - if (roleDefn == null) { - l.error(MessageFormat.format( - java.util.PropertyResourceBundle.getBundle( - "org.scribble.protocol.projection.impl.Messages").getString("_UNKNOWN_ROLE"), - role.getName()), ret.getProperties()); - ret = null; - } else { - - // Get enclosing protocol for the supplied role - Protocol srcprotocol=RoleUtil.getEnclosingProtocol(roleDefn); - - if (srcprotocol != null) { - - //protocol = (Protocol)context.project(srcprotocol, - // role, l); - protocol = ProtocolProjectorRule.startProtocolProjection(context, - srcprotocol, role, l); - - // Check if block enclosing the role definition is the protocol's - // top level block - Block srcblock=RoleUtil.getEnclosingBlock(srcprotocol, roleDefn, true); - - Block block=null; - if (srcblock != null) { - block = (Block)context.project(srcblock, role, l); - } - - if (block != null) { - - // If no top level protocol, then use top level protocol name - if (srcprotocol != source.getProtocol()) { - protocol.setName(source.getProtocol().getName()); - - // TODO: Clear the parameter definitions for now - protocol.getParameterDefinitions().clear(); - } - - // Replace the top level block - protocol.setBlock(block); - - // Get new list of declared roles - java.util.Set declaredRoles=RoleUtil.getDeclaredRoles(protocol.getBlock()); - - java.util.Set usedRoles=RoleUtil.getUsedRoles(protocol.getBlock()); - - usedRoles.removeAll(declaredRoles); - - // Check if parameter definitions need to be updated - protocol.getParameterDefinitions().clear(); - - for (Role used : usedRoles) { - - if (!used.equals(role)) { - ParameterDefinition pd=new ParameterDefinition(); - pd.setName(used.getName()); - protocol.getParameterDefinitions().add(pd); - } - } - } - - ProtocolProjectorRule.endProtocolProjection(context, - srcprotocol, protocol, role, l); - } - - ret.setProtocol(protocol); - } - - if (ret != null && context.getProtocolValidationManager() != null) { - // Validate the local protocol model - context.getProtocolValidationManager().validate(context.getProtocolContext(), - ret, l); - } - - return (ret); - } - - /** - * This method checks the containing constructs of the supplied - * block to determine whether they are relevant. - * - * @param block The block - * @return The processed block - */ - protected static Block checkContainingConstructs(Block block) { - Block ret=block; - ModelObject cur=ret; - - while (cur != null && cur.getParent() != null - && !(cur.getParent() instanceof Protocol)) { - if (cur.getParent().getClass() == RecBlock.class) { - RecBlock rb=new RecBlock(); - - rb.derivedFrom(cur.getParent()); - rb.setLabel(((RecBlock)cur.getParent()).getLabel()); - - rb.setBlock(ret); - - ret = new Block(); - ret.add(rb); - } - - cur = cur.getParent(); - } - - return (ret); - } - -} diff --git a/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/ProtocolProjectorContext.java b/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/ProtocolProjectorContext.java deleted file mode 100644 index a276d2021..000000000 --- a/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/ProtocolProjectorContext.java +++ /dev/null @@ -1,122 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.projection.impl; - -import org.scribble.common.logging.Journal; -import org.scribble.protocol.ProtocolContext; -import org.scribble.protocol.model.ModelObject; -import org.scribble.protocol.model.Protocol; -import org.scribble.protocol.model.Role; -import org.scribble.protocol.validation.ProtocolValidationManager; - -/** - * This interface represents the comparator context. - */ -public interface ProtocolProjectorContext { - - /** - * This method returns the context in which the protocol - * is being processed. - * - * @return The protocol context - */ - public ProtocolContext getProtocolContext(); - - /** - * This method returns the protocol validation manager. - * - * @return The protocol validation manager - */ - public ProtocolValidationManager getProtocolValidationManager(); - - /** - * This method projects the supplied model object based on the - * specified role. - * - * @param model The model object - * @param role The role - * @param l The model listener - * @return The projected model object - */ - public Object project(ModelObject model, Role role, - Journal l); - - /** - * This method returns the named state from the current - * scope. - * - * @param name The state name - * @return The state value, or null if not found - */ - public Object getState(String name); - - /** - * This method sets the value associated with the supplied - * name in the current state. - * - * @param name The state name - * @param value The state value - */ - public void setState(String name, Object value); - - /** - * This method pushes the current state onto a stack. - */ - public void pushState(); - - /** - * This method pops the current state from the stack. - */ - public void popState(); - - /** - * This method pushes the current scope onto a stack. - */ - public void pushScope(); - - /** - * This method pops the current scope from the stack. - */ - public void popScope(); - - /** - * This method determines whether the context is associated - * with the outer scope. - * - * @return Whether the context is for the outer scope - */ - public boolean isOuterScope(); - - /** - * This method registers an interest in the projected role - * associated with the supplied definition. - * - * @param defn The definition - * @param role The projected role of interest - */ - public void registerInterest(Protocol defn, Role role); - - /** - * This method returns the list of roles of interest - * for the supplied definition. - * - * @param defn The definition - * @return The list of roles, or null if no roles have - * registered interest in the definition - */ - public java.util.List getRolesOfInterestForDefinition(Protocol defn); - -} diff --git a/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/ProtocolProjectorImpl.java b/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/ProtocolProjectorImpl.java deleted file mode 100644 index 37141a413..000000000 --- a/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/ProtocolProjectorImpl.java +++ /dev/null @@ -1,129 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.projection.impl; - -import java.text.MessageFormat; - -import org.scribble.common.logging.Journal; -import org.scribble.protocol.ProtocolContext; -import org.scribble.protocol.model.ProtocolModel; -import org.scribble.protocol.model.Role; -import org.scribble.protocol.projection.ProtocolProjector; -import org.scribble.protocol.validation.ProtocolValidationManager; - -/** - * This class provides an implementation of the protocol projector. - * - */ -public class ProtocolProjectorImpl implements ProtocolProjector { - - private ProtocolValidationManager _protocolValidationManager=null; - private java.util.List _customRules=new java.util.Vector(); - - /** - * This method sets the protocol validation manager. - * - * @param pvm The protocol validation manager - */ - public void setProtocolValidationManager(ProtocolValidationManager pvm) { - _protocolValidationManager = pvm; - } - - /** - * This method returns the protocol validation manager. - * - * @return The protocol validation manager - */ - public ProtocolValidationManager getProtocolValidationManager() { - return (_protocolValidationManager); - } - - /** - * This method returns the list of custom rules. - * - * @return The custom rules - */ - public java.util.List getCustomRules() { - return(_customRules); - } - - /** - * This method projects a 'global' protocol model to a specified - * role's 'local' protocol model. - * - * @param context The protocol context - * @param model The 'global' protocol model - * @param role The role to project - * @param journal Journal for reporting issues - * @return The 'local' protocol model - */ - public ProtocolModel project(ProtocolContext context, ProtocolModel model, - Role role, Journal journal) { - ProtocolModel ret=null; - - if (model == null || role == null) { - throw new IllegalArgumentException("Model and/or role has not bee specified"); - } - - // Check that the supplied role has been defined within the model - // being projected - java.util.List roles=model.getRoles(); - int index=roles.indexOf(role); - - if (index == -1) { - throw new IllegalArgumentException("Role '"+role.getName() - +"' is not defined within the protocol model"); - } else { - // Obtain the role instance actually defined within the model, - // as this can be used to locate the appropriate scope to be - // projected - role = roles.get(index); - } - - // Check that role is defined within a role list, and its parent - // link has not inadvertantly been reset - /* GPB: TO INVESTIGATE - if ((role.getParent() instanceof Introduces) == false) { - throw new IllegalArgumentException("Role is not contained within a role list, " + - "and is therefore not the declared role"); - } - */ - - DefaultProjectorContext projectorContext=new DefaultProjectorContext(context, - _protocolValidationManager, _customRules); - - Object obj=projectorContext.project(model, role, journal); - - if (obj != null) { - if (obj instanceof ProtocolModel) { - ret = (ProtocolModel)obj; - } else { - String modelName=model.getProtocol().getName(); - - if (model.getProtocol().getLocatedRole() != null) { - modelName += ","+model.getProtocol().getLocatedRole(); - } - - journal.error(MessageFormat.format( - java.util.PropertyResourceBundle.getBundle("org.scribble.protocol.projection.impl.Messages").getString( - "_NOT_PROJECTED_MODEL"), modelName), null); - } - } - - return (ret); - } - -} diff --git a/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/ProtocolProjectorRule.java b/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/ProtocolProjectorRule.java deleted file mode 100644 index cb0a43e84..000000000 --- a/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/ProtocolProjectorRule.java +++ /dev/null @@ -1,239 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.projection.impl; - -import java.util.logging.Logger; - -import org.scribble.common.logging.Journal; -import org.scribble.protocol.model.Activity; -import org.scribble.protocol.model.Block; -import org.scribble.protocol.model.Choice; -import org.scribble.protocol.model.DefaultVisitor; -import org.scribble.protocol.model.Inline; -import org.scribble.protocol.model.Interaction; -import org.scribble.protocol.model.Introduces; -import org.scribble.protocol.model.ModelObject; -import org.scribble.protocol.model.ParameterDefinition; -import org.scribble.protocol.model.Protocol; -import org.scribble.protocol.model.Role; -import org.scribble.protocol.model.Run; - -/** - * This class provides the Protocol implementation of the - * projector rule. - */ -public class ProtocolProjectorRule implements ProjectorRule { - - private static final Logger LOG=Logger.getLogger(ProtocolProjectorRule.class.getName()); - - /** - * This method determines whether the projection rule is - * appropriate for the supplied model object. - * - * @param obj The model object to be projected - * @return Whether the rule is relevant for the - * model object - */ - public boolean isSupported(ModelObject obj) { - return (obj.getClass() == Protocol.class); - } - - /** - * This method projects the supplied model object based on the - * specified role. - * - * @param context The context - * @param model The model object - * @param role The role - * @param l The model listener - * @return The projected model object - */ - @SuppressWarnings("unchecked") - public Object project(ProtocolProjectorContext context, ModelObject model, - Role role, Journal l) { - Object ret=null; - Protocol source=(Protocol)model; - java.util.List roles=context.getRolesOfInterestForDefinition(source); - - if (context.isOuterScope() - || roles != null) { - - if (roles == null) { - roles = new java.util.Vector(); - roles.add(role); - } - - for (int j=0; j < roles.size(); j++) { - - // Set current role - role = roles.get(j); - - Protocol prot = startProtocolProjection(context, source, role, l); - - prot.setBlock((Block)context.project(source.getBlock(), - role, l)); - prot.getBlock().setParent(prot); - - endProtocolProjection(context, source, prot, role, l); - - // Clean up role lists, to ensure they don't include redundant roles - cleanUpRoles(prot); - - if (ret == null) { - ret = prot; - } else if (ret instanceof java.util.List) { - ((java.util.List)ret).add(prot); - } else { - java.util.List b=new java.util.Vector(); - b.add((ModelObject)ret); - b.add(prot); - ret = b; - } - } - } - - return (ret); - } - - /** - * This method is called to start the projection of a protocol. - * - * @param context The projection context - * @param source The source protocol - * @param role The role - * @param l The journal - * @return The projected protocol - */ - public static Protocol startProtocolProjection(ProtocolProjectorContext context, Protocol source, - Role role, Journal l) { - Protocol prot = new Protocol(); - - prot.derivedFrom(source); - - prot.setName(source.getName()); - - Role located=(Role)context.project(role, role, l); - - prot.setLocatedRole(located); - - context.pushScope(); - - // Project parameters - for (ParameterDefinition p : source.getParameterDefinitions()) { - ParameterDefinition projp=(ParameterDefinition)context.project(p, role, l); - - if (projp != null) { - prot.getParameterDefinitions().add(projp); - } - } - - return (prot); - } - - /** - * This method closes the projection of the protocol. - * - * @param context The projector context - * @param source The source protocol - * @param projected The projected protocol - * @param role The role - * @param l The journal - */ - public static void endProtocolProjection(ProtocolProjectorContext context, Protocol source, - Protocol projected, Role role, Journal l) { - // Project nested protocols - for (Protocol nested : source.getNestedProtocols()) { - Object pp=context.project(nested, role, l); - - if (pp instanceof Protocol) { - projected.getNestedProtocols().add((Protocol)pp); - } else if (pp instanceof java.util.List) { - for (Object obj : (java.util.List)pp) { - if (obj instanceof Protocol) { - projected.getNestedProtocols().add((Protocol)obj); - } else { - LOG.severe("Projection of nested protocol returned unexpected component: "+obj); - } - } - } - } - - context.popScope(); - } - - /** - * This method cleans up the roles associated with the supplied protocol. - * - * @param protocol The protocol - */ - protected void cleanUpRoles(Protocol protocol) { - - // Visit protocol to locate role lists - protocol.visit(new DefaultVisitor() { - - public void accept(Introduces list) { - - // Identify parent block - Block parent=(Block)list.getParent(); - - for (int i=list.getIntroducedRoles().size()-1; i >= 0; i--) { - final Role role=(Role)list.getIntroducedRoles().get(i); - final java.util.List acts=new java.util.Vector(); - - // Find out if role is used in a relevant activity - parent.visit(new DefaultVisitor() { - - public void accept(Interaction interaction) { - if (role.equals(interaction.getFromRole()) - || interaction.getToRoles().contains(role)) { - acts.add(interaction); - } - } - - public boolean start(Choice choice) { - if (role.equals(choice.getRole())) { - acts.add(choice); - } - return (true); - } - - public void accept(Run run) { - if (run.getParameter(role.getName()) != null) { - acts.add(run); - } - } - - public void accept(Inline elem) { - if (elem.getParameter(role.getName()) != null) { - acts.add(elem); - } - } - }); - - if (acts.size() == 0) { - list.getIntroducedRoles().remove(role); - - if (list.getIntroducedRoles().size() == 0) { - parent.remove(list); - } - } - } - } - }); - } - - //private static Logger logger = Logger.getLogger("org.scribble.protocol.projector"); -} diff --git a/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/ProtocolReferenceProjectorRule.java b/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/ProtocolReferenceProjectorRule.java deleted file mode 100644 index 1aafbe2fc..000000000 --- a/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/ProtocolReferenceProjectorRule.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.projection.impl; - -import org.scribble.common.logging.Journal; -import org.scribble.protocol.model.ModelObject; -import org.scribble.protocol.model.ProtocolReference; -import org.scribble.protocol.model.Role; - -/** - * This class provides the ProtocolReference implementation of the - * projector rule. - */ -public class ProtocolReferenceProjectorRule implements ProjectorRule { - - /** - * This is the default constructor. - */ - public ProtocolReferenceProjectorRule() { - } - - /** - * This method determines whether the projection rule is - * appropriate for the supplied model object. - * - * @param obj The model object to be projected - * @return Whether the rule is relevant for the - * model object - */ - public boolean isSupported(ModelObject obj) { - return (obj.getClass() == ProtocolReference.class); - } - - /** - * This method projects the supplied model object based on the - * specified role. - * - * @param context The context - * @param model The model object - * @param role The role - * @param l The model listener - * @return The projected model object - */ - public Object project(ProtocolProjectorContext context, ModelObject model, - Role role, Journal l) { - ProtocolReference src=(ProtocolReference)model; - ProtocolReference ret=new ProtocolReference(); - - ret.derivedFrom(src); - - ret.setName(src.getName()); - - ret.setRole((Role)context.project(role, role, l)); - - return (ret); - } -} diff --git a/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/RecBlockProjectorRule.java b/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/RecBlockProjectorRule.java deleted file mode 100644 index 337908f1a..000000000 --- a/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/RecBlockProjectorRule.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.projection.impl; - -import org.scribble.common.logging.Journal; -import org.scribble.protocol.model.Block; -import org.scribble.protocol.model.ModelObject; -import org.scribble.protocol.model.RecBlock; -import org.scribble.protocol.model.Role; - -/** - * This class provides the Labelled Block implementation of the - * projector rule. - */ -public class RecBlockProjectorRule implements ProjectorRule { - - /** - * This method determines whether the projection rule is - * appropriate for the supplied model object. - * - * @param obj The model object to be projected - * @return Whether the rule is relevant for the - * model object - */ - public boolean isSupported(ModelObject obj) { - return (obj.getClass() == RecBlock.class); - } - - /** - * This method projects the supplied model object based on the - * specified role. - * - * @param context The context - * @param model The model object - * @param role The role - * @param l The model listener - * @return The projected model object - */ - public Object project(ProtocolProjectorContext context, ModelObject model, - Role role, Journal l) { - RecBlock ret=new RecBlock(); - RecBlock source=(RecBlock)model; - - ret.derivedFrom(source); - - ret.setLabel(source.getLabel()); - - if (ret != null && source.getBlock() != null) { - - // Project the block - ret.setBlock((Block) - context.project(source.getBlock(), - role, l)); - - if (ret.getBlock() != null) { - ret.getBlock().setParent(ret); - } else { - ret = null; - } - } - - return (ret); - } -} diff --git a/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/RecursionProjectorRule.java b/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/RecursionProjectorRule.java deleted file mode 100644 index 49b12c043..000000000 --- a/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/RecursionProjectorRule.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.projection.impl; - -import org.scribble.common.logging.Journal; -import org.scribble.protocol.model.ModelObject; -import org.scribble.protocol.model.Recursion; -import org.scribble.protocol.model.Role; - -/** - * This class provides the Recursion implementation of the - * projector rule. - */ -public class RecursionProjectorRule implements ProjectorRule { - - /** - * This method determines whether the projection rule is - * appropriate for the supplied model object. - * - * @param obj The model object to be projected - * @return Whether the rule is relevant for the - * model object - */ - public boolean isSupported(ModelObject obj) { - return (obj.getClass() == Recursion.class); - } - - /** - * This method projects the supplied model object based on the - * specified role. - * - * @param context The context - * @param model The model object - * @param role The role - * @param l The model listener - * @return The projected model object - */ - public Object project(ProtocolProjectorContext context, ModelObject model, - Role role, Journal l) { - Recursion ret=new Recursion(); - Recursion recursion=(Recursion)model; - - ret.derivedFrom(recursion); - - ret.setLabel(recursion.getLabel()); - - return (ret); - } -} diff --git a/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/RepeatProjectorRule.java b/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/RepeatProjectorRule.java deleted file mode 100644 index b79efd6a6..000000000 --- a/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/RepeatProjectorRule.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.projection.impl; - -import org.scribble.common.logging.Journal; -import org.scribble.protocol.model.Block; -import org.scribble.protocol.model.ModelObject; -import org.scribble.protocol.model.Repeat; -import org.scribble.protocol.model.Role; - -/** - * This class provides the Repeat implementation of the - * projector rule. - */ -public class RepeatProjectorRule implements ProjectorRule { - - /** - * This method determines whether the projection rule is - * appropriate for the supplied model object. - * - * @param obj The model object to be projected - * @return Whether the rule is relevant for the - * model object - */ - public boolean isSupported(ModelObject obj) { - return (obj.getClass() == Repeat.class); - } - - /** - * This method projects the supplied model object based on the - * specified role. - * - * @param context The context - * @param model The model object - * @param role The role - * @param l The model listener - * @return The projected model object - */ - public Object project(ProtocolProjectorContext context, ModelObject model, - Role role, Journal l) { - Repeat ret=new Repeat(); - Repeat source=(Repeat)model; - - ret.derivedFrom(source); - - // Project the list of roles - for (int i=0; i < source.getRoles().size(); i++) { - // Possibly don't project roles that are not relevant to the - // current projected role - - //if (source.getRoles().get(i).getName().equals(role.getName()) == false) { - ret.getRoles().add(new Role(source.getRoles().get(i))); - //} - } - - if (ret != null && source.getBlock() != null) { - - // Project the block - Block b=(Block)context.project(source.getBlock(), role, l); - - if (b != null) { - ret.setBlock(b); - ret.getBlock().setParent(ret); - } else { - ret = null; - } - } - - return (ret); - } -} diff --git a/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/RoleProjectorRule.java b/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/RoleProjectorRule.java deleted file mode 100644 index 3689c0858..000000000 --- a/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/RoleProjectorRule.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.projection.impl; - -import org.scribble.common.logging.Journal; -import org.scribble.protocol.model.ModelObject; -import org.scribble.protocol.model.Role; - -/** - * This class provides the Role implementation of the - * projector rule. - */ -public class RoleProjectorRule implements ProjectorRule { - - /** - * This method determines whether the projection rule is - * appropriate for the supplied model object. - * - * @param obj The model object to be projected - * @return Whether the rule is relevant for the - * model object - */ - public boolean isSupported(ModelObject obj) { - return (obj.getClass() == Role.class); - } - - /** - * This method projects the supplied model object based on the - * specified role. - * - * @param context The context - * @param model The model object - * @param role The role - * @param l The model listener - * @return The projected model object - */ - public Object project(ProtocolProjectorContext context, ModelObject model, - Role role, Journal l) { - Role ret=new Role(); - Role source=(Role)model; - - ret.derivedFrom(source); - - ret.setName(source.getName()); - - // Add to state - context.setState(ret.getName(), ret); - - return (ret); - } -} diff --git a/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/RunProjectorRule.java b/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/RunProjectorRule.java deleted file mode 100644 index c16377993..000000000 --- a/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/RunProjectorRule.java +++ /dev/null @@ -1,157 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.projection.impl; - -import org.scribble.common.logging.Journal; -import org.scribble.protocol.model.ModelObject; -import org.scribble.protocol.model.Parameter; -import org.scribble.protocol.model.ParameterDefinition; -import org.scribble.protocol.model.Protocol; -import org.scribble.protocol.model.ProtocolImport; -import org.scribble.protocol.model.ProtocolModel; -import org.scribble.protocol.model.ProtocolReference; -import org.scribble.protocol.model.Role; -import org.scribble.protocol.model.Run; -import org.scribble.protocol.util.ProtocolModelUtil; -import org.scribble.protocol.util.RunUtil; - -/** - * This class provides the Run implementation of the - * projector rule. - */ -public class RunProjectorRule implements ProjectorRule { - - /** - * This method determines whether the projection rule is - * appropriate for the supplied model object. - * - * @param obj The model object to be projected - * @return Whether the rule is relevant for the - * model object - */ - public boolean isSupported(ModelObject obj) { - return (obj.getClass() == Run.class); - } - - /** - * This method projects the supplied model object based on the - * specified role. - * - * @param context The context - * @param model The model object - * @param role The role - * @param l The model listener - * @return The projected model object - */ - public Object project(ProtocolProjectorContext context, ModelObject model, - Role role, Journal l) { - Run ret=new Run(); - Run source=(Run)model; - - ret.derivedFrom(source); - - java.util.List params= - source.getParameters(); - int mappedIndex=-1; - - for (int i=0; i < params.size(); i++) { - Parameter db=params.get(i); - - // Don't project declaration if same as role - this - // will be done in the model include statement, - // not the bindings - if (!db.getName().equals(role.getName())) { - - Parameter dbcopy= - new Parameter(db.getName()); - - dbcopy.derivedFrom(db); - - ret.getParameters().add(dbcopy); - } else { - mappedIndex = i; - } - } - - if (source.getFromRole() != null) { - ret.setFromRole((Role)context.project(source.getFromRole(), role, l)); - } - - if (source.getProtocolReference() != null) { - boolean inner=false; - - // Store protocol against mapped role - Protocol defn=RunUtil.getInnerProtocol(source.getEnclosingProtocol(), - source.getProtocolReference()); //source.getProtocol(); - - if (defn == null) { - // Check if protocol import defined for protocol - ProtocolImport pi=ProtocolModelUtil.getProtocolImport(source.getModel(), - source.getProtocolReference()); - - if (pi == null) { - l.error("Referenced protocol '"+source.getProtocolReference().getName() - +"' not found within model or in import statements", source.getProperties()); - } else { - ProtocolModel pm=context.getProtocolContext().getProtocolModel(pi, l); - - if (pm != null) { - defn = pm.getProtocol(); - } else { - l.error("Referenced protocol '"+source.getProtocolReference().getName() - +"' could not be loaded from location '"+pi.getLocation()+"'", - source.getProperties()); - } - } - } else { - inner = true; - } - - if (defn != null && mappedIndex != -1) { - - Role mappedRole=null; - - if (mappedIndex < defn.getParameterDefinitions().size()) { - ParameterDefinition pd=defn.getParameterDefinitions().get(mappedIndex); - - if (pd.getType() != null) { - l.error("Run parameter is not a role", source.getProperties()); - } else { - mappedRole = new Role(pd.getName()); - } - } else { - l.error("Run parameter is not a role", source.getProperties()); - } - - if (mappedRole != null) { - // If inner reference, then record interest - // in project of definition against this mapped - // role - if (inner) { - context.registerInterest(defn, mappedRole); - } - - ret.setProtocolReference((ProtocolReference)context.project( - source.getProtocolReference(), mappedRole, l)); - } - } else { - ret = null; - } - } - - return (ret); - } -} diff --git a/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/Scope.java b/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/Scope.java deleted file mode 100644 index 706e611f2..000000000 --- a/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/Scope.java +++ /dev/null @@ -1,149 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.projection.impl; - -import java.util.logging.Logger; - -/** - * This class represents information associated with a scope. - */ -public class Scope { - - private final static Logger LOG = Logger.getLogger(Scope.class.getName()); - - private String _locatedRole=null; - private java.util.List> _stateStack= - new java.util.Vector>(); - private java.util.Map _properties=new java.util.HashMap(); - - /** - * The default constructor for the scope. - */ - public Scope() { - // Initialize the state - pushState(); - } - - /** - * This is the copy constructor for the scope. - * - * @param copy The copy - */ - public Scope(Scope copy) { - _locatedRole = copy._locatedRole; - - for (int i=0; i < copy._stateStack.size(); i++) { - java.util.Map current=copy._stateStack.get(i); - - java.util.Map copyStackEntry= - new java.util.Hashtable(); - - java.util.Iterator iter=current.keySet().iterator(); - - while (iter.hasNext()) { - String key=iter.next(); - Object value=current.get(key); - - copyStackEntry.put(key, value); - } - - _stateStack.add(copyStackEntry); - } - } - - /** - * This method returns the named state from the current - * scope. - * - * @param name The state name - * @return The state value, or null if not found - */ - public Object getState(String name) { - Object ret=null; - - if (_stateStack.size() > 0) { - for (int i=0; ret == null && i < _stateStack.size(); i++) { - java.util.Map current=_stateStack.get(i); - ret = current.get(name); - } - } - - return (ret); - } - - /** - * This method sets the value associated with the supplied - * name in the current state scope. - * - * @param name The state name - * @param value The state value - */ - public void setState(String name, Object value) { - if (_stateStack.size() > 0) { - java.util.Map current=_stateStack.get(0); - current.put(name, value); - } - } - - /** - * This method returns the located role associated with the - * current scope. - * - * @return The located role - */ - public String getLocatedParticipant() { - return (_locatedRole); - } - - /** - * This method sets the located role associated with the - * current scope. - * - * @param located The located role - */ - public void setLocatedParticipant(String located) { - _locatedRole = located; - } - - /** - * This method pushes the current state onto a stack. - */ - public void pushState() { - _stateStack.add(0, new java.util.Hashtable()); - } - - /** - * This method pops the current state from the stack. - */ - public void popState() { - if (_stateStack.size() > 0) { - _stateStack.remove(0); - } else { - LOG.severe("No state entry to pop from stack"); - } - } - - /** - * This method returns the properties associated with - * the scope. - * - * @return The properties - */ - public java.util.Map getProperties() { - return (_properties); - } -} diff --git a/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/TypeImportListProjectorRule.java b/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/TypeImportListProjectorRule.java deleted file mode 100644 index 49f3f07a8..000000000 --- a/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/TypeImportListProjectorRule.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.projection.impl; - -import org.scribble.common.logging.Journal; -import org.scribble.protocol.model.ModelObject; -import org.scribble.protocol.model.Role; -import org.scribble.protocol.model.TypeImport; -import org.scribble.protocol.model.TypeImportList; - -/** - * This class provides the ImportList implementation of the - * projector rule. - */ -public class TypeImportListProjectorRule implements ProjectorRule { - - /** - * This method determines whether the projection rule is - * appropriate for the supplied model object. - * - * @param obj The model object to be projected - * @return Whether the rule is relevant for the - * model object - */ - public boolean isSupported(ModelObject obj) { - return (obj.getClass() == TypeImportList.class); - } - - /** - * This method projects the supplied model object based on the - * specified role. - * - * @param context The context - * @param model The model object - * @param role The role - * @param l The model listener - * @return The projected model object - */ - public Object project(ProtocolProjectorContext context, ModelObject model, - Role role, Journal l) { - TypeImportList ret=new TypeImportList(); - TypeImportList source=(TypeImportList)model; - - ret.derivedFrom(source); - - ret.setFormat(source.getFormat()); - ret.setLocation(source.getLocation()); - - for (int i=0; i < source.getTypeImports().size(); i++) { - TypeImport p=(TypeImport)context.project(source.getTypeImports().get(i), role, l); - - if (p != null) { - ret.getTypeImports().add(p); - } - } - - return (ret); - } -} diff --git a/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/TypeImportProjectorRule.java b/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/TypeImportProjectorRule.java deleted file mode 100644 index c9a5c7c3f..000000000 --- a/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/TypeImportProjectorRule.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.projection.impl; - -import org.scribble.common.logging.Journal; -import org.scribble.protocol.model.DataType; -import org.scribble.protocol.model.ModelObject; -import org.scribble.protocol.model.Role; -import org.scribble.protocol.model.TypeImport; - -/** - * This class provides the TypeImport implementation of the - * projector rule. - */ -public class TypeImportProjectorRule implements ProjectorRule { - - /** - * This method determines whether the projection rule is - * appropriate for the supplied model object. - * - * @param obj The model object to be projected - * @return Whether the rule is relevant for the - * model object - */ - public boolean isSupported(ModelObject obj) { - return (obj.getClass() == TypeImport.class); - } - - /** - * This method projects the supplied model object based on the - * specified role. - * - * @param context The context - * @param model The model object - * @param role The role - * @param l The model listener - * @return The projected model object - */ - public Object project(ProtocolProjectorContext context, ModelObject model, - Role role, Journal l) { - TypeImport ret=new TypeImport(); - TypeImport source=(TypeImport)model; - - ret.derivedFrom(source); - - ret.setName(source.getName()); - - if (source.getDataType() != null) { - ret.setDataType((DataType)context.project(source.getDataType(), role, l)); - } - - return (ret); - } -} diff --git a/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/TypeReferenceProjectorRule.java b/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/TypeReferenceProjectorRule.java deleted file mode 100644 index 4001a91f7..000000000 --- a/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/TypeReferenceProjectorRule.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.projection.impl; - -import org.scribble.common.logging.Journal; -import org.scribble.protocol.model.ModelObject; -import org.scribble.protocol.model.Role; -import org.scribble.protocol.model.TypeReference; - -/** - * This class provides the TypeReference implementation of the - * projector rule. - */ -public class TypeReferenceProjectorRule implements ProjectorRule { - - /** - * This is the default constructor. - */ - public TypeReferenceProjectorRule() { - } - - /** - * This method determines whether the projection rule is - * appropriate for the supplied model object. - * - * @param obj The model object to be projected - * @return Whether the rule is relevant for the - * model object - */ - public boolean isSupported(ModelObject obj) { - return (obj.getClass() == TypeReference.class); - } - - /** - * This method projects the supplied model object based on the - * specified role. - * - * @param context The context - * @param model The model object - * @param role The role - * @param l The model listener - * @return The projected model object - */ - public Object project(ProtocolProjectorContext context, ModelObject model, - Role role, Journal l) { - TypeReference source=(TypeReference)model; - TypeReference ret=new TypeReference(); - - ret.derivedFrom(source); - - ret.setName(source.getName()); - - return (ret); - } -} diff --git a/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/UnorderedProjectorRule.java b/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/UnorderedProjectorRule.java deleted file mode 100644 index d324928c0..000000000 --- a/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/impl/UnorderedProjectorRule.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright 2009-11 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.projection.impl; - -import org.scribble.common.logging.Journal; -import org.scribble.protocol.model.Block; -import org.scribble.protocol.model.ModelObject; -import org.scribble.protocol.model.Role; -import org.scribble.protocol.model.Unordered; - -/** - * This class provides the Unordered implementation of the - * projector rule. - */ -public class UnorderedProjectorRule implements ProjectorRule { - - /** - * This method determines whether the projection rule is - * appropriate for the supplied model object. - * - * @param obj The model object to be projected - * @return Whether the rule is relevant for the - * model object - */ - public boolean isSupported(ModelObject obj) { - return (obj.getClass() == Unordered.class); - } - - /** - * This method projects the supplied model object based on the - * specified role. - * - * @param context The context - * @param model The model object - * @param role The role - * @param l The model listener - * @return The projected model object - */ - public Object project(ProtocolProjectorContext context, ModelObject model, - Role role, Journal l) { - Unordered ret=new Unordered(); - Unordered source=(Unordered)model; - - ret.derivedFrom(source); - - if (source.getBlock() != null) { - - // Project the block - ret.setBlock((Block) - context.project(source.getBlock(), - role, l)); - ret.getBlock().setParent(ret); - } - - return (ret); - } -} diff --git a/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/osgi/Activator.java b/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/osgi/Activator.java deleted file mode 100644 index bd7816a5f..000000000 --- a/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/osgi/Activator.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright 2009-11 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.projection.osgi; - -import java.util.Properties; -import java.util.logging.Logger; - -import org.osgi.framework.BundleActivator; -import org.osgi.framework.BundleContext; -import org.osgi.framework.ServiceReference; -import org.osgi.util.tracker.ServiceTracker; -import org.scribble.protocol.projection.ProtocolProjector; -import org.scribble.protocol.projection.impl.ProjectorRule; -import org.scribble.protocol.projection.impl.ProtocolProjectorImpl; - -/** - * Activator. - * - */ -public class Activator implements BundleActivator { - - private static final Logger LOG=Logger.getLogger(Activator.class.getName()); - - private org.osgi.util.tracker.ServiceTracker _protocolValidationManagerTracker=null; - private org.osgi.util.tracker.ServiceTracker _protocolProjectorRuleTracker=null; - - /** - * {@inheritDoc} - */ - public void start(BundleContext context) throws Exception { - Properties props = new Properties(); - - final ProtocolProjectorImpl pp=new ProtocolProjectorImpl(); - - context.registerService(ProtocolProjector.class.getName(), - pp, props); - - // Detect protocol validation manager - _protocolValidationManagerTracker = new ServiceTracker(context, - org.scribble.protocol.validation.ProtocolValidationManager.class.getName(), - null) { - - public Object addingService(ServiceReference ref) { - Object ret=super.addingService(ref); - - LOG.fine("Validation manager has been added to projector: "+ret); - - pp.setProtocolValidationManager((org.scribble.protocol.validation.ProtocolValidationManager)ret); - - return (ret); - } - }; - - _protocolValidationManagerTracker.open(); - - // Detect additional protocol projection rules - _protocolProjectorRuleTracker = new ServiceTracker(context, - org.scribble.protocol.projection.impl.ProjectorRule.class.getName(), - null) { - - public Object addingService(ServiceReference ref) { - Object ret=super.addingService(ref); - - LOG.fine("Projection rule has been added: "+ret); - - pp.getCustomRules().add((ProjectorRule)ret); - - return (ret); - } - }; - - _protocolProjectorRuleTracker.open(); - - } - - /** - * {@inheritDoc} - */ - public void stop(BundleContext context) throws Exception { - } - -} diff --git a/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/util/ChoiceMergingUtil.java b/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/util/ChoiceMergingUtil.java deleted file mode 100644 index 8544fe37b..000000000 --- a/bundles/org.scribble.protocol.projection/src/main/java/org/scribble/protocol/projection/util/ChoiceMergingUtil.java +++ /dev/null @@ -1,223 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.projection.util; - -import java.text.MessageFormat; -import java.util.logging.Logger; - -import org.scribble.common.logging.Journal; -import org.scribble.protocol.model.Activity; -import org.scribble.protocol.model.Block; -import org.scribble.protocol.model.Choice; -import org.scribble.protocol.model.Role; - -/** - * This class provides the Choice Merging utility function. - */ -public class ChoiceMergingUtil { - - /** - * System property: should choice constructs be permitted to have empty paths - * and therefore be optional? - */ - public static final String ALLOW_OPTIONAL = "scribble.choice.allowOptional"; - - private static final Logger LOG=Logger.getLogger(ChoiceMergingUtil.class.getName()); - - /** - * This method processes a choice construct. - * - * @param context The context - * @param projected The projected choice - * @param role The projected role - * @param l The journal - * @param optional Whether the construct is optional - * @return The processed activities - */ - public static Object merge(Choice projected, Role role, - Journal l, boolean optional) { - Object ret=null; - - ret = extractCommonBehaviour(projected, role, l); - - // If multiple paths have common initiator (but not common to all behaviours) - // then group in sub-choice - groupSubpathsWithCommonInitiator(projected, role, l); - - // Remove all empty paths - for (int i=projected.getPaths().size()-1; i >= 0; i--) { - Block b=projected.getPaths().get(i); - - if (b.size() == 0) { - projected.getPaths().remove(i); - optional = true; - } - } - - if (projected.getPaths().size() == 0) { - if (ret == projected) { - ret = null; - } else { - ((java.util.List)ret).remove(projected); - } - projected = null; - } else if (optional) { - - // Check if optional permitted - if (System.getProperty(ALLOW_OPTIONAL, "false"). - equalsIgnoreCase(Boolean.FALSE.toString())) { - l.error(MessageFormat.format( - java.util.PropertyResourceBundle.getBundle( - "org.scribble.protocol.projection.impl.Messages"). - getString("_CHOICE_EMPTY_PATH"), - role.getName()), projected.getProperties()); - } - - // Add optional block - projected.getPaths().add(new Block()); - } - - return (ret); - } - - /** - * This method checks whether choice paths should be grouped into sub-paths - * with common initiating interaction sentences. - * - * @param projected The projected choice - * @param role The role - * @param l The journal - */ - @SuppressWarnings("unchecked") - protected static void groupSubpathsWithCommonInitiator(Choice projected, - Role role, Journal l) { - java.util.Map> pathGroups= - new java.util.HashMap>(); - - for (Block path : projected.getPaths()) { - if (path.size() > 0) { - java.util.List plist=pathGroups.get(path.get(0)); - if (plist == null) { - plist = new java.util.Vector(); - pathGroups.put(path.get(0), plist); - } - plist.add(path); - } - } - - for (Activity act : pathGroups.keySet()) { - java.util.List plist=pathGroups.get(act); - - if (plist.size() >= 2) { - - // Create new choice construct - Choice sub=new Choice(); - int pos=-1; - - // TODO: Do we need to determine/set the role associated with choice? - // If different then report error? - - for (Block b : plist) { - if (pos == -1) { - pos = projected.getPaths().indexOf(b); - } - projected.getPaths().remove(b); - sub.getPaths().add(b); - } - - Block newPath=new Block(); - - projected.getPaths().add(pos, newPath); - - Object processed=merge(sub, role, l, false); - - if (processed instanceof java.util.List) { - newPath.getContents().addAll((java.util.List)processed); - } else { - LOG.severe("Should have returned a list with extracted common activity(s) followed by choice"); - } - } - } - } - - /** - * Extract common behaviour. - * - * @param projected The projected choice - * @param role The role - * @param l The journal - * @return Extracted common behaviour - */ - @SuppressWarnings("unchecked") - protected static Object extractCommonBehaviour(Choice projected, - Role role, Journal l) { - Object ret=projected; - - // Check to see whether common interaction sentences can be extracted - // out from each path to precede the choice - boolean checkPaths=true; - do { - boolean allSame=projected.getPaths().size() > 1; - - for (int i=1; allSame && i < projected.getPaths().size(); i++) { - Block b1=projected.getPaths().get(0); - Block b2=projected.getPaths().get(i); - - if (b1.size() == 0 || b2.size() == 0) { - allSame = false; - } else if (!b1.get(0).equals(b2.get(0))) { - allSame = false; - } - } - - if (allSame) { - // Merge first elements from each path and place before the choice - if (!(ret instanceof java.util.List)) { - ret = new java.util.Vector(); - ((java.util.List)ret).add(projected); - } - - ((java.util.List)ret).add(((java.util.List)ret).size()-1, - projected.getPaths().get(0).getContents().get(0)); - - for (int i=0; i < projected.getPaths().size(); i++) { - // Remove first element - projected.getPaths().get(i).getContents().remove(0); - } - } else { - checkPaths = false; - } - - } while(checkPaths); - - return (ret); - } - - /** - * Check whether roles are the same. - * - * @param c1 First choice - * @param c2 Second choice - * @return Whether roles are same - */ - protected boolean isSameRole(Choice c1, Choice c2) { - if (c1.getRole() == null && c2.getRole() == null) { - return (true); - } else { - return (c1.getRole().equals(c2.getRole())); - } - } -} diff --git a/bundles/org.scribble.protocol.projection/src/main/resources/OSGI-INF/protocol-projector.xml b/bundles/org.scribble.protocol.projection/src/main/resources/OSGI-INF/protocol-projector.xml deleted file mode 100644 index ad3c11b55..000000000 --- a/bundles/org.scribble.protocol.projection/src/main/resources/OSGI-INF/protocol-projector.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/bundles/org.scribble.protocol.projection/src/main/resources/org/scribble/protocol/projection/impl/Messages.properties b/bundles/org.scribble.protocol.projection/src/main/resources/org/scribble/protocol/projection/impl/Messages.properties deleted file mode 100644 index d7389be84..000000000 --- a/bundles/org.scribble.protocol.projection/src/main/resources/org/scribble/protocol/projection/impl/Messages.properties +++ /dev/null @@ -1,19 +0,0 @@ -#/* -# * Copyright 2009 Scribble.org -# * -# * 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 -# * -# * http://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. -# * -# */ -_CHOICE_EMPTY_PATH=Choice for role ''{0}'' is not projected to all paths -_NOT_PROJECTED_MODEL=Model ''{0}'' was not projected to another model -_UNKNOWN_ROLE=Role ''{0}'' is not defined within this protocol model diff --git a/bundles/org.scribble.protocol.projection/src/test/java/org/scribble/protocol/projection/impl/ChoiceProjectorRuleTest.java b/bundles/org.scribble.protocol.projection/src/test/java/org/scribble/protocol/projection/impl/ChoiceProjectorRuleTest.java deleted file mode 100644 index d56bb1fc6..000000000 --- a/bundles/org.scribble.protocol.projection/src/test/java/org/scribble/protocol/projection/impl/ChoiceProjectorRuleTest.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.scribble.protocol.projection.impl; - -import static org.junit.Assert.*; - -import org.junit.Test; - -public class ChoiceProjectorRuleTest { - - @Test - public void test() { - //ChoiceProjectorRule.extractCommonBehaviour(context, projected, role, l); - } - -} diff --git a/bundles/org.scribble.protocol.projection/src/test/java/org/scribble/protocol/projection/impl/ProtocolModelProjectorRuleTest.java b/bundles/org.scribble.protocol.projection/src/test/java/org/scribble/protocol/projection/impl/ProtocolModelProjectorRuleTest.java deleted file mode 100644 index 5d26fa547..000000000 --- a/bundles/org.scribble.protocol.projection/src/test/java/org/scribble/protocol/projection/impl/ProtocolModelProjectorRuleTest.java +++ /dev/null @@ -1,175 +0,0 @@ -/* - * Copyright 2009-11 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.projection.impl; - -import static org.junit.Assert.*; - -import java.text.MessageFormat; - -import org.scribble.common.logging.CachedJournal; -import org.scribble.common.logging.CachedJournal.IssueDetails; -import org.scribble.protocol.model.Block; -import org.scribble.protocol.model.Choice; -import org.scribble.protocol.model.Protocol; -import org.scribble.protocol.model.ProtocolModel; -import org.scribble.protocol.model.RecBlock; -import org.scribble.protocol.model.Role; -import org.scribble.protocol.model.Introduces; - -public class ProtocolModelProjectorRuleTest { - - @org.junit.Test - public void projectUnknownRole() { - ProtocolModel pm=new ProtocolModel(); - - Protocol p=new Protocol(); - - Introduces rl=new Introduces(); - - Role r=new Role(); - r.setName("role"); - - rl.getIntroducedRoles().add(r); - - p.getBlock().add(rl); - - pm.setProtocol(p); - - Role unknown=new Role("unknown"); - - ProtocolModelProjectorRule rule=new ProtocolModelProjectorRule(); - - ProtocolProjectorContext context=new DefaultProjectorContext(null, null); - - CachedJournal l=new CachedJournal(); - - rule.project(context, pm, unknown, l); - - if (l.getIssues().size() != 1 || l.hasErrors() == false) { - fail("Expecting 1 error"); - } - - IssueDetails id=l.getIssues().get(0); - - if (id.getMessage().equals(MessageFormat.format( - java.util.PropertyResourceBundle.getBundle( - "org.scribble.protocol.projection.impl.Messages").getString("_UNKNOWN_ROLE"), - unknown.getName())) == false) { - fail("Unexpected error message: "+id.getMessage()); - } - } - - @org.junit.Test - public void projectKnownRole() { - ProtocolModel pm=new ProtocolModel(); - - Protocol p=new Protocol(); - - Introduces rl=new Introduces(); - - Role introducer=new Role(); - introducer.setName("introducer"); - - rl.setIntroducer(introducer); - - Role r=new Role(); - r.setName("role"); - - rl.getIntroducedRoles().add(r); - - p.getBlock().add(rl); - - pm.setProtocol(p); - - ProtocolModelProjectorRule rule=new ProtocolModelProjectorRule(); - - ProtocolProjectorContext context=new DefaultProjectorContext(null, null); - - CachedJournal l=new CachedJournal(); - - Role known=new Role(); - known.setName(r.getName()); - - rule.project(context, pm, known, l); - - if (l.hasErrors()) { - fail("Expecting no error"); - } - } - - @org.junit.Test - public void testCheckContainingConstructsNoChange() { - - Protocol prot1=new Protocol(); - - Block b1=new Block(); - prot1.setBlock(b1); - - Choice c1=new Choice(); - b1.add(c1); - - Block b2=new Block(); - c1.getPaths().add(b2); - - if (ProtocolModelProjectorRule.checkContainingConstructs(b2) != b2) { - fail("Block should be the same"); - } - } - - @org.junit.Test - public void testCheckContainingConstructsAddRecBlock() { - - Protocol prot1=new Protocol(); - - Block b1=new Block(); - prot1.setBlock(b1); - - RecBlock rb1=new RecBlock(); - rb1.setLabel("label"); - b1.add(rb1); - - Choice c1=new Choice(); - rb1.getBlock().add(c1); - - Block b2=new Block(); - c1.getPaths().add(b2); - - Block result=ProtocolModelProjectorRule.checkContainingConstructs(b2); - - if (result == null) { - fail("Result is null"); - } - - if (result.size() != 1) { - fail("Result block should have 1"); - } - - if ((result.get(0) instanceof RecBlock) == false) { - fail("RecBlock not found"); - } - - RecBlock rbresult=(RecBlock)result.get(0); - - if (rbresult.getLabel().equals(rb1.getLabel()) == false) { - fail("RecBlock not the same"); - } - - if (rbresult.getBlock() != b2) { - fail("RecBlock should contain b2"); - } - } -} diff --git a/bundles/org.scribble.protocol/LICENSE.txt b/bundles/org.scribble.protocol/LICENSE.txt deleted file mode 100644 index 29f81d812..000000000 --- a/bundles/org.scribble.protocol/LICENSE.txt +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - 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 - - http://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. diff --git a/bundles/org.scribble.protocol/META-INF/MANIFEST.MF b/bundles/org.scribble.protocol/META-INF/MANIFEST.MF deleted file mode 100644 index 7d685acc9..000000000 --- a/bundles/org.scribble.protocol/META-INF/MANIFEST.MF +++ /dev/null @@ -1,22 +0,0 @@ -Manifest-Version: 1.0 -Bundle-ManifestVersion: 2 -Bundle-Name: Scribble Protocol -Bundle-SymbolicName: org.scribble.protocol;singleton:=true -Bundle-Version: 2.1.0.SNAPSHOT -Bundle-Activator: org.scribble.protocol.osgi.Activator -Bundle-Vendor: www.scribble.org -Import-Package: org.osgi.framework, - org.osgi.util.tracker -Require-Bundle: org.scribble.common -Export-Package: org.scribble.protocol.conformance, - org.scribble.protocol, - org.scribble.protocol.export, - org.scribble.protocol.export.text, - org.scribble.protocol.model, - org.scribble.protocol.parser, - org.scribble.protocol.projection, - org.scribble.protocol.util, - org.scribble.protocol.validation, - org.scribble.protocol.validation.rules -Bundle-ActivationPolicy: lazy -Bundle-RequiredExecutionEnvironment: JavaSE-1.6 diff --git a/bundles/org.scribble.protocol/build.properties b/bundles/org.scribble.protocol/build.properties deleted file mode 100644 index 7e70dff6d..000000000 --- a/bundles/org.scribble.protocol/build.properties +++ /dev/null @@ -1,15 +0,0 @@ -source.. = src/main/java/,\ - src/main/resources/ -output.. = bin/ -bin.includes = META-INF/,\ - .,\ - LICENSE.txt,\ - OSGI-INF/ -src.includes = .classpath,\ - .project,\ - LICENSE.txt,\ - META-INF/,\ - build.properties,\ - pom.xml,\ - src/,\ - OSGI-INF/ diff --git a/bundles/org.scribble.protocol/pom.xml b/bundles/org.scribble.protocol/pom.xml deleted file mode 100644 index 35bc9d6c6..000000000 --- a/bundles/org.scribble.protocol/pom.xml +++ /dev/null @@ -1,84 +0,0 @@ - - 4.0.0 - org.scribble.bundles - org.scribble.protocol - jar - 2.1.0-SNAPSHOT - Scribble::Bundles::Protocol - - - org.scribble - bundles - 2.1.0-SNAPSHOT - - - - - org.scribble.bundles - org.scribble.common - ${scribble.bundles.version} - - - org.osgi - org.osgi.core - ${osgi.version} - - - org.osgi - org.osgi.compendium - ${osgi.version} - - - junit - junit - test - - - - - - - maven-javadoc-plugin - - - generate-javadoc - package - - jar - - - - - org.jboss.apiviz.APIviz - - org.jboss.apiviz - apiviz - 1.2.4.GA - - true - false - - -d ${project.build.directory}/javadoc - -charset UTF-8 - -docencoding UTF-8 - -version - -author - -breakiterator - -windowtitle "${project.name} ${project.version} API Reference" - -doctitle "${project.name} ${project.version} API Reference" - -bottom "Copyright © ${project.inceptionYear}-Present ${project.organization.name}. All Rights Reserved." - -link http://java.sun.com/javase/6/docs/api/ - -sourceclasspath ${project.build.outputDirectory} - - UTF-8 - en_US - - org.scribble.protocol - - org.scribble.protocol.validation.*:*.osgi - - - - - diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/DefaultProtocolContext.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/DefaultProtocolContext.java deleted file mode 100644 index bcbe251d6..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/DefaultProtocolContext.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - * Copyright 2009-11 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol; - -import java.net.MalformedURLException; -import java.util.logging.Level; -import java.util.logging.Logger; - -import org.scribble.common.logging.Journal; -import org.scribble.common.resource.Content; -import org.scribble.common.resource.ResourceContent; -import org.scribble.common.resource.ResourceLocator; -import org.scribble.protocol.model.ProtocolImport; -import org.scribble.protocol.model.ProtocolModel; -import org.scribble.protocol.parser.ProtocolParserManager; - -/** - * This interface represents the context in which a protocol - * will be processed. - * - */ -public class DefaultProtocolContext implements ProtocolContext { - - private ProtocolParserManager _parserManager=null; - private ResourceLocator _resourceLocator=null; - - private static Logger logger=Logger.getLogger(DefaultProtocolContext.class.getName()); - - /** - * This is the default constructor. - */ - public DefaultProtocolContext() { - } - - /** - * This is the constructor for the default protocol context - * implementation. - * - * @param parserManager The parser manager - * @param locator The resource locator - */ - public DefaultProtocolContext(ProtocolParserManager parserManager, - ResourceLocator locator) { - _parserManager = parserManager; - _resourceLocator = locator; - } - - /** - * This method returns the resource locator. - * - * @return The resource locator - */ - public ResourceLocator getResourceLocator() { - return (_resourceLocator); - } - - /** - * This method sets the resource locator. - * - * @param locator The resource locator - */ - public void setResourceLocator(ResourceLocator locator) { - _resourceLocator = locator; - } - - /** - * This method sets the protocol parser manager. - * - * @param ppm The parser manager - */ - public void setProtocolParserManager(ProtocolParserManager ppm) { - _parserManager = ppm; - } - - /** - * This method retrieves a protocol model associated with a protocol - * import statement. - * - * @param pi The protocol import - * @param journal The journal for reporting issues - * @return The protocol model, or null if not found - */ - public ProtocolModel getProtocolModel(ProtocolImport pi, Journal journal) { - ProtocolModel ret=null; - - if (pi.getLocation() == null || pi.getLocation().trim().length() == 0) { - journal.error("Protocol import does not define a location", pi.getProperties()); - } else { - - try { - java.net.URI uri=getResourceLocator().getResourceURI(pi.getLocation()); - - Content content=new ResourceContent(uri); - - ret = _parserManager.parse(this, content, journal); - - } catch (MalformedURLException mue) { - journal.error("Invalid URL '"+mue+"'", pi.getProperties()); - } catch (Exception e) { - logger.log(Level.SEVERE, "Failed to read protocol from '"+pi.getLocation()+"'", e); - - journal.error("Failed to read protocol from '"+pi.getLocation()+"'", - pi.getProperties()); - } - } - - return (ret); - } - -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/ProtocolContext.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/ProtocolContext.java deleted file mode 100644 index 6b90dfa31..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/ProtocolContext.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright 2009-11 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol; - -import org.scribble.common.logging.Journal; -import org.scribble.common.resource.ResourceLocator; -import org.scribble.protocol.model.ProtocolImport; -import org.scribble.protocol.model.ProtocolModel; - -/** - * This interface provides access to capabilities based on the - * protocol being processed. - * - */ -public interface ProtocolContext { - - /** - * This method returns the resource locator. - * - * @return The resource locator - */ - public ResourceLocator getResourceLocator(); - - /** - * This method retrieves a protocol model associated with a protocol - * import statement. - * - * @param pi The protocol import - * @param journal The journal for reporting issues - * @return The protocol model, or null if not found - */ - public ProtocolModel getProtocolModel(ProtocolImport pi, Journal journal); - -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/ProtocolDefinitions.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/ProtocolDefinitions.java deleted file mode 100644 index 942b40b00..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/ProtocolDefinitions.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol; - -/** - * This class provides common protocol definitions. - * - */ -public final class ProtocolDefinitions { - - /** - * Default constructor. - */ - private ProtocolDefinitions() { - } - - /** - * The protocol type. - */ - public static final String PROTOCOL_TYPE = "spr"; - - /** - * The list of reserved workds. - */ - public static final String[] RESERVED_WORDS={ - "import", - "protocol", - "role", - "introduces", - "at", - "from", - "to", - "unordered", - "parallel", - "and", - "choice", - "or", - "repeat", - "run", - "inline", - "do", - "interrupt", - "end" - }; -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/conformance/ConformanceHandler.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/conformance/ConformanceHandler.java deleted file mode 100644 index 2535f9f1e..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/conformance/ConformanceHandler.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright 2009-11 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.conformance; - -import org.scribble.protocol.model.ModelObject; - -/** - * This interface can be used to be informed of the conformance results - * associated with performing a conformance check on two local - * protocol models. - * - * WARNING: This component is still in the EXPERIMENTAL stage, so its API could change. - */ -public interface ConformanceHandler { - - /** - * This method indicates that a new model object has been detected in - * the model. The position of the new object, relative to the reference - * model, is provided by the parent model object in the reference model - * and optionally the index (where relevant). - * - * @param modelObject The new model object, from the model being checked - * @param refParent The 'parent' model object, from the reference model, - * that would contain the new object - * @param index The child index, in the reference model, where the new - * model object would be positioned - */ - public void added(ModelObject modelObject, ModelObject refParent, int index); - - /** - * This method indicates that a change has been detected between - * equivalent model objects found in the primary and reference models. - * - * @param modelObject The model object, from the model being checked - * @param refObject The model object, from the reference model - */ - public void updated(ModelObject modelObject, ModelObject refObject); - - /** - * This method indicates that a model object within the reference model - * does not exist in the model being conformance checked. - * - * @param refObject The model object, not found in the primary model, - * as defined in the reference model - */ - public void removed(ModelObject refObject); - -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/conformance/LoggingConformanceHandler.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/conformance/LoggingConformanceHandler.java deleted file mode 100644 index 1e34521e3..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/conformance/LoggingConformanceHandler.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright 2009-11 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.conformance; - -import org.scribble.common.logging.Journal; -import org.scribble.protocol.model.ModelObject; - -/** - * This implementation records conformance related information to the logging journal. - * - * WARNING: This component is still in the EXPERIMENTAL stage, so its API could change. - */ -public class LoggingConformanceHandler implements ConformanceHandler { - - //private Journal m_logger=null; - - /** - * Conformance model object. - */ - public static final String CONFORMANCE_MODEL_OBJECT="Conformance.Model.Object"; - - /** - * Conformance model object. - */ - public static final String CONFORMANCE_REFERENCE_PARENT="Conformance.Reference.Parent"; - - /** - * Conformance model object. - */ - public static final String CONFORMANCE_REFERENCE_INDEX="Conformance.Reference.Index"; - - /** - * Conformance model object. - */ - public static final String CONFORMANCE_REFERENCE_OBJECT="Conformance.Reference.Object"; - - /** - * This constructor initialises the conformance handler with the journal. - * - * @param logger The journal - */ - public LoggingConformanceHandler(Journal logger) { - //m_logger = logger; - } - - /** - * This method indicates that a new model object has been detected in - * the model. The position of the new object, relative to the reference - * model, is provided by the parent model object in the reference model - * and optionally the index (where relevant). - * - * @param modelObject The new model object, from the model being checked - * @param refParent The 'parent' model object, from the reference model, - * that would contain the new object - * @param index The child index, in the reference model, where the new - * model object would be positioned - */ - public void added(ModelObject modelObject, ModelObject refParent, int index) { - } - - /** - * This method indicates that a change has been detected between - * equivalent model objects found in the primary and reference models. - * - * @param modelObject The model object, from the model being checked - * @param refObject The model object, from the reference model - */ - public void updated(ModelObject modelObject, ModelObject refObject) { - } - - /** - * This method indicates that a model object within the reference model - * does not exist in the model being conformance checked. - * - * @param refObject The model object, not found in the primary model, - * as defined in the reference model - */ - public void removed(ModelObject refObject) { - } - -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/conformance/ProtocolConformer.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/conformance/ProtocolConformer.java deleted file mode 100644 index b09dde7bf..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/conformance/ProtocolConformer.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright 2009 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.conformance; - -/** - * This interface represents a conformance checking capability for the Protocol - * description. - * - * WARNING: This component is still in the EXPERIMENTAL stage, so its API could change. - */ -public interface ProtocolConformer { - - /** - * This method checks whether the supplied model conforms to - * the reference model. - * - * @param model The model to be verified - * @param ref The reference model - * @param handler Handler for reporting conformance results - */ - public void conforms(org.scribble.protocol.model.ProtocolModel model, - org.scribble.protocol.model.ProtocolModel ref, - ConformanceHandler handler); - -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/export/DefaultProtocolExportManager.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/export/DefaultProtocolExportManager.java deleted file mode 100644 index 8ad4a0c6b..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/export/DefaultProtocolExportManager.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.export; - -/** - * This is the default protocol export manager implementation. - * - */ -public class DefaultProtocolExportManager implements ProtocolExportManager { - - private java.util.List _exporters=null; - - /** - * This method returns the protocol exporter associated with - * the supplied id. - * - * @param id The id - * @return The exporter, or null if not found - */ - public ProtocolExporter getExporter(String id) { - if (_exporters != null) { - for (ProtocolExporter pe : _exporters) { - if (pe.getId().equals(id)) { - return (pe); - } - } - } - - return (null); - } - - /** - * This method returns the list of exporters registered - * with the manager. - * - * @return The list of exporters - */ - public java.util.List getExporters() { - if (_exporters == null) { - _exporters = new java.util.ArrayList(); - } - - return (_exporters); - } - - /** - * This method sets the list of exporters registered - * with the manager. - * - * @param exporters The list of exporters - */ - public void setExporters(java.util.List exporters) { - _exporters = exporters; - } -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/export/ProtocolExportManager.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/export/ProtocolExportManager.java deleted file mode 100644 index 8cb8dabb1..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/export/ProtocolExportManager.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.export; - -/** - * This interface manages a set of protocol exporters. - * - */ -public interface ProtocolExportManager { - - /** - * This method returns the protocol exporter associated with - * the supplied id. - * - * @param id The id - * @return The exporter, or null if not found - */ - public ProtocolExporter getExporter(String id); - - /** - * This method returns the list of exporters registered - * with the manager. - * - * @return The list of exporters - */ - public java.util.List getExporters(); - - /** - * This method sets the list of exporters registered - * with the manager. - * - * @param exporters The list of exporters - */ - public void setExporters(java.util.List exporters); - -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/export/ProtocolExportManagerFactory.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/export/ProtocolExportManagerFactory.java deleted file mode 100644 index e92dc2126..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/export/ProtocolExportManagerFactory.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.export; - -/** - * This method returns an instance of the export manager. - * - */ -public final class ProtocolExportManagerFactory { - - private final static ProtocolExportManager INSTANCE= - new org.scribble.protocol.export.DefaultProtocolExportManager(); - - /** - * Default private constructor. - */ - private ProtocolExportManagerFactory() { - } - - /** - * This method returns the export manager. - * - * @return The export manager - */ - public static ProtocolExportManager getExportManager() { - return (INSTANCE); - } -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/export/ProtocolExporter.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/export/ProtocolExporter.java deleted file mode 100644 index e4d727b53..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/export/ProtocolExporter.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.export; - -import org.scribble.common.logging.Journal; -import org.scribble.protocol.model.ProtocolModel; - -/** - * This interface provides an export mechanism for converting a - * Protocol Model into a range of other representations. - * - */ -public interface ProtocolExporter { - - /** - * This method returns the id of the exporter. - * - * @return The exporter id - */ - public String getId(); - - /** - * This method returns the name of the exporter for use in - * user based selectors. - * - * @return The name of the exporter - */ - public String getName(); - - /** - * This method exports the supplied protocol model, in the implementation - * specific format, to the specified output stream. If any issues occur - * during the export process, they will be reported to the journal. - * - * @param model The protocol model to be exported - * @param journal The journal - * @param os The output stream - * @throws java.io.IOException Failed to export - */ - public void export(ProtocolModel model, Journal journal, java.io.OutputStream os) - throws java.io.IOException; - -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/export/text/TextProtocolExporter.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/export/text/TextProtocolExporter.java deleted file mode 100644 index df7941a83..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/export/text/TextProtocolExporter.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.export.text; - -import java.text.MessageFormat; - -import org.scribble.common.logging.Journal; -import org.scribble.protocol.export.ProtocolExporter; -import org.scribble.protocol.model.ProtocolModel; - -/** - * This class provides a text based exporter for the protocol. - * - */ -public class TextProtocolExporter implements ProtocolExporter { - - /** - * Export id for text. - */ - public static final String TEXT_ID = "txt"; - - private java.util.List _rules= - new java.util.Vector(); - - /** - * This method returns the id of the exporter. - * - * @return The exporter id - */ - public String getId() { - return (TEXT_ID); - } - - /** - * This method returns the name of the exporter for use in - * user based selectors. - * - * @return The name of the exporter - */ - public String getName() { - return ("Text"); - } - - /** - * This method exports the supplied protocol model, in the implementation - * specific format, to the specified output stream. If any issues occur - * during the export process, they will be reported to the journal. - * - * @param model The protocol model to be exported - * @param journal The journal - * @param os The output stream - */ - public void export(ProtocolModel model, Journal journal, java.io.OutputStream os) { - TextProtocolExporterVisitor visitor=createVisitor(journal, os, _rules); - - model.visit(visitor); - - if (visitor.getException() != null) { - journal.error(MessageFormat.format( - java.util.PropertyResourceBundle.getBundle( - "org.scribble.protocol.Messages").getString("_EXPORT_FAILED"), - visitor.getException().getLocalizedMessage()), null); - } - } - - /** - * This method creates the text protocol export visitor. - * - * @param journal The journal - * @param os The output stream - * @return The visitor - */ - protected TextProtocolExporterVisitor createVisitor(Journal journal, java.io.OutputStream os) { - return (new TextProtocolExporterVisitor(journal, os)); - } - - /** - * This method creates the text protocol export visitor. - * - * @param journal The journal - * @param os The output stream - * @param rules The additional set of rules - * @return The visitor - */ - protected TextProtocolExporterVisitor createVisitor(Journal journal, java.io.OutputStream os, - java.util.List rules) { - return (new TextProtocolExporterVisitor(journal, os, rules)); - } - - /** - * This method registers a text protocol exporter rule. - * - * @param rule The rule - */ - public void register(TextProtocolExporterRule rule) { - _rules.add(rule); - } - - /** - * This method unregisters a text protocol exporter rule. - * - * @param rule The rule - */ - public void unregister(TextProtocolExporterRule rule) { - _rules.remove(rule); - } -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/export/text/TextProtocolExporterRule.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/export/text/TextProtocolExporterRule.java deleted file mode 100644 index bccfa4ae1..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/export/text/TextProtocolExporterRule.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * JBoss, Home of Professional Open Source - * Copyright 2008-11, Red Hat Middleware LLC, and others contributors as indicated - * by the @authors tag. All rights reserved. - * See the copyright.txt in the distribution for a - * full listing of individual contributors. - * This copyrighted material is made available to anyone wishing to use, - * modify, copy, or redistribute it subject to the terms and conditions - * of the GNU Lesser General Public License, v. 2.1. - * This program is distributed in the hope that it will be useful, but WITHOUT A - * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A - * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License, - * v.2.1 along with this distribution; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301, USA. - */ -package org.scribble.protocol.export.text; - -import org.scribble.common.logging.Journal; -import org.scribble.protocol.model.ModelObject; - -/** - * This interface represents a rule used to provide - * protocol model object's with text export capabilities. - * - */ -public interface TextProtocolExporterRule { - - /** - * This method determines whether the text protocol - * exporter rule is associated with the supplied - * model object. - * - * @param obj The model object - * @return Whether the rule supports the supplied object - */ - public boolean isSupported(ModelObject obj); - - /** - * This method exports the supplied model object to export. - * If errors occur, then they will be reported to - * the journal, and a null will be returned. - * - * @param obj The model object - * @param journal The journal - * @return The text, or null if cannot export - */ - public String getText(ModelObject obj, Journal journal); - -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/export/text/TextProtocolExporterVisitor.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/export/text/TextProtocolExporterVisitor.java deleted file mode 100644 index 48660074b..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/export/text/TextProtocolExporterVisitor.java +++ /dev/null @@ -1,907 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.export.text; - -import org.scribble.common.logging.Journal; -import org.scribble.common.model.Annotation; -import org.scribble.protocol.model.Block; -import org.scribble.protocol.model.CustomActivity; -import org.scribble.protocol.model.Visitor; -import org.scribble.protocol.model.Parallel; -import org.scribble.protocol.model.Choice; -import org.scribble.protocol.model.OnMessage; -import org.scribble.protocol.model.Interaction; -import org.scribble.protocol.model.Interrupt; -import org.scribble.protocol.model.Do; -import org.scribble.protocol.model.Introduces; -import org.scribble.protocol.model.MessageSignature; -import org.scribble.protocol.model.ParameterDefinition; -import org.scribble.protocol.model.Protocol; -import org.scribble.protocol.model.ProtocolImport; -import org.scribble.protocol.model.RecBlock; -import org.scribble.protocol.model.ProtocolImportList; -import org.scribble.protocol.model.Recursion; -import org.scribble.protocol.model.Repeat; -import org.scribble.protocol.model.DirectedChoice; -import org.scribble.protocol.model.End; -import org.scribble.protocol.model.Inline; -import org.scribble.protocol.model.Run; -import org.scribble.protocol.model.TypeImport; -import org.scribble.protocol.model.TypeImportList; -import org.scribble.protocol.model.Unordered; - -/** - * This class provides a protocol visitor used to export a text - * based representation of a protocol. - * - */ -public class TextProtocolExporterVisitor implements Visitor { - - private java.io.OutputStream _outputStream=null; - private Journal _journal=null; - private int _indent=0; - private Exception _exception=null; - private java.util.List _rules=null; - - /** - * This is the visitor for the text based protocol export. - * - * @param journal The journal - * @param os The output stream - */ - public TextProtocolExporterVisitor(Journal journal, java.io.OutputStream os) { - _journal = journal; - _outputStream = os; - } - - /** - * This is the visitor for the text based protocol export. - * - * @param journal The journal - * @param os The output stream - * @param rules The additional exporter rules - */ - public TextProtocolExporterVisitor(Journal journal, java.io.OutputStream os, - java.util.List rules) { - _journal = journal; - _outputStream = os; - _rules = rules; - } - - /** - * This method indicates the start of a - * block. - * - * @param elem The block - * @return Whether to process the contents - */ - public boolean start(Block elem) { - - // Only add the 'and' keyword if the parent is a Parallel construct - // and the block being processed is not the first block - if (elem.getParent() instanceof Parallel - && ((Parallel) elem.getParent()).getPaths().indexOf(elem) > 0) { - output(" and"); - } else if (elem.getParent() instanceof Choice - && ((Choice) elem.getParent()).getPaths().indexOf(elem) > 0) { - output(" or"); - } - - if (!(elem.getParent() instanceof OnMessage)) { - output(" {\r\n"); - } - - _indent++; - - return (true); - } - - /** - * This method indicates the end of a - * block. - * - * @param elem The block - */ - public void end(Block elem) { - // If parent is not a Protocol, then perform end of block functonality - if (!(elem.getParent() instanceof Protocol)) { - endOfBlock(elem); - } - } - - protected void endOfBlock(Block elem) { - _indent--; - - indent(); - - if (!(elem.getParent() instanceof OnMessage)) { - output("}"); - } - - // Place newline after close bracket, unless the parent element is a - // multipath construct AND the block is not the final block - if (isEndOfBlock(elem)) { - output("\r\n"); - } - } - - /** - * This method determines if this is the last block. - * - * @param elem The block - * @return Whether the element is the last block - */ - protected boolean isEndOfBlock(Block elem) { - boolean ret=true; - - if (elem.getParent() instanceof Parallel) { - ret = ((Parallel) elem.getParent()).getPaths().indexOf(elem) - == ((Parallel) elem.getParent()).getPaths().size()-1; - } else if (elem.getParent() instanceof Choice) { - ret = ((Choice) elem.getParent()).getPaths().indexOf(elem) - == ((Choice) elem.getParent()).getPaths().size()-1; - } else if (elem.getParent() instanceof Interrupt) { - Interrupt c=(Interrupt) elem.getParent(); - - if (c.getParent() instanceof Do) { - Do te=(Do) c.getParent(); - - ret = te.getInterrupts().indexOf(c) == te.getInterrupts().size()-1; - } - } else if (elem.getParent() instanceof Do) { - ret = ((Do) elem.getParent()).getInterrupts().size() == 0; - } - - return (ret); - } - - /** - * This method visits an import component. - * - * @param elem The import - */ - public void accept(TypeImportList elem) { - for (Annotation annotation : elem.getAnnotations()) { - output("[["+annotation.toString()+"]]\r\n"); - } - - output("import "); - - boolean first=true; - - if (elem.getFormat() != null) { - output(elem.getFormat()+" "); - } - - for (TypeImport t : elem.getTypeImports()) { - if (!first) { - output(", "); - } - - first = false; - - if (t.getDataType() != null && t.getDataType().getDetails() != null) { - output("\""+t.getDataType().getDetails()+"\" as "); - } - - output(t.getName()); - } - - if (elem.getLocation() != null) { - output(" from \""+elem.getLocation()+"\""); - } - - output(";\r\n"); - } - - - /** - * This method visits an import component. - * - * @param elem The protocol import list - */ - public void accept(ProtocolImportList elem) { - for (Annotation annotation : elem.getAnnotations()) { - output("[["+annotation.toString()+"]]\r\n"); - } - - output("import protocol "); - - boolean first=true; - for (ProtocolImport t : elem.getProtocolImports()) { - if (!first) { - output(", "); - } - - first = false; - output(t.getName()); - - output(" from \""+t.getLocation()+"\""); - } - - output(";\r\n"); - } - - /** - * This method visits the role list. - * - * @param elem The role list - */ - public void accept(Introduces elem) { - for (Annotation annotation : elem.getAnnotations()) { - indent(); - output("[["+annotation.toString()+"]]\r\n"); - } - - indent(); - - output(elem.getIntroducer().getName()); - - output(" introduces "); - - for (int i=0; i < elem.getIntroducedRoles().size(); i++) { - if (i > 0) { - output(", "); - } - output(elem.getIntroducedRoles().get(i).getName()); - } - - output(";\r\n"); - } - - /** - * This method visits an interaction component. - * - * @param elem The interaction - */ - public void accept(Interaction elem) { - - if (!(elem.getParent() instanceof Interrupt)) { - for (Annotation annotation : elem.getAnnotations()) { - indent(); - output("[["+annotation.toString()+"]]\r\n"); - } - - indent(); - - outputInteraction(elem); - - output(";\r\n"); - } - } - - /** - * This method outputs the information about the supplied - * interaction. - * - * @param elem The interaction - */ - protected void outputInteraction(Interaction elem) { - - outputMessageSignature(elem.getMessageSignature()); - - if (elem.getFromRole() != null) { - output(" from "+elem.getFromRole().getName()); - } - - if (elem.getToRoles().size() > 0) { - output(" to "); - - for (int i=0; i < elem.getToRoles().size(); i++) { - if (i > 0) { - output(","); - } - output(elem.getToRoles().get(i).getName()); - } - } - - } - - /** - * This method visits a recursion component. - * - * @param elem The recursion - */ - public void accept(Recursion elem) { - for (Annotation annotation : elem.getAnnotations()) { - indent(); - output("[["+annotation.toString()+"]]\r\n"); - } - - indent(); - - if (elem.getLabel() != null) { - output(elem.getLabel()); - } - - output(";\r\n"); - } - - /** - * This method indicates the start of a - * protocol. - * - * @param elem The protocol - * @return Whether to process the contents - */ - public boolean start(Protocol elem) { - for (Annotation annotation : elem.getAnnotations()) { - indent(); - output("[["+annotation.toString()+"]]\r\n"); - } - - indent(); - - output("protocol "+elem.getName()); - - if (elem.getLocatedRole() != null) { - output(" at "+elem.getLocatedRole().getName()); - } - - if (elem.getParameterDefinitions().size() > 0) { - output("("); - - for (int i=0; i < elem.getParameterDefinitions().size(); i++) { - ParameterDefinition pd=elem.getParameterDefinitions().get(i); - - if (i > 0) { - output(", "); - } - - if (pd.getRole() != null) { - output("role "+pd.getRole().getName()); - } else { - output(pd.getType().getName()+" "+pd.getName()); - } - } - - output(")"); - } - - return (true); - } - - /** - * This method indicates the start of a - * choice. - * - * @param elem The choice - * @return Whether to process the contents - */ - public boolean start(Choice elem) { - for (Annotation annotation : elem.getAnnotations()) { - indent(); - output("[["+annotation.toString()+"]]\r\n"); - } - - indent(); - - output("choice"); - - if (elem.getRole() != null) { - output(" at "+elem.getRole().getName()); - } - - //output(" {\r\n"); - - //m_indent++; - - return (true); - } - - /** - * This method indicates the start of a - * directed choice. - * - * @param elem The directed choice - * @return Whether to process the contents - */ - public boolean start(DirectedChoice elem) { - for (Annotation annotation : elem.getAnnotations()) { - indent(); - output("[["+annotation.toString()+"]]\r\n"); - } - - indent(); - - if (elem.getFromRole() != null) { - output("from "+elem.getFromRole().getName()+" "); - } - - if (elem.getToRoles().size() > 0) { - output("to "); - - for (int i=0; i < elem.getToRoles().size(); i++) { - if (i > 0) { - output(", "); - } - - output(elem.getToRoles().get(i).getName()); - } - } - - output(" {\r\n"); - - _indent++; - - return (true); - } - - /** - * This method indicates the start of a - * directed choice. - * - * @param elem The on-message - * @return Whether to process the contents - */ - public boolean start(OnMessage elem) { - for (Annotation annotation : elem.getAnnotations()) { - indent(); - output("[["+annotation.toString()+"]]\r\n"); - } - - indent(); - - outputMessageSignature(elem.getMessageSignature()); - - output(":\r\n"); - - //m_indent++; - - return (true); - } - - /** - * This method indicates the end of a - * choice. - * - * @param elem The choice - */ - public void end(Choice elem) { - - //m_indent--; - - //indent(); - - //output("}\r\n"); - } - - /** - * This method indicates the end of a - * choice. - * - * @param elem The choice - */ - public void end(DirectedChoice elem) { - - _indent--; - - indent(); - - output("}\r\n"); - } - - /** - * This method indicates the end of a - * on-message. - * - * @param elem The on-message - */ - public void end(OnMessage elem) { - } - - /** - * This method processes an interrupt clause. - * - * @param elem The interrupt - * @return Whether to process the block contents - */ - public boolean start(Interrupt elem) { - - indent(); - - output(" interrupt"); - - return (true); - } - - /** - * This method outputs information about the supplied - * message signature. - * - * @param ms The message signature - */ - private void outputMessageSignature(MessageSignature ms) { - if (ms != null) { - if (ms.getOperation() != null) { - output(ms.getOperation()+"("); - - for (int i=0; i < ms.getTypeReferences().size(); i++) { - if (i > 0) { - output(", "); - } - output(ms.getTypeReferences().get(i).getName()); - } - - output(")"); - } else if (ms.getTypeReferences().size() > 0) { - output(ms.getTypeReferences().get(0).getName()); - } - } - } - - /** - * This method indicates the start of a - * run. - * - * @param elem The run - */ - public void accept(Run elem) { - for (Annotation annotation : elem.getAnnotations()) { - indent(); - output("[["+annotation.toString()+"]]\r\n"); - } - - indent(); - - output("run "+elem.getProtocolReference().getName()); - - if (elem.getProtocolReference().getRole() != null) { - output(" at "+elem.getProtocolReference().getRole().getName()); - } - - if (elem.getParameters().size() > 0) { - output("("); - - for (int i=0; i < elem.getParameters().size(); i++) { - if (i > 0) { - output(", "); - } - - output(elem.getParameters().get(i).getName()); - } - - output(")"); - } - - if (elem.getFromRole() != null) { - output(" from "+elem.getFromRole().getName()); - } - - output(";\r\n"); - } - - /** - * This method indicates the start of a - * parallel. - * - * @param elem The parallel - * @return Whether to process the contents - */ - public boolean start(Parallel elem) { - for (Annotation annotation : elem.getAnnotations()) { - indent(); - output("[["+annotation.toString()+"]]\r\n"); - } - - indent(); - - output("parallel"); - - return (true); - } - - /** - * This method indicates the end of a - * parallel. - * - * @param elem The parallel - */ - public void end(Parallel elem) { - } - - /** - * This method indicates the start of a - * try/escape. - * - * @param elem The try escape - * @return Whether to process the contents - */ - public boolean start(Do elem) { - for (Annotation annotation : elem.getAnnotations()) { - indent(); - output("[["+annotation.toString()+"]]\r\n"); - } - - indent(); - - output("do"); - - return (true); - } - - /** - * This method indicates the end of a - * try/escape. - * - * @param elem The try escape - */ - public void end(Do elem) { - } - - /** - * This method indicates the start of a - * repeat. - * - * @param elem The repeat - * @return Whether to process the contents - */ - public boolean start(Repeat elem) { - for (Annotation annotation : elem.getAnnotations()) { - indent(); - output("[["+annotation.toString()+"]]\r\n"); - } - - indent(); - - output("repeat"); - - if (elem.getRoles().size() > 0) { - output(" at "); - - for (int i=0; i < elem.getRoles().size(); i++) { - if (i > 0) { - output(","); - } - - output(elem.getRoles().get(i).getName()); - } - } - - return (true); - } - - /** - * This method indicates the end of a - * repeat. - * - * @param elem The repeat - */ - public void end(Repeat elem) { - } - - /** - * This method indicates the start of a - * unordered block. - * - * @param elem The unordered block - * @return Whether to process the contents - */ - public boolean start(Unordered elem) { - for (Annotation annotation : elem.getAnnotations()) { - indent(); - output("[["+annotation.toString()+"]]\r\n"); - } - - indent(); - - output("unordered"); - - return (true); - } - - /** - * This method indicates the end of a - * unordered block. - * - * @param elem The unordered block - */ - public void end(Unordered elem) { - } - - /** - * This method indicates the start of a - * labelled block. - * - * @param elem The labelled block - * @return Whether to process the contents - */ - public boolean start(RecBlock elem) { - for (Annotation annotation : elem.getAnnotations()) { - indent(); - output("[["+annotation.toString()+"]]\r\n"); - } - - indent(); - - if (elem.getLabel() != null) { - output("rec "+elem.getLabel()); - } - - return (true); - } - - /** - * This method indicates the end of a - * labelled block. - * - * @param elem The labelled block - */ - public void end(RecBlock elem) { - } - - /** - * This method indents the output. - */ - protected void indent() { - for (int i=0; i < _indent; i++) { - output("\t"); - } - } - - /** - * This method outputs the supplied string. - * - * @param str The string - */ - protected void output(String str) { - try { - _outputStream.write(str.getBytes()); - } catch (Exception e) { - _exception = e; - } - } - - /** - * This method return the exception. - * - * @return The exception, or null if not found - */ - public Exception getException() { - return (_exception); - } - - /** - * This method returns the journal. - * - * @return The journal - */ - public Journal getJournal() { - return (_journal); - } - - /** - * This method indicates the end of the protocol. - * - * @param elem The protocol - */ - public void end(Protocol elem) { - - // Perform end of block - needed to be postponed to ensure - // nested protocols are exported within the outer protocol - endOfBlock(elem.getBlock()); - } - - /** - * This method indicates the end of the interrupt. - * - * @param elem The interrupt - */ - public void end(Interrupt elem) { - } - - /** - * This method accepts an 'inline' construct. - * - * @param elem The inline construct - */ - public void accept(Inline elem) { - for (Annotation annotation : elem.getAnnotations()) { - indent(); - output("[["+annotation.toString()+"]]\r\n"); - } - - indent(); - - output("inline "+elem.getProtocolReference().getName()); - - if (elem.getProtocolReference().getRole() != null) { - output(" at "+elem.getProtocolReference().getRole().getName()); - } - - if (elem.getParameters().size() > 0) { - output("("); - - for (int i=0; i < elem.getParameters().size(); i++) { - if (i > 0) { - output(", "); - } - - output(elem.getParameters().get(i).getName()); - } - - output(")"); - } - - output(";\r\n"); - } - - /** - * This method accepts a type import. - * - * @param elem The type import - */ - public void accept(TypeImport elem) { - } - - /** - * This method accepts a protocol import. - * - * @param elem The protocol import - */ - public void accept(ProtocolImport elem) { - } - - /** - * This method visits an end statement. - * - * @param elem The end statement - */ - public void accept(End elem) { - for (Annotation annotation : elem.getAnnotations()) { - indent(); - output("[["+annotation.toString()+"]]\r\n"); - } - - indent(); - - output("end;\r\n"); - } - - /** - * This method visits an end statement. - * - * @param elem The end statement - */ - public void accept(CustomActivity elem) { - - // Check if element can be exported to text - if (_rules != null) { - - for (TextProtocolExporterRule rule : _rules) { - - if (rule.isSupported(elem)) { - String exported=rule.getText(elem, _journal); - - if (exported != null) { - for (Annotation annotation : elem.getAnnotations()) { - indent(); - output("[["+annotation.toString()+"]]\r\n"); - } - - indent(); - - output(exported+";\r\n"); - - break; - } - } - } - } - - } - -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/AbstractModelObjectVisitor.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/AbstractModelObjectVisitor.java deleted file mode 100644 index 405d72733..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/AbstractModelObjectVisitor.java +++ /dev/null @@ -1,361 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.model; - -/** - * This class provides a default visitor which can be used - * to traverse a model. - */ -public abstract class AbstractModelObjectVisitor implements Visitor { - - /** - * The default constructor. - */ - public AbstractModelObjectVisitor() { - } - - /** - * This method can be implemented to process all of the model - * objects within a particular protocol model. - * - * @param obj The model object - * @return Whether to process the contents - */ - public abstract boolean process(ModelObject obj); - - /** - * This method indicates the start of a - * block. - * - * @param elem The block - * @return Whether to process the contents - */ - public boolean start(Block elem) { - return (process(elem)); - } - - /** - * This method indicates the end of a - * block. - * - * @param elem The block - */ - public void end(Block elem) { - } - - /** - * This method visits an import component. - * - * @param elem The import - */ - public void accept(TypeImportList elem) { - process(elem); - } - - /** - * This method visits an import component. - * - * @param elem The import - */ - public void accept(ProtocolImportList elem) { - process(elem); - } - - /** - * This method visits an interaction component. - * - * @param elem The interaction - */ - public void accept(Interaction elem) { - process(elem); - } - - /** - * This method indicates the start of a - * run construct. - * - * @param elem The run - */ - public void accept(Run elem) { - process(elem); - } - - /** - * This method visits an use component. - * - * @param elem The use component - */ - public void accept(Inline elem) { - process(elem); - } - - /** - * This method visits a recursion component. - * - * @param elem The recursion - */ - public void accept(Recursion elem) { - process(elem); - } - - /** - * This method visits the role list. - * - * @param elem The role list - */ - public void accept(Introduces elem) { - process(elem); - } - - /** - * This method indicates the start of a - * protocol. - * - * @param elem The protocol - * @return Whether to process the contents - */ - public boolean start(Protocol elem) { - return (process(elem)); - } - - /** - * This method indicates the end of a - * protocol. - * - * @param elem The protocol - */ - public void end(Protocol elem) { - } - - /** - * This method indicates the start of a - * choice. - * - * @param elem The choice - * @return Whether to process the contents - */ - public boolean start(Choice elem) { - return (process(elem)); - } - - /** - * This method indicates the end of a - * choice. - * - * @param elem The choice - */ - public void end(Choice elem) { - } - - /** - * This method indicates the start of a - * directed choice. - * - * @param elem The directed choice - * @return Whether to process the contents - */ - public boolean start(DirectedChoice elem) { - return (process(elem)); - } - - /** - * This method indicates the end of a - * directed choice. - * - * @param elem The directed choice - */ - public void end(DirectedChoice elem) { - } - - /** - * This method indicates the start of a - * on-message. - * - * @param elem The on-message element - * @return Whether to process the contents - */ - public boolean start(OnMessage elem) { - return (process(elem)); - } - - /** - * This method indicates the end of a - * on-message. - * - * @param elem The on-message element - */ - public void end(OnMessage elem) { - } - - /** - * This method indicates the start of a - * parallel. - * - * @param elem The parallel - * @return Whether to process the contents - */ - public boolean start(Parallel elem) { - return (process(elem)); - } - - /** - * This method indicates the end of a - * parallel. - * - * @param elem The parallel - */ - public void end(Parallel elem) { - } - - /** - * This method indicates the start of a - * repeat. - * - * @param elem The repeat - * @return Whether to process the contents - */ - public boolean start(Repeat elem) { - return (process(elem)); - } - - /** - * This method indicates the end of a - * repeat. - * - * @param elem The repeat - */ - public void end(Repeat elem) { - } - - /** - * This method indicates the start of a - * labelled block. - * - * @param elem The labelled block - * @return Whether to process the contents - */ - public boolean start(RecBlock elem) { - return (process(elem)); - } - - /** - * This method indicates the end of a - * labelled block. - * - * @param elem The labelled block - */ - public void end(RecBlock elem) { - } - - /** - * This method indicates the start of an - * Unordered construct. - * - * @param elem The Unordered construct - * @return Whether to process the contents - */ - public boolean start(Unordered elem) { - return (process(elem)); - } - - /** - * This method indicates the end of an - * Unordered construct. - * - * @param elem The Unordered construct - */ - public void end(Unordered elem) { - } - - /** - * This method indicates the start of a - * try escape. - * - * @param elem The try escape - * @return Whether to process the contents - */ - public boolean start(Do elem) { - return (process(elem)); - } - - /** - * This method indicates the end of a - * try escape. - * - * @param elem The try escape - */ - public void end(Do elem) { - } - - /** - * This method indicates the start of a - * catch block. - * - * @param elem The catch block - * @return Whether to process the contents - */ - public boolean start(Interrupt elem) { - boolean ret=process(elem); - - return (ret); - } - - /** - * This method indicates the end of a - * catch block. - * - * @param elem The catch block - */ - public void end(Interrupt elem) { - } - - /** - * This method visits a type component. - * - * @param elem The type - */ - public void accept(TypeImport elem) { - process(elem); - } - - /** - * This method visits a protocol import component. - * - * @param elem The protocol import - */ - public void accept(ProtocolImport elem) { - process(elem); - } - - /** - * This method visits an end statement. - * - * @param elem The end statement - */ - public void accept(End elem) { - process(elem); - } - - /** - * This method visits a custom activity. - * - * @param elem The custom activity - */ - public void accept(CustomActivity elem) { - process(elem); - } - -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/Activity.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/Activity.java deleted file mode 100644 index 250c8d27e..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/Activity.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright 2009 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.model; - -/** - * This class represents the base class for all Scribble definition - * components. - */ -public abstract class Activity extends ModelObject { - - /** - * The default constructor. - */ - public Activity() { - } - - /** - * The copy constructor. - * - * @param act The activity - */ - public Activity(Activity act) { - super(act); - } - - /** - * This method returns the protocol in which this - * activity is contained. - * - * @return The protocol, or null if not found - */ - public Protocol getEnclosingProtocol() { - Protocol ret=null; - ModelObject cur=this; - - while (ret == null && cur != null) { - - if (cur instanceof Protocol) { - ret = (Protocol) cur; - } else { - cur = cur.getParent(); - } - } - - return (ret); - } - -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/Block.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/Block.java deleted file mode 100644 index 9823f5bbd..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/Block.java +++ /dev/null @@ -1,134 +0,0 @@ -/* - * Copyright 2009 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.model; - -/** - * This class represents a group of activities. - * - */ -public class Block extends Activity { - - private java.util.List _contents= - new ContainmentList(this, Activity.class); - - /** - * This method returns the contents associated with - * the block. - * - * @return The contents - */ - public java.util.List getContents() { - return (_contents); - } - - /** - * This method adds an activity to the block. - * - * @param act The activity - * @return Whether the activity has been added - */ - public boolean add(Activity act) { - return (_contents.add(act)); - } - - /** - * This method removes an activity from the block. - * - * @param act The activity - * @return Whether the activity has been removed - */ - public boolean remove(Activity act) { - return (_contents.remove(act)); - } - - /** - * This method returns the number of activities - * in the block. - * - * @return The number of activities - */ - public int size() { - return (_contents.size()); - } - - /** - * This method returns the activity at the specified - * index. - * - * @param index The index The index - * @return The activity The activity - * @throws IndexOutOfBoundsException Out of bounds - */ - public Activity get(int index) throws IndexOutOfBoundsException { - return (_contents.get(index)); - } - - /** - * This method returns the index of the supplied activity. - * - * @param act The activity - * @return The index, or -1 if the activity is not found - */ - public int indexOf(Activity act) { - return (_contents.indexOf(act)); - } - - /** - * This method visits the model object using the supplied - * visitor. - * - * @param visitor The visitor - */ - public void visit(Visitor visitor) { - - if (visitor.start(this)) { - - for (int i=0; i < getContents().size(); i++) { - getContents().get(i).visit(visitor); - } - } - - visitor.end(this); - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - - Block that = (Block) o; - - return _contents.equals(that._contents); - } - - @Override - public int hashCode() { - return _contents.hashCode(); - } - - @Override - public String toString() { - String result = "{\n"; - for (Activity act : _contents) { - result += act + "\n"; - } - return result + "}"; - } -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/Choice.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/Choice.java deleted file mode 100644 index 0a13416a3..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/Choice.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Copyright 2009 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.model; - -/** - * This class represents the Choice construct between - * two or more paths. - * - */ -public class Choice extends Activity { - - private Role _role=null; - private java.util.List _blocks=new ContainmentList(this, Block.class); - - /** - * This is the default constructor. - * - */ - public Choice() { - } - - /** - * This method returns the role. - * - * @return The role - */ - public Role getRole() { - return (_role); - } - - /** - * This method sets the role. - * - * @param part The role - */ - public void setRole(Role part) { - _role = part; - } - - /** - * This method returns the list of mutually exclusive - * activity blocks that comprise the multi-path construct. - * - * @return The list of choice paths - */ - public java.util.List getPaths() { - return (_blocks); - } - - /** - * This method visits the model object using the supplied - * visitor. - * - * @param visitor The visitor - */ - public void visit(Visitor visitor) { - if (visitor.start(this)) { - - for (Block b : getPaths()) { - b.visit(visitor); - } - } - - visitor.end(this); - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - - Choice that = (Choice) o; - - return !(_role != null - ? !_role.equals(that._role) - : that._role != null) - && _blocks.equals(that._blocks); - } - - @Override - public int hashCode() { - int result = _blocks.hashCode(); - result = 31 * result + (_role != null ? _role.hashCode() : 0); - return result; - } - - @Override - public String toString() { - String result = "choice "; - if (_role != null) { - result += "at " + _role+" "; - } - for (Block b : _blocks) { - if (_blocks.indexOf(b) > 0) { - result += "or "; - } - result += b + "\n"; - } - return result; - } -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/ContainmentList.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/ContainmentList.java deleted file mode 100644 index 6ed248620..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/ContainmentList.java +++ /dev/null @@ -1,273 +0,0 @@ -/* - * Copyright 2009 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.model; - -import java.util.Collection; -import java.util.List; -import java.util.Vector; - -/** - * This class represents a list that understands how to manage - * containment and parent relationships. - * - * @param The element type - */ -public class ContainmentList extends Vector implements List { - - private static final long serialVersionUID = -1265091580286297521L; - - private ModelObject _parent=null; - private Class _type=null; - - /** - * This is the constructor for the containment list. - * - * @param parent The parent model object - * @param type The type of the elements in the list - */ - public ContainmentList(ModelObject parent, Class type) { - _parent = parent; - _type = type; - } - - /** - * This method returns the base type associated with the list - * elements. - * - * @return The base type for the list elements - */ - public Class getType() { - return (_type); - } - - /** - * Appends the specified element to the end of this list (optional - * operation).

- * - * Lists that support this operation may place limitations on what - * elements may be added to this list. In particular, some - * lists will refuse to add null elements, and others will impose - * restrictions on the type of elements that may be added. List - * classes should clearly specify in their documentation any restrictions - * on what elements may be added. - * - * @param o element to be appended to this list. - * @return true (as per the general contract of the - * Collection.add method). - */ - public boolean add(E o) { - boolean ret=super.add(o); - - if (ret) { - o.setParent(_parent); - } - - return (ret); - } - - /** - * Removes the first occurrence in this list of the specified element - * (optional operation). If this list does not contain the element, it is - * unchanged. More formally, removes the element with the lowest index i - * such that (o==null ? get(i)==null : o.equals(get(i))) (if - * such an element exists). - * - * @param o element to be removed from this list, if present. - * @return true if this list contained the specified element. - */ - public boolean remove(Object o) { - boolean ret=super.remove(o); - - if (ret && o instanceof ModelObject) { - ((ModelObject) o).setParent(null); - } - - return (ret); - } - - /** - * Appends all of the elements in the specified collection to the end of - * this list, in the order that they are returned by the specified - * collection's iterator (optional operation). The behavior of this - * operation is unspecified if the specified collection is modified while - * the operation is in progress. (Note that this will occur if the - * specified collection is this list, and it's nonempty.) - * - * @param c collection whose elements are to be added to this list. - * @return true if this list changed as a result of the call. - * @see #add(Object) - */ - public boolean addAll(Collection c) { - boolean ret=super.addAll(c); - - if (ret) { - java.util.Iterator iter=c.iterator(); - - while (iter.hasNext()) { - iter.next().setParent(_parent); - } - } - - return (ret); - } - - /** - * Inserts all of the elements in the specified collection into this - * list at the specified position (optional operation). Shifts the - * element currently at that position (if any) and any subsequent - * elements to the right (increases their indices). The new elements - * will appear in this list in the order that they are returned by the - * specified collection's iterator. The behavior of this operation is - * unspecified if the specified collection is modified while the - * operation is in progress. (Note that this will occur if the specified - * collection is this list, and it's nonempty.) - * - * @param index index at which to insert first element from the specified - * collection. - * @param c elements to be inserted into this list. - * @return true if this list changed as a result of the call. - */ - public boolean addAll(int index, Collection c) { - boolean ret=super.addAll(index, c); - - if (ret) { - java.util.Iterator iter=c.iterator(); - - while (iter.hasNext()) { - iter.next().setParent(_parent); - } - } - - return (ret); - } - - /** - * Removes from this list all the elements that are contained in the - * specified collection (optional operation). - * - * @param c collection that defines which elements will be removed from - * this list. - * @return true if this list changed as a result of the call. - * @see #remove(Object) - * @see #contains(Object) - */ - public boolean removeAll(Collection c) { - boolean ret=super.removeAll(c); - - if (ret) { - java.util.Iterator iter=c.iterator(); - - while (iter.hasNext()) { - Object val=iter.next(); - if (val instanceof ModelObject) { - ((ModelObject) val).setParent(null); - } - } - } - - return (ret); - } - - /** - * Retains only the elements in this list that are contained in the - * specified collection (optional operation). In other words, removes - * from this list all the elements that are not contained in the specified - * collection. - * - * @param c collection that defines which elements this set will retain. - * - * @return true if this list changed as a result of the call. - * @see #remove(Object) - * @see #contains(Object) - */ - public boolean retainAll(Collection c) { - return (super.retainAll(c)); - } - - /** - * Removes all of the elements from this list (optional operation). This - * list will be empty after this call returns (unless it throws an - * exception). - */ - public void clear() { - java.util.Iterator iter=iterator(); - - while (iter.hasNext()) { - iter.next().setParent(null); - } - - super.clear(); - } - - /** - * Replaces the element at the specified position in this list with the - * specified element (optional operation). - * - * @param index index of element to replace. - * @param element element to be stored at the specified position. - * @return the element previously at the specified position. - */ - public E set(int index, E element) { - E ret=super.set(index, element); - - if (element != null) { - element.setParent(_parent); - } - - if (ret != null) { - ret.setParent(null); - } - - return (ret); - } - - /** - * Inserts the specified element at the specified position in this list - * (optional operation). Shifts the element currently at that position - * (if any) and any subsequent elements to the right (adds one to their - * indices). - * - * @param index index at which the specified element is to be inserted. - * @param element element to be inserted. - * - */ - public void add(int index, E element) { - super.add(index, element); - - if (element != null) { - element.setParent(_parent); - } - } - - /** - * Removes the element at the specified position in this list (optional - * operation). Shifts any subsequent elements to the left (subtracts one - * from their indices). Returns the element that was removed from the - * list. - * - * @param index the index of the element to removed. - * @return the element previously at the specified position. - */ - public E remove(int index) { - E ret=super.remove(index); - - if (ret != null) { - ret.setParent(null); - } - - return (ret); - } -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/CustomActivity.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/CustomActivity.java deleted file mode 100644 index 86e82546b..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/CustomActivity.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.model; - -/** - * This class represents a custom activity. - * - */ -public class CustomActivity extends Activity { - - private java.util.List _roles=new java.util.Vector(); - - /** - * This is the default constructor. - * - */ - public CustomActivity() { - } - - /** - * This is the copy constructor. - * - * @param act The custom activity to copy - */ - public CustomActivity(CustomActivity act) { - super(act); - } - - /** - * This method returns the roles associated with the custom activity. - * - * @return The roles - */ - public java.util.List getRoles() { - return(_roles); - } - - /** - * This method visits the model object using the supplied - * visitor. - * - * @param visitor The visitor - */ - public void visit(Visitor visitor) { - visitor.accept(this); - } -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/DataType.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/DataType.java deleted file mode 100644 index b95a3b525..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/DataType.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.model; - -/** - * This class represents the data type bound to a particular type name used - * in the protocol. - * - */ -public class DataType extends ModelObject { - - private String _details=null; - - /** - * Default constructor. - */ - public DataType() { - } - - /** - * Copy constructor. - * - * @param copy The copy - */ - public DataType(DataType copy) { - _details = copy.getDetails(); - } - - /** - * Constructor used to initialise the data type details. - * - * @param details The details - */ - public DataType(String details) { - _details = details; - } - - /** - * This method returns the details. - * - * @return The details - */ - public String getDetails() { - return (_details); - } - - /** - * This method sets the details. - * - * @param details The details - */ - public void setDetails(String details) { - _details = details; - } - - /** - * This method visits the data type. - * - * @param visitor The visitor - */ - public void visit(Visitor visitor) { - } -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/DefaultVisitor.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/DefaultVisitor.java deleted file mode 100644 index 96b246bbd..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/DefaultVisitor.java +++ /dev/null @@ -1,360 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.model; - -/** - * This class provides a default visitor which can be used - * to traverse a model. - */ -public class DefaultVisitor implements Visitor { - - private boolean _defaultGroupReturn=true; - - /** - * This is the default constructor. - */ - public DefaultVisitor() { - } - - /** - * This constructor configures the default group return value. - * - * @param defaultGroupReturn The default group return value - */ - public DefaultVisitor(boolean defaultGroupReturn) { - _defaultGroupReturn = defaultGroupReturn; - } - - /** - * This method sets the default group construct return value. - * - * @param b The value - */ - public void setDefaultGroupReturn(boolean b) { - _defaultGroupReturn = b; - } - - /** - * This method indicates the start of a - * block. - * - * @param elem The block - * @return Whether to process the contents - */ - public boolean start(Block elem) { - return (_defaultGroupReturn); - } - - /** - * This method indicates the end of a - * block. - * - * @param elem The block - */ - public void end(Block elem) { - } - - /** - * This method visits an import component. - * - * @param elem The import - */ - public void accept(TypeImportList elem) { - } - - /** - * This method visits an import component. - * - * @param elem The import - */ - public void accept(ProtocolImportList elem) { - } - - /** - * This method visits an interaction component. - * - * @param elem The interaction - */ - public void accept(Interaction elem) { - } - - /** - * This method visits a use component. - * - * @param elem The use component - */ - public void accept(Inline elem) { - } - - /** - * This method visits a recursion component. - * - * @param elem The recursion - */ - public void accept(Recursion elem) { - } - - /** - * This method visits the role list. - * - * @param elem The role list - */ - public void accept(Introduces elem) { - } - - /** - * This method indicates the start of a - * protocol. - * - * @param elem The protocol - * @return Whether to process the contents - */ - public boolean start(Protocol elem) { - return (_defaultGroupReturn); - } - - /** - * This method indicates the end of a - * protocol. - * - * @param elem The protocol - */ - public void end(Protocol elem) { - } - - /** - * This method indicates the start of a - * choice. - * - * @param elem The choice - * @return Whether to process the contents - */ - public boolean start(Choice elem) { - return (_defaultGroupReturn); - } - - /** - * This method indicates the end of a - * choice. - * - * @param elem The choice - */ - public void end(Choice elem) { - } - - /** - * This method indicates the start of a - * directed choice. - * - * @param elem The directed choice - * @return Whether to process the contents - */ - public boolean start(DirectedChoice elem) { - return (_defaultGroupReturn); - } - - /** - * This method indicates the end of a - * directed choice. - * - * @param elem The directed choice - */ - public void end(DirectedChoice elem) { - } - - /** - * This method indicates the start of a - * on-message. - * - * @param elem The on-message element - * @return Whether to process the contents - */ - public boolean start(OnMessage elem) { - return (_defaultGroupReturn); - } - - /** - * This method indicates the end of a - * on-message. - * - * @param elem The on-message element - */ - public void end(OnMessage elem) { - } - - /** - * This method indicates the start of a - * parallel. - * - * @param elem The parallel - * @return Whether to process the contents - */ - public boolean start(Parallel elem) { - return (_defaultGroupReturn); - } - - /** - * This method indicates the end of a - * parallel. - * - * @param elem The parallel - */ - public void end(Parallel elem) { - } - - /** - * This method indicates the start of a - * repeat. - * - * @param elem The repeat - * @return Whether to process the contents - */ - public boolean start(Repeat elem) { - return (_defaultGroupReturn); - } - - /** - * This method indicates the end of a - * repeat. - * - * @param elem The repeat - */ - public void end(Repeat elem) { - } - - /** - * This method indicates the start of a - * labelled block. - * - * @param elem The labelled block - * @return Whether to process the contents - */ - public boolean start(RecBlock elem) { - return (_defaultGroupReturn); - } - - /** - * This method indicates the end of a - * labelled block. - * - * @param elem The labelled block - */ - public void end(RecBlock elem) { - } - - /** - * This method indicates the start of an - * Unordered construct. - * - * @param elem The Unordered construct - * @return Whether to process the contents - */ - public boolean start(Unordered elem) { - return (_defaultGroupReturn); - } - - /** - * This method indicates the end of an - * Unordered construct. - * - * @param elem The Unordered construct - */ - public void end(Unordered elem) { - } - - /** - * This method indicates the start of a - * try escape. - * - * @param elem The try escape - * @return Whether to process the contents - */ - public boolean start(Do elem) { - return (_defaultGroupReturn); - } - - /** - * This method indicates the end of a - * try escape. - * - * @param elem The try escape - */ - public void end(Do elem) { - } - - /** - * This method indicates the start of a - * catch block. - * - * @param elem The catch block - * @return Whether to process the contents - */ - public boolean start(Interrupt elem) { - return (_defaultGroupReturn); - } - - /** - * This method indicates the end of a - * catch block. - * - * @param elem The catch block - */ - public void end(Interrupt elem) { - } - - /** - * This method indicates the start of a - * run construct. - * - * @param elem The run - */ - public void accept(Run elem) { - } - - /** - * This method visits a type component. - * - * @param elem The type - */ - public void accept(TypeImport elem) { - } - - /** - * This method visits a protocol import component. - * - * @param elem The protocol import - */ - public void accept(ProtocolImport elem) { - } - - /** - * This method visits an end statement. - * - * @param elem The end statement - */ - public void accept(End elem) { - } - - /** - * This method visits any extensible activity that is not - * part of the base protocol model. - * - * @param elem The custom activity - */ - public void accept(CustomActivity elem) { - } - -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/DirectedChoice.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/DirectedChoice.java deleted file mode 100644 index 37f0908e4..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/DirectedChoice.java +++ /dev/null @@ -1,138 +0,0 @@ -/* - * Copyright 2009 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.model; - -/** - * This class represents the Choice construct between - * two or more paths. - * - */ -public class DirectedChoice extends Activity { - - private Role _fromRole=null; - private java.util.List _toRoles= - new ContainmentList(this, Role.class); - private java.util.List _onMessages=new ContainmentList(this, OnMessage.class); - - /** - * This is the default constructor. - * - */ - public DirectedChoice() { - } - - /** - * This method returns the from role. - * - * @return The from role - */ - public Role getFromRole() { - return (_fromRole); - } - - /** - * This method sets the from role. - * - * @param part The from role - */ - public void setFromRole(Role part) { - _fromRole = part; - } - - /** - * This method returns the optional (one or many) 'to' roles. - * - * @return The optional 'to' roles - */ - public java.util.List getToRoles() { - return (_toRoles); - } - - /** - * This method returns the list of on-message blocks - * representing the different paths of the directed - * choice. - * - * @return The list of on-messages - */ - public java.util.List getOnMessages() { - return (_onMessages); - } - - /** - * This method visits the model object using the supplied - * visitor. - * - * @param visitor The visitor - */ - public void visit(Visitor visitor) { - if (visitor.start(this)) { - for (OnMessage om : getOnMessages()) { - om.visit(visitor); - } - } - - visitor.end(this); - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - - DirectedChoice that = (DirectedChoice) o; - - return !(_fromRole != null - ? !_fromRole.equals(that._fromRole) - : that._fromRole != null) - && _onMessages.equals(that._onMessages); - } - - @Override - public int hashCode() { - int result = _onMessages.hashCode(); - result = 31 * result + (_fromRole != null ? _fromRole.hashCode() : 0); - return result; - } - - @Override - public String toString() { - String result = ""; - if (_fromRole != null) { - result += "from " + _fromRole+" "; - } - if (_toRoles.size() > 0) { - result += "to "; - for (int i=0; i < _toRoles.size(); i++) { - if (i > 0) { - result += ", "; - } - result += _toRoles.get(i); - } - } - for (OnMessage b : _onMessages) { - if (_onMessages.indexOf(b) > 0) { - result += "or "; - } - result += b + "\n"; - } - return result; - } -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/Do.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/Do.java deleted file mode 100644 index 452e797dd..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/Do.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright 2009 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.model; - -/** - * This class represents the Try/Escape construct. - * - */ -public class Do extends Activity { - - private Block _block=null; - private java.util.List _interrupts=new ContainmentList(this, Interrupt.class); - - /** - * This is the default constructor. - * - */ - public Do() { - } - - /** - * This method returns the block of activities associated - * with the definition. - * - * @return The block of activities - */ - public Block getBlock() { - - if (_block == null) { - _block = new Block(); - _block.setParent(this); - } - - return (_block); - } - - /** - * This method sets the block of activities associated - * with the definition. - * - * @param block The block of activities - */ - public void setBlock(Block block) { - if (_block != null) { - _block.setParent(null); - } - - _block = block; - - if (_block != null) { - _block.setParent(this); - } - } - - /** - * This method returns the list of interrupt statements associated - * with the global escape (do). - * - * @return The list of interrupt statements - */ - public java.util.List getInterrupts() { - return (_interrupts); - } - - /** - * This method visits the model object using the supplied - * visitor. - * - * @param visitor The visitor - */ - public void visit(Visitor visitor) { - if (visitor.start(this)) { - - getBlock().visit(visitor); - - for (Interrupt path : getInterrupts()) { - path.visit(visitor); - } - } - - visitor.end(this); - } - -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/End.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/End.java deleted file mode 100644 index 0c1728722..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/End.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.model; - -/** - * This class represents the Include construct. - * - */ -public class End extends Activity { - - /** - * This is the default constructor. - * - */ - public End() { - } - - /** - * This is the copy constructor. - * - * @param end The end activity to copy - */ - public End(End end) { - super(end); - } - - /** - * This method visits the model object using the supplied - * visitor. - * - * @param visitor The visitor - */ - public void visit(Visitor visitor) { - visitor.accept(this); - } -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/ImportList.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/ImportList.java deleted file mode 100644 index 1b0a7614c..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/ImportList.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright 2009 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.model; - -/** - * This class represents an import definition associated with a model. - * - */ -public abstract class ImportList extends ModelObject { - - /** - * The default constructor. - */ - public ImportList() { - } - - /** - * The copy constructor. - * - * @param copy The copy - */ - public ImportList(ImportList copy) { - super(copy); - } - -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/Inline.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/Inline.java deleted file mode 100644 index e870257d1..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/Inline.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.model; - -/** - * This class represents the Include construct. - * - */ -public class Inline extends Activity { - - private ProtocolReference _reference=null; - private java.util.List _parameters=new java.util.Vector(); - - /** - * This is the default constructor. - * - */ - public Inline() { - } - - /** - * This is the copy constructor. - * - * @param copy The instance to copy - */ - public Inline(Inline copy) { - super(copy); - - _reference = new ProtocolReference(copy._reference); - - for (Parameter p : copy._parameters) { - _parameters.add(new Parameter(p)); - } - } - - /** - * This method returns the bindings for the - * composition construct. - * - * @return The list of bindings - */ - public java.util.List getParameters() { - return (_parameters); - } - - /** - * This method returns the declaration binding associated - * with the supplied declaration. - * - * @param declName The declaration - * @return The declaration binding, or null if not found - */ - public Parameter getParameter(String declName) { - Parameter ret=null; - - java.util.Iterator iter=getParameters().iterator(); - - while (ret == null && iter.hasNext()) { - ret = iter.next(); - - if (!ret.getName().equals(declName)) { - ret = null; - } - } - - return (ret); - } - - /** - * This method returns the protocol reference associated - * with the run construct. - * - * @return The protocol reference, or null if not defined - */ - public ProtocolReference getProtocolReference() { - return (_reference); - } - - /** - * This method sets the protocol reference associated - * with the run construct. - * - * @param ref The protocol reference - */ - public void setProtocolReference(ProtocolReference ref) { - - if (_reference != null) { - _reference.setParent(null); - } - - _reference = ref; - - if (_reference != null) { - _reference.setParent(this); - } - } - - /** - * This method visits the model object using the supplied - * visitor. - * - * @param visitor The visitor - */ - public void visit(Visitor visitor) { - visitor.accept(this); - - if (_reference != null) { - _reference.visit(visitor); - } - - for (Parameter db : getParameters()) { - db.visit(visitor); - } - } -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/Interaction.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/Interaction.java deleted file mode 100644 index bb012d92e..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/Interaction.java +++ /dev/null @@ -1,234 +0,0 @@ -/* - * Copyright 2009 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.model; - -import java.util.Collection; - -/** - * This class represents an interaction: the communication - * of a message from one role to another, or several others. - * - */ -public class Interaction extends Activity { - - private MessageSignature _messageSignature=null; - private Role _fromRole=null; - private java.util.List _toRoles= - new ContainmentList(this, Role.class); - - /** - * The default constructor. - */ - public Interaction() { - } - - /** - * The copy constructor. - * - * @param i The interaction to copy - */ - public Interaction(Interaction i) { - super(i); - - if (i._messageSignature != null) { - _messageSignature = new MessageSignature(i._messageSignature); - } - if (i._fromRole != null) { - _fromRole = new Role(i._fromRole); - } - for (Role r : i._toRoles) { - _toRoles.add(new Role(r)); - } - } - - /** - * This constructor initializes the 'from' role and message - * signature. - * - * @param fromRole The 'from' role - * @param sig The message signature - */ - public Interaction(Role fromRole, MessageSignature sig) { - _fromRole = fromRole; - _messageSignature = sig; - } - - /** - * This method initializes the 'from' and 'to' roles, and - * message signature. - * - * @param fromRole The 'from' role - * @param toRole The 'to' role - * @param sig The message signature - */ - public Interaction(Role fromRole, Role toRole, MessageSignature sig) { - this(fromRole, sig); - if (toRole != null) { - _toRoles.add(toRole); - } - } - - /** - * This method initializes the 'from' and 'to' roles, and - * message signature. - * - * @param fromRole The 'from' role - * @param toRoles The 'to' roles - * @param sig The message signature - */ - public Interaction(Role fromRole, Collection toRoles, MessageSignature sig) { - this(fromRole, sig); - _toRoles.addAll(toRoles); - } - - /** - * This method returns the message signature. - * - * @return The message signature - */ - public MessageSignature getMessageSignature() { - return (_messageSignature); - } - - /** - * This method sets the message signature. - * - * @param signature The message signature - */ - public void setMessageSignature(MessageSignature signature) { - - if (_messageSignature != null) { - _messageSignature.setParent(null); - } - - _messageSignature = signature; - - if (_messageSignature != null) { - _messageSignature.setParent(this); - } - } - - /** - * This method returns the optional 'from' role. - * - * @return The optional 'from' role - */ - public Role getFromRole() { - return (_fromRole); - } - - /** - * This method sets the optional 'from' role. - * - * @param part The optional 'from' role - */ - public void setFromRole(Role part) { - _fromRole = part; - } - - /** - * This method returns the optional (one or many) 'to' roles. - * - * @return The optional 'to' roles - */ - public java.util.List getToRoles() { - return (_toRoles); - } - - @Override - public String toString() { - StringBuffer ret=new StringBuffer(); - - if (getMessageSignature() != null) { - ret.append(getMessageSignature()); - ret.append(" "); - } - - if (getFromRole() != null) { - ret.append(getFromRole()); - ret.append("->"); - - for (int i=0; i < getToRoles().size(); i++) { - if (i > 0) { - ret.append(","); - } - ret.append(getToRoles().get(i)); - } - } else { - ret.append("->"); - - for (int i=0; i < getToRoles().size(); i++) { - if (i > 0) { - ret.append(","); - } - ret.append(getToRoles().get(i)); - } - } - - return (ret.toString()); - } - - /** - * This method visits the model object using the supplied - * visitor. - * - * @param visitor The visitor - */ - public void visit(Visitor visitor) { - visitor.accept(this); - - if (getMessageSignature() != null) { - getMessageSignature().visit(visitor); - } - - if (getFromRole() != null) { - getFromRole().visit(visitor); - } - - for (Role r : getToRoles()) { - r.visit(visitor); - } - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - - Interaction that = (Interaction) o; - - return !(_fromRole != null - ? !_fromRole.equals(that._fromRole) - : that._fromRole != null) - && !(_messageSignature != null - ? !_messageSignature.equals(that._messageSignature) - : that._messageSignature != null) - && _toRoles.equals(that._toRoles); - } - - @Override - public int hashCode() { - int result = _messageSignature != null ? _messageSignature.hashCode() : 0; - result = 31 * result + (_fromRole != null ? _fromRole.hashCode() : 0); - result = 31 * result + (_toRoles != null ? _toRoles.hashCode() : 0); - return result; - } - -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/Interrupt.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/Interrupt.java deleted file mode 100644 index 8da07cea9..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/Interrupt.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright 2009 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.model; - - -/** - * This class represents a group of activities within - * an interrupt block associated with a global escape. - * - */ -public class Interrupt extends ModelObject { - - private Block _contents=null; - - /** - * This method returns the block of activities associated - * with the definition. - * - * @return The block of activities - */ - public Block getBlock() { - - if (_contents == null) { - _contents = new Block(); - _contents.setParent(this); - } - - return (_contents); - } - - /** - * This method sets the block of activities associated - * with the definition. - * - * @param block The block of activities - */ - public void setBlock(Block block) { - if (_contents != null) { - _contents.setParent(null); - } - - _contents = block; - - if (_contents != null) { - _contents.setParent(this); - } - } - - /** - * This method visits the model object using the supplied - * visitor. - * - * @param visitor The visitor - */ - public void visit(Visitor visitor) { - - if (visitor.start(this)) { - - getBlock().visit(visitor); - } - - visitor.end(this); - } - -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/Introduces.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/Introduces.java deleted file mode 100644 index 8b1736579..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/Introduces.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright 2009 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.model; - -/** - * This class represents the list of roles introduced by - * an existing role within a Scribble definition. - */ -public class Introduces extends Activity { - - private Role _introducer=null; - private java.util.List _roles= - new ContainmentList(this, Role.class); - - /** - * The default constructor. - */ - public Introduces() { - } - - /** - * The copy constructor. - * - * @param i The introduces construct to copy - */ - public Introduces(Introduces i) { - super(i); - - _introducer = new Role(i.getIntroducer()); - - for (Role r : i.getIntroducedRoles()) { - getIntroducedRoles().add(new Role(r)); - } - } - - /** - * This method returns the introducing role. - * - * @return The introducer - */ - public Role getIntroducer() { - return (_introducer); - } - - /** - * This method sets the introducing role. - * - * @param role The introducer - */ - public void setIntroducer(Role role) { - _introducer = role; - } - - /** - * This method returns the list of roles. - * - * @return The list of roles - */ - public java.util.List getIntroducedRoles() { - return (_roles); - } - - /** - * This method returns the role associated with - * the supplied name. - * - * @param name The role name - * @return The role, or null if not found - */ - public Role getIntroducedRole(String name) { - Role ret=null; - - for (int i=0; ret == null - && i < _roles.size(); i++) { - if (_roles.get(i).getName().equals(name)) { - ret = _roles.get(i); - } - } - - return (ret); - } - - /** - * This method visits the model object using the supplied - * visitor. - * - * @param visitor The visitor - */ - public void visit(Visitor visitor) { - visitor.accept(this); - } - - @Override - public String toString() { - return (getIntroducer()+" introduces "+getIntroducedRoles()+";"); - } -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/MessageSignature.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/MessageSignature.java deleted file mode 100644 index 7117e9695..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/MessageSignature.java +++ /dev/null @@ -1,173 +0,0 @@ -/* - * Copyright 2009 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.model; - -import java.util.Collection; - -/** - * This class represents a message signature. - * Message signatures can be either a simple signature with - * a unique TypeReference, or an operation name with several - * TypeReferences as arguments. - */ -public class MessageSignature extends ModelObject { - - private String _operation=null; - private java.util.List _typeReferences= - new ContainmentList(this, TypeReference.class); - - /** - * The default constructor. - */ - public MessageSignature() { - } - - /** - * No-operation constructor: only one TypeReference is allowed. - * @param typeRef The TypeReference for this simply-typed message. - */ - public MessageSignature(TypeReference typeRef) { - _typeReferences.add(typeRef); - } - - /** - * Constructor for MessageSignatures that comprise an operation. - * @param operation The operation name. - * @param typeRefs The arguments for the operation. - */ - public MessageSignature(String operation, Collection typeRefs) { - _operation = operation; - _typeReferences.addAll(typeRefs); - } - - /** - * The copy constructor. - * - * @param msig The message signature - */ - public MessageSignature(MessageSignature msig) { - super(msig); - - _operation = msig.getOperation(); - - for (TypeReference tref : msig.getTypeReferences()) { - _typeReferences.add(new TypeReference(tref)); - } - } - - /** - * This method returns the optional operation. - * - * @return The optional operation - */ - public String getOperation() { - return (_operation); - } - - /** - * This method sets the operation. - * - * @param operation The operation - */ - public void setOperation(String operation) { - _operation = operation; - } - - // TODO: Need to think about actual type for this list - // See how JDT DOM handles local details (e.g. short - // name) versus fully qualified name identifying the - // actual type. Issue also is if the model can be - // updated, what happens to the fully qualified name? - /** - * This method returns the list of type references. If - * no operation is defined, then only one type reference - * should be defined. - * - * @return The list of type references - */ - public java.util.List getTypeReferences() { - return (_typeReferences); - } - - @Override - public int hashCode() { - int result = 13; - result = 31 * result + _typeReferences.hashCode(); - result = 31 * result + (_operation == null ? 0 : _operation.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - boolean ret=false; - - if (obj instanceof MessageSignature) { - MessageSignature other=(MessageSignature) obj; - - if (other.getTypeReferences().size() == getTypeReferences().size()) { - if (other._operation != null && _operation != null) { - ret = other._operation.equals(_operation); - } else if (other._operation == null && _operation == null) { - ret = true; - } - - for (int i=0; ret && i < getTypeReferences().size(); i++) { - ret = getTypeReferences().get(i).equals(other.getTypeReferences().get(i)); - } - } - } - - return (ret); - } - - @Override - public String toString() { - String ret=""; - - if (getOperation() != null - && getOperation().trim().length() > 0) { - ret += getOperation() + "("; - } - - for (int i=0; i < _typeReferences.size(); i++) { - if (i > 0) { - ret += ","; - } - ret += _typeReferences.get(i).getName(); - } - - if (getOperation() != null - && getOperation().trim().length() > 0) { - ret += ")"; - } - - if (ret.equals("")) { - ret = ""; - } - - return (ret); - } - - /** - * This method visits the model object using the supplied - * visitor. - * - * @param visitor The visitor - */ - public void visit(Visitor visitor) { - } - -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/ModelObject.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/ModelObject.java deleted file mode 100644 index 54b6954ed..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/ModelObject.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Copyright 2009 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.model; - -import org.scribble.common.model.Annotation; - -/** - * This is the generic object from which all Scribble model objects - * are derived. - */ -public abstract class ModelObject { - - private ModelObject _parent=null; - private java.util.List _annotations= - new java.util.Vector(); - private java.util.Map _properties= - new java.util.HashMap(); - - /** - * This is the default constructor for the model object. - */ - public ModelObject() { - } - - /** - * This is the copy constructor. - * - * @param obj The object to copy - */ - public ModelObject(ModelObject obj) { - _properties.putAll(obj.getProperties()); - _annotations.addAll(obj.getAnnotations()); - } - - /** - * This method returns the parent of this - * model object. - * - * @return The parent, or null if top model - * object - */ - public ModelObject getParent() { - return (_parent); - } - - /** - * This method sets the parent model object. - * - * @param parent The parent - */ - public void setParent(ModelObject parent) { - _parent = parent; - } - - /** - * This method establishes the necessary information to - * indicate that the current model object is derived - * from the supplied source model object. - * - * @param modelObj The source model object - */ - public void derivedFrom(ModelObject modelObj) { - if (modelObj != null) { - _properties = new java.util.HashMap(modelObj.getProperties()); - _annotations = new java.util.Vector(modelObj.getAnnotations()); - } - } - - /** - * This method returns the list of annotations associated with the - * model object. - * - * @return The list of annotations - */ - public java.util.List getAnnotations() { - return (_annotations); - } - - /** - * This method returns the properties associated - * with this model object. - * - * @return The properties - */ - public java.util.Map getProperties() { - return (_properties); - } - - /** - * This method returns the protocol model in which this - * object is contained. - * - * @return The protocol model, or null if not found - */ - public ProtocolModel getModel() { - ProtocolModel ret=null; - ModelObject cur=this; - - while (ret == null && cur != null) { - - if (cur instanceof ProtocolModel) { - ret = (ProtocolModel) cur; - } else { - cur = cur.getParent(); - } - } - - return (ret); - } - - /** - * This method visits the model object using the supplied - * visitor. - * - * @param visitor The visitor - */ - public abstract void visit(Visitor visitor); -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/ModelProperties.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/ModelProperties.java deleted file mode 100644 index d0284f70b..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/ModelProperties.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright 2009 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.model; - -/** - * This interface provides the definitions for the properties - * associated with objects in the model. - */ -public interface ModelProperties { - - /** - * This construct defines the start location in a textual description of - * a scribble construct. - */ - public static final String START_LOCATION="scribble.start.location"; - - /** - * This construct defines the end location in a textual description of - * a scribble construct. - */ - public static final String END_LOCATION="scribble.end.location"; - - /** - * This construct defines the URI for locating the source component. - */ - public static final String URI="scribble.uri"; - -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/OnMessage.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/OnMessage.java deleted file mode 100644 index 2437d4a69..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/OnMessage.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Copyright 2009-11 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.model; - -/** - * This class represents a possible path of a directed choice, triggered - * by a specified message signature. - * - */ -public class OnMessage extends ModelObject { - - private MessageSignature _messageSignature=null; - private Block _block=new Block(); - - /** - * This is the default constructor. - * - */ - public OnMessage() { - _block.setParent(this); - } - - /** - * This method returns the message signature. - * - * @return The message signature - */ - public MessageSignature getMessageSignature() { - return (_messageSignature); - } - - /** - * This method sets the message signature. - * - * @param signature The message signature - */ - public void setMessageSignature(MessageSignature signature) { - - if (_messageSignature != null) { - _messageSignature.setParent(null); - } - - _messageSignature = signature; - - if (_messageSignature != null) { - _messageSignature.setParent(this); - } - } - - /** - * This method returns the activities. - * - * @return The block of activities - */ - public Block getBlock() { - return (_block); - } - - /** - * This method sets the block. - * - * @param block The block - */ - public void setBlock(Block block) { - if (_block != null) { - _block.setParent(null); - } - - _block = block; - - if (_block != null) { - _block.setParent(this); - } - } - - /** - * This method visits the model object using the supplied - * visitor. - * - * @param visitor The visitor - */ - public void visit(Visitor visitor) { - if (visitor.start(this)) { - - if (getBlock() != null) { - getBlock().visit(visitor); - } - } - - visitor.end(this); - } -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/Parallel.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/Parallel.java deleted file mode 100644 index 47a9de6bd..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/Parallel.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright 2009 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.model; - -/** - * This class represents the Parallel construct with - * two or more concurrent paths. - * - */ -public class Parallel extends Activity { - - private java.util.List _blocks=new ContainmentList(this, Block.class); - - /** - * This is the default constructor. - * - */ - public Parallel() { - } - - /** - * This method returns the list of concurrent - * activity blocks that comprise the multi-path construct. - * - * @return The list of concurrent paths - */ - public java.util.List getPaths() { - return (_blocks); - } - - /** - * This method visits the model object using the supplied - * visitor. - * - * @param visitor The visitor - */ - public void visit(Visitor visitor) { - if (visitor.start(this)) { - - for (Block b : getPaths()) { - b.visit(visitor); - } - } - - visitor.end(this); - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - - Parallel that = (Parallel) o; - - return _blocks.equals(that._blocks); - } - - @Override - public int hashCode() { - int result = _blocks.hashCode(); - return result; - } - - @Override - public String toString() { - String result = "parallel "; - for (Block b : _blocks) { - if (_blocks.indexOf(b) > 0) { - result += "and "; - } - result += b + "\n"; - } - return result; - } -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/Parameter.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/Parameter.java deleted file mode 100644 index 6a4229c68..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/Parameter.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright 2009 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.model; - -/** - * This class represents the binding between a declaration and - * the name of a declaration in a composed definition. - */ -public class Parameter extends ModelObject { - - private String _localName=null; - - /** - * The default constructor. - */ - public Parameter() { - } - - /** - * This constructor initializes the declaration (local name) and bound - * name. - * - * @param localName The local name - */ - public Parameter(String localName) { - _localName = localName; - } - - /** - * This is the copy constructor. - * - * @param p The parameter to copy - */ - public Parameter(Parameter p) { - super(p); - _localName = p._localName; - } - - /** - * This method sets the local name. - * - * @param localName The local name - */ - public void setName(String localName) { - _localName = localName; - } - - /** - * This method returns the local name. - * - * @return The local name - */ - public String getName() { - return (_localName); - } - - /** - * This method visits the model object using the supplied - * visitor. - * - * @param visitor The visitor - */ - public void visit(Visitor visitor) { - } -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/ParameterDefinition.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/ParameterDefinition.java deleted file mode 100644 index 50f0d1e65..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/ParameterDefinition.java +++ /dev/null @@ -1,160 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.model; - -/** - * This class represents a parameter. - * - */ -public class ParameterDefinition extends ModelObject { - - private String _name=null; - private TypeReference _type=null; - - /** - * This is the default constructor. - */ - public ParameterDefinition() { - } - - /** - * This constructor initializes the parameter as representing - * a role with the supplied name. - * - * @param name The name - */ - public ParameterDefinition(String name) { - _name = name; - } - - /** - * This method returns the name of the parameter. - * - * @return The name - */ - public String getName() { - return (_name); - } - - /** - * This method sets the name of the parameter. - * - * @param name The name - */ - public void setName(String name) { - _name = name; - } - - /** - * This method returns the type of the parameter. If - * the type is null, then it means the parameter - * name represents a role. - * - * @return The type - */ - public TypeReference getType() { - return (_type); - } - - /** - * This method sets the type of the parameter. - * - * @param type The type - */ - public void setType(TypeReference type) { - _type = type; - } - - /** - * This method determines whether the parameter represents a role. - * - * @return Whether the parameter represents a role - */ - public boolean isRole() { - return (_type == null); - } - - /** - * This method returns the role associated with the parameter, - * if the parameter represents a role, otherwise null. - * - * @return The role, or null if parameter does not represent a role - */ - public Role getRole() { - Role ret=null; - - if (isRole() && getName() != null) { - ret = new Role(getName()); - ret.setParent(this); - } - - return (ret); - } - - @Override - public boolean equals(Object obj) { - boolean ret=false; - - if (obj instanceof ParameterDefinition) { - ParameterDefinition other=(ParameterDefinition) obj; - - ret = true; - - if (other.getName() == null || !other.getName().equals(_name)) { - ret = false; - } else if (other.getType() == null) { - if (getType() != null) { - ret = false; - } - } else if (getType() == null || !other.getType().equals(getType())) { - ret = false; - } - } - - return (ret); - } - - @Override - public int hashCode() { - int ret=super.hashCode(); - - if (_name != null) { - ret = _name.hashCode(); - } - - return (ret); - } - - @Override - public String toString() { - String ret=getName(); - - if (ret == null) { - ret = ""; - } - - return (ret); - } - - /** - * This method visits the model object using the supplied - * visitor. - * - * @param visitor The visitor - */ - public void visit(Visitor visitor) { - } -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/Protocol.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/Protocol.java deleted file mode 100644 index 006a7eb89..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/Protocol.java +++ /dev/null @@ -1,290 +0,0 @@ -/* - * Copyright 2009 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.model; - -/** - * This class represents the protocol notation. - */ -public class Protocol extends ModelObject { - - private String _name=null; - private Role _locatedRole=null; - private Block _block=null; - private java.util.List _nestedProtocols= - new ContainmentList(this, Protocol.class); - private java.util.List _parameterDefs= - new ContainmentList(this, ParameterDefinition.class); - - /** - * The default constructor. - */ - public Protocol() { - } - - /** - * This method returns the name. - * - * @return The name - */ - public String getName() { - return (_name); - } - - /** - * This method sets the name. - * - * @param name The name - */ - public void setName(String name) { - _name = name; - } - - /** - * This method returns the located role. This - * field is set when the protocol represents a local - * model. - * - * @return The located role - */ - public Role getLocatedRole() { - return (_locatedRole); - } - - /** - * This method sets the located role. This - * field is set when the protocol represents a local - * model. - * - * @param role The located role - */ - public void setLocatedRole(Role role) { - - if (_locatedRole != null) { - _locatedRole.setParent(null); - } - - _locatedRole = role; - - if (_locatedRole != null) { - _locatedRole.setParent(this); - } - } - - /** - * This method returns the parameters associated with - * the protocol. - * - * @return The parameter definitions - */ - public java.util.List getParameterDefinitions() { - return (_parameterDefs); - } - - /** - * This method returns the parameter definition associated with the - * supplied name. - * - * @param name The name - * @return The parameter definition, or null if not found - */ - public ParameterDefinition getParameterDefinition(String name) { - ParameterDefinition ret=null; - - for (ParameterDefinition pd : getParameterDefinitions()) { - if (pd.getName().equals(name)) { - ret = pd; - break; - } - } - - return (ret); - } - - /** - * This method returns the block of activities associated - * with the definition. - * - * @return The block of activities - */ - public Block getBlock() { - - if (_block == null) { - _block = new Block(); - _block.setParent(this); - } - - return (_block); - } - - /** - * This method sets the block of activities associated - * with the definition. - * - * @param block The block of activities - */ - public void setBlock(Block block) { - if (_block != null) { - _block.setParent(null); - } - - _block = block; - - if (_block != null) { - _block.setParent(this); - } - } - - /** - * This method returns the list of nested protocols. - * - * @return The nested protocols - */ - public java.util.List getNestedProtocols() { - return (_nestedProtocols); - } - - /** - * This method returns the model in which this definition - * is contained. - * - * @return The model, or null if not contained within - * a model - */ - public ProtocolModel getModel() { - ProtocolModel ret=null; - ModelObject cur=this; - - while (ret == null && cur != null) { - if (cur instanceof ProtocolModel) { - ret = (ProtocolModel) cur; - } else { - cur = cur.getParent(); - } - } - - return (ret); - } - - /** - * This method returns the protocol in which this - * activity is contained. - * - * @return The protocol, or null if not found - */ - public Protocol getEnclosingProtocol() { - return (this); - } - - /** - * This method returns the top level protocol. - * - * @return The top level protocol - */ - public Protocol getTopLevelProtocol() { - Protocol ret=this; - - if (getParent() instanceof Protocol) { - ret = ((Protocol)getParent()).getTopLevelProtocol(); - } - - return (ret); - } - - /** - * This method returns the nested-protocol associated - * with the supplied name. - * - * @param name The name - * @return The nested-protocol for the supplied name, - * or null if not found - */ - public Protocol getNestedProtocol(String name) { - - for (Protocol protocol : _nestedProtocols) { - if (protocol.getName().equals(name)) { - return (protocol); - } - } - - return (null); - } - - /** - * This method returns the list of roles defined within - * the protocol definition. - * - * @return The list of roles - */ - public java.util.List getRoles() { - final java.util.List ret=new java.util.Vector(); - - for (ParameterDefinition p : getParameterDefinitions()) { - if (p.isRole()) { - ret.add(p.getRole()); - } - } - - visit(new DefaultVisitor() { - - public boolean start(Protocol elem) { - return (Protocol.this == elem); - } - - public void accept(Introduces elem) { - ret.addAll(elem.getIntroducedRoles()); - } - - }); - - return (ret); - } - - /** - * This method visits the model object using the supplied - * visitor. - * - * @param visitor The visitor - */ - public void visit(Visitor visitor) { - - if (visitor.start(this)) { - - if (getBlock() != null) { - getBlock().visit(visitor); - } - - for (Protocol p : getNestedProtocols()) { - p.visit(visitor); - } - } - - visitor.end(this); - } - - public String toString() { - String ret="protocol "+getName()+" ( "; - - for (ParameterDefinition pd : getParameterDefinitions()) { - ret += (pd.isRole() ? "role" : pd.getType())+" "+pd.getName()+" "; - } - - ret += ")\r\n"; - - ret += getBlock(); - - return(ret); - } -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/ProtocolImport.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/ProtocolImport.java deleted file mode 100644 index 53dc4791f..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/ProtocolImport.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Copyright 2009 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.model; - -/** - * This class represents an imported protocol. - * - */ -public class ProtocolImport extends ModelObject { - - private String _location=null; - private String _name=null; - - /** - * The default constructor. - */ - public ProtocolImport() { - } - - /** - * The copy constructor. - * - * @param copy The copy - */ - public ProtocolImport(ProtocolImport copy) { - super(copy); - _location = copy.getLocation(); - _name = copy.getName(); - } - - /** - * This method returns the name of the - * type being imported. - * - * @return The name - */ - public String getName() { - return (_name); - } - - /** - * This method sets the name of the - * type being imported. - * - * @param name The name - */ - public void setName(String name) { - _name = name; - } - - /** - * This method returns the location of the schema. - * - * @return The location - */ - public String getLocation() { - return (_location); - } - - /** - * This method sets the location of the schema. - * - * @param location The location - */ - public void setLocation(String location) { - _location = location; - } - - /** - * This method visits the model object using the supplied - * visitor. - * - * @param visitor The visitor - */ - public void visit(Visitor visitor) { - visitor.accept(this); - } - - @Override - public String toString() { - String ret=getName(); - - if (ret == null) { - ret = ""; - } - - return (ret); - } -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/ProtocolImportList.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/ProtocolImportList.java deleted file mode 100644 index 62d620a91..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/ProtocolImportList.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright 2009 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.model; - -/** - * This class represents an import definition associated with a model. - * - */ -public class ProtocolImportList extends ImportList { - - private java.util.List _protocolImports= - new ContainmentList(this, ProtocolImport.class); - - /** - * The default constructor. - */ - public ProtocolImportList() { - } - - /** - * The copy constructor. - * - * @param copy The copy - */ - public ProtocolImportList(ProtocolImportList copy) { - super(copy); - for (ProtocolImport pi : copy.getProtocolImports()) { - _protocolImports.add(new ProtocolImport(pi)); - } - } - - /** - * This method returns the list of imported protocols. - * - * @return The list of imported protocols - */ - public java.util.List getProtocolImports() { - return (_protocolImports); - } - - /** - * This method returns the imported protocol associated with - * the supplied name. - * - * @param name The protocol name - * @return The protocol, or null if not found - */ - public ProtocolImport getProtocolImport(String name) { - ProtocolImport ret=null; - - for (int i=0; ret == null - && i < _protocolImports.size(); i++) { - if (_protocolImports.get(i).getName().equals(name)) { - ret = _protocolImports.get(i); - } - } - - return (ret); - } - - /** - * This method visits the model object using the supplied - * visitor. - * - * @param visitor The visitor - */ - public void visit(Visitor visitor) { - visitor.accept(this); - - for (ProtocolImport pi : getProtocolImports()) { - pi.visit(visitor); - } - } -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/ProtocolModel.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/ProtocolModel.java deleted file mode 100644 index d523fb91c..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/ProtocolModel.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Copyright 2009 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.model; - -/** - * This class represents the base class for models associated with - * specific notations. The details associated with the notation are - * contained within derived classes. - * - */ -public class ProtocolModel extends ModelObject { - - private Protocol _definition=null; - private java.util.List _imports= - new ContainmentList(this, ImportList.class); - - /** - * The default constructor for the model. - */ - public ProtocolModel() { - } - - /** - * This method returns the list of import definitions. - * - * @return The import definitions - */ - public java.util.List getImports() { - return (_imports); - } - - /** - * This method returns the definition associated with - * this model. - * - * @return The definition - */ - public Protocol getProtocol() { - return (_definition); - } - - /** - * This method set the definition associated with the - * model. - * - * @param defn The definition - */ - public void setProtocol(Protocol defn) { - if (_definition != null) { - _definition.setParent(null); - } - - _definition = defn; - - if (_definition != null) { - _definition.setParent(this); - } - } - - /** - * This method determines whether the model is located. - * - * @return Whether the model is located - */ - public boolean isLocated() { - boolean ret=false; - - if (getProtocol() != null) { - ret = (getProtocol().getLocatedRole() != null); - } - - return (ret); - } - - /** - * This method returns the distinct list of roles defined - * in the protocol and its nested-protocols. - * - * @return The list of projectable roles - */ - public java.util.List getRoles() { - final java.util.List ret=new java.util.Vector(); - - visit(new DefaultVisitor() { - - public boolean start(Protocol elem) { - - for (Role r : elem.getRoles()) { - if (!ret.contains(r)) { - ret.add(r); - } - } - - return (true); - } - }); - - return (ret); - } - - /** - * This method visits the model object using the supplied - * visitor. - * - * @param visitor The visitor - */ - public void visit(Visitor visitor) { - - for (ImportList imp : getImports()) { - imp.visit(visitor); - } - - if (getProtocol() != null) { - getProtocol().visit(visitor); - } - } -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/ProtocolReference.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/ProtocolReference.java deleted file mode 100644 index 0fe104f89..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/ProtocolReference.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright 2009 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.model; - -/** - * This class represents a protocol reference. - */ -public class ProtocolReference extends ModelObject { - - private String _name=null; - private Role _role=null; - - /** - * This is the default constructor for the protocol reference. - */ - public ProtocolReference() { - } - - /** - * This is the constructor for the protocol reference. - * - * @param name The name - */ - public ProtocolReference(String name) { - setName(name); - } - - /** - * This is the copy constructor for the model reference. - * - * @param ref The reference to copy - */ - public ProtocolReference(ProtocolReference ref) { - super(ref); - - _name = ref._name; - _role = ref._role; - } - - /** - * This method returns the name associated with the - * model reference. - * - * @return The name - */ - public String getName() { - return (_name); - } - - /** - * This method sets the name associated with the - * model reference. - * - * @param name The name - */ - public void setName(String name) { - _name = name; - } - - /** - * This method sets the located role. - * - * @param role The role - */ - public void setRole(Role role) { - _role = role; - } - - /** - * This method returns the located role. - * - * @return The role - */ - public Role getRole() { - return (_role); - } - - /** - * This method visits the model object using the supplied - * visitor. - * - * @param visitor The visitor - */ - public void visit(Visitor visitor) { - } -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/RecBlock.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/RecBlock.java deleted file mode 100644 index 2e4969fdc..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/RecBlock.java +++ /dev/null @@ -1,125 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.model; - -/** - * This class represents the Recur construct. - * - */ -public class RecBlock extends Activity { - - private String _label=null; - private Block _block=new Block(); - - /** - * This is the default constructor. - * - */ - public RecBlock() { - _block.setParent(this); - } - - /** - * This method returns the label associated with the labelled block construct. - * - * @return The label - */ - public String getLabel() { - return (_label); - } - - /** - * This method sets the label associated with the labelled block construct. - * - * @param label The label - */ - public void setLabel(String label) { - _label = label; - } - - /** - * This method returns the activities. - * - * @return The block of activities - */ - public Block getBlock() { - return (_block); - } - - /** - * This method sets the block. - * - * @param block The block - */ - public void setBlock(Block block) { - if (_block != null) { - _block.setParent(null); - } - - _block = block; - - if (_block != null) { - _block.setParent(this); - } - } - - /** - * This method visits the model object using the supplied - * visitor. - * - * @param visitor The visitor - */ - public void visit(Visitor visitor) { - if (visitor.start(this)) { - - if (getBlock() != null) { - getBlock().visit(visitor); - } - } - - visitor.end(this); - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - - RecBlock that = (RecBlock) o; - - return !(_label != null - ? !_label.equals(that._label) - : that._label != null) - && !(_block != null - ? !_block.equals(that._block) - : that._block != null); - } - - @Override - public int hashCode() { - int result = _label != null ? _label.hashCode() : 0; - return 31 * result + (_block != null ? _block.hashCode() : 0); - } - - @Override - public String toString() { - return "rec "+_label+" "+_block; - } -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/Recursion.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/Recursion.java deleted file mode 100644 index 5452d897a..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/Recursion.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright 2009 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.model; - -/** - * This class represents the Raise construct. - * - */ -public class Recursion extends Activity { - - private String _label=null; - - /** - * This is the default constructor. - * - */ - public Recursion() { - } - - /** - * This is the copy constructor. - * - * @param copy The recursion to copy - */ - public Recursion(Recursion copy) { - super(copy); - _label = copy.getLabel(); - } - - /** - * This method returns the label associated with the recursion construct. - * - * @return The label - */ - public String getLabel() { - return (_label); - } - - /** - * This method sets the label associated with the recursion construct. - * - * @param label The label - */ - public void setLabel(String label) { - _label = label; - } - - /** - * This method visits the model object using the supplied - * visitor. - * - * @param visitor The visitor - */ - public void visit(Visitor visitor) { - visitor.accept(this); - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - - Recursion that = (Recursion) o; - - return !(_label != null - ? !_label.equals(that._label) - : that._label != null); - } - - @Override - public int hashCode() { - return _label != null ? _label.hashCode() : 0; - } - - @Override - public String toString() { - return '#' + _label; - } -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/Repeat.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/Repeat.java deleted file mode 100644 index 88e2e731a..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/Repeat.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright 2009 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.model; - -/** - * This class represents the Repeat construct. - * - */ -public class Repeat extends Activity { - - private Block _block=new Block(); - private java.util.List _roles=new java.util.Vector(); - - /** - * This is the default constructor. - * - */ - public Repeat() { - _block.setParent(this); - } - - /** - * This method returns the list of roles at which - * the repeat decision is located. - * - * @return The list of roles - */ - public java.util.List getRoles() { - return (_roles); - } - - /** - * This method returns the activities. - * - * @return The block of activities - */ - public Block getBlock() { - return (_block); - } - - /** - * This method sets the block. - * - * @param block The block - */ - public void setBlock(Block block) { - if (_block != null) { - _block.setParent(null); - } - - _block = block; - - if (_block != null) { - _block.setParent(this); - } - } - - /** - * This method visits the model object using the supplied - * visitor. - * - * @param visitor The visitor - */ - public void visit(Visitor visitor) { - if (visitor.start(this)) { - - if (getBlock() != null) { - getBlock().visit(visitor); - } - } - - visitor.end(this); - } -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/Role.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/Role.java deleted file mode 100644 index 356a3f297..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/Role.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Copyright 2009 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.model; - -/** - * This class represents a role. - * - */ -public class Role extends ModelObject { - - private String _name=null; - - /** - * This is the default constructor. - */ - public Role() { - } - - /** - * This is the copy constructor. - * - * @param role The role - */ - public Role(Role role) { - super(role); - _name = role.getName(); - } - - /** - * This constructor initializes the role with a name. - * - * @param roleName The role name - */ - public Role(String roleName) { - _name = roleName; - } - - /** - * This method returns the name of the role. - * - * @return The name - */ - public String getName() { - return (_name); - } - - /** - * This method sets the name of the role. - * - * @param name The name - */ - public void setName(String name) { - _name = name; - } - - @Override - public boolean equals(Object obj) { - boolean ret=false; - - if (obj instanceof Role) { - Role other=(Role)obj; - - if (other.getName() != null && other.getName().equals(_name)) { - ret = true; - } - } - - return (ret); - } - - @Override - public int hashCode() { - int ret=super.hashCode(); - - if (_name != null) { - ret = _name.hashCode(); - } - - return (ret); - } - - @Override - public String toString() { - String ret=getName(); - - if (ret == null) { - ret = ""; - } - - return (ret); - } - - /** - * This method visits the model object using the supplied - * visitor. - * - * @param visitor The visitor - */ - public void visit(Visitor visitor) { - } -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/Run.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/Run.java deleted file mode 100644 index 3566475fe..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/Run.java +++ /dev/null @@ -1,142 +0,0 @@ -/* - * Copyright 2009 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.model; - -/** - * This class represents the Run construct. - * - */ -public class Run extends Activity { - - private ProtocolReference _reference=null; - private Role _fromRole=null; - private java.util.List _parameters=new java.util.Vector(); - - /** - * This is the default constructor. - * - */ - public Run() { - } - - /** - * This is the copy constructor. - * - * @param copy The copy - */ - public Run(Run copy) { - super(copy); - _reference = new ProtocolReference(copy.getProtocolReference()); - - if (copy.getFromRole() != null) { - _fromRole = new Role(copy.getFromRole()); - } - - for (Parameter p : copy.getParameters()) { - _parameters.add(new Parameter(p)); - } - } - - /** - * This method returns the optional 'from' role. - * - * @return The optional 'from' role - */ - public Role getFromRole() { - return (_fromRole); - } - - /** - * This method sets the optional 'from' role. - * - * @param part The optional 'from' role - */ - public void setFromRole(Role part) { - _fromRole = part; - } - - /** - * This method returns the parameters for the - * composition construct. - * - * @return The list of parameters - */ - public java.util.List getParameters() { - return (_parameters); - } - - /** - * This method returns the parameter associated - * with the supplied declaration. - * - * @param declName The declaration name - * @return The parameter, or null if not found - */ - public Parameter getParameter(String declName) { - Parameter ret=null; - - java.util.Iterator iter=getParameters().iterator(); - - while (ret == null && iter.hasNext()) { - ret = iter.next(); - - if (!ret.getName().equals(declName)) { - ret = null; - } - } - - return (ret); - } - - /** - * This method returns the protocol reference associated - * with the run construct. - * - * @return The protocol reference, or null if not defined - */ - public ProtocolReference getProtocolReference() { - return (_reference); - } - - /** - * This method sets the protocol reference associated - * with the run construct. - * - * @param ref The protocol reference - */ - public void setProtocolReference(ProtocolReference ref) { - - if (_reference != null) { - _reference.setParent(null); - } - - _reference = ref; - - if (_reference != null) { - _reference.setParent(this); - } - } - - /** - * This method visits the model object using the supplied - * visitor. - * - * @param visitor The visitor - */ - public void visit(Visitor visitor) { - visitor.accept(this); - } -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/TypeImport.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/TypeImport.java deleted file mode 100644 index 8d6dac371..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/TypeImport.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Copyright 2009 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.model; - -/** - * This class represents an imported type associated with a model. - * - */ -public class TypeImport extends ModelObject { - - private String _name=null; - private DataType _dataType=null; - - /** - * The default constructor. - */ - public TypeImport() { - } - - /** - * The copy constructor. - * - * @param copy The copy - */ - public TypeImport(TypeImport copy) { - super(copy); - _name = copy.getName(); - if (copy.getDataType() != null) { - _dataType = new DataType(copy.getDataType()); - } - } - - /** - * This method returns the name of the - * type being imported. - * - * @return The name - */ - public String getName() { - return (_name); - } - - /** - * This method sets the name of the - * type being imported. - * - * @param name The name - */ - public void setName(String name) { - _name = name; - } - - /** - * This method returns the data type. - * - * @return The data type - */ - public DataType getDataType() { - return (_dataType); - } - - /** - * This method sets the data type. - * - * @param dataType The data type - */ - public void setDataType(DataType dataType) { - _dataType = dataType; - } - - /** - * This method visits the model object using the supplied - * visitor. - * - * @param visitor The visitor - */ - public void visit(Visitor visitor) { - visitor.accept(this); - } - - @Override - public String toString() { - String ret=getName(); - - if (ret == null) { - ret = ""; - } - - return (ret); - } -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/TypeImportList.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/TypeImportList.java deleted file mode 100644 index b091ee849..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/TypeImportList.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Copyright 2009 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.model; - -/** - * This class represents an import definition associated with a model. - * - */ -public class TypeImportList extends ImportList { - - private String _format=null; - private String _location=null; - private java.util.List _types= - new ContainmentList(this, TypeImport.class); - - /** - * The default constructor. - */ - public TypeImportList() { - } - - /** - * The copy constructor. - * - * @param copy The copy - */ - public TypeImportList(TypeImportList copy) { - super(copy); - _format = copy.getFormat(); - _location = copy.getLocation(); - for (TypeImport ti : copy.getTypeImports()) { - _types.add(new TypeImport(ti)); - } - } - - /** - * This method returns the format. - * - * @return The format - */ - public String getFormat() { - return (_format); - } - - /** - * This method sets the format. - * - * @param format The format - */ - public void setFormat(String format) { - _format = format; - } - - /** - * This method returns the location of the schema. - * - * @return The location - */ - public String getLocation() { - return (_location); - } - - /** - * This method sets the location of the schema. - * - * @param location The location - */ - public void setLocation(String location) { - _location = location; - } - - /** - * This method returns the list of imported types. - * - * @return The list of imported types - */ - public java.util.List getTypeImports() { - return (_types); - } - - /** - * This method returns the imported type associated with - * the supplied name. - * - * @param name The type name - * @return The type, or null if not found - */ - public TypeImport getTypeImport(String name) { - TypeImport ret=null; - - for (int i=0; ret == null - && i < _types.size(); i++) { - if (_types.get(i).getName().equals(name)) { - ret = _types.get(i); - } - } - - return (ret); - } - - /** - * This method visits the model object using the supplied - * visitor. - * - * @param visitor The visitor - */ - public void visit(Visitor visitor) { - visitor.accept(this); - - for (TypeImport t : getTypeImports()) { - t.visit(visitor); - } - } -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/TypeReference.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/TypeReference.java deleted file mode 100644 index 111144fe0..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/TypeReference.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright 2009 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.model; - -/** - * This class represents a type reference. - */ -public class TypeReference extends ModelObject { - - private String _name=null; - - /** - * This is the default constructor for the type reference. - */ - public TypeReference() { - } - - /** - * This is the copy constructor for the type reference. - * - * @param ref The reference to copy - */ - public TypeReference(TypeReference ref) { - super(ref); - _name = ref._name; - } - - /** - * This is the constructor for the type reference. - * - * @param name The name - */ - public TypeReference(String name) { - setName(name); - } - - /** - * This method returns the name associated with the - * model reference. - * - * @return The name - */ - public String getName() { - return (_name); - } - - /** - * This method sets the name associated with the - * model reference. - * - * @param name The name - */ - public void setName(String name) { - _name = name; - } - - /** - * This method visits the model object using the supplied - * visitor. - * - * @param visitor The visitor - */ - public void visit(Visitor visitor) { - } - - /** - * This method returns the hash code. - * - * @return The hash code - */ - public int hashCode() { - int ret=0; - - if (getName() != null) { - ret = getName().hashCode(); - } - - return (ret); - } - - @Override - public boolean equals(Object o) { - if (!(o instanceof TypeReference)) { - return false; - } - TypeReference tr = (TypeReference) o; - return tr._name == null ? _name == null : tr._name.equals(_name); - } - - @Override - public String toString() { - return ("TypeRef["+getName()+"]"); - } -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/Unordered.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/Unordered.java deleted file mode 100644 index 562a0109c..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/Unordered.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.model; - -/** - * This class represents the Unordered construct. - * - */ -public class Unordered extends Activity { - - private Block _block=new Block(); - - /** - * This is the default constructor. - * - */ - public Unordered() { - _block.setParent(this); - } - - /** - * This method returns the activities. - * - * @return The block of activities - */ - public Block getBlock() { - return (_block); - } - - /** - * This method sets the block. - * - * @param block The block - */ - public void setBlock(Block block) { - if (_block != null) { - _block.setParent(null); - } - - _block = block; - - if (_block != null) { - _block.setParent(this); - } - } - - /** - * This method visits the model object using the supplied - * visitor. - * - * @param visitor The visitor - */ - public void visit(Visitor visitor) { - if (visitor.start(this)) { - - if (getBlock() != null) { - getBlock().visit(visitor); - } - } - - visitor.end(this); - } -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/Visitor.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/Visitor.java deleted file mode 100644 index c3d8c53d1..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/model/Visitor.java +++ /dev/null @@ -1,291 +0,0 @@ -/* - * Copyright 2009 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.model; - -/** - * This interface represents a visitor which can be used - * to traverse a model. - */ -public interface Visitor { - - /** - * This method indicates the start of a - * block. - * - * @param elem The block - * @return Whether to process the contents - */ - public boolean start(Block elem); - - /** - * This method indicates the end of a - * block. - * - * @param elem The block - */ - public void end(Block elem); - - /** - * This method indicates the start of a - * choice. - * - * @param elem The choice - * @return Whether to process the contents - */ - public boolean start(Choice elem); - - /** - * This method indicates the end of a - * choice. - * - * @param elem The choice - */ - public void end(Choice elem); - - /** - * This method indicates the start of a - * directed choice. - * - * @param elem The directed choice - * @return Whether to process the contents - */ - public boolean start(DirectedChoice elem); - - /** - * This method indicates the end of a - * directed choice. - * - * @param elem The directed choice - */ - public void end(DirectedChoice elem); - - /** - * This method indicates the start of a - * on-message. - * - * @param elem The on-message element - * @return Whether to process the contents - */ - public boolean start(OnMessage elem); - - /** - * This method indicates the end of a - * on-message. - * - * @param elem The on-message element - */ - public void end(OnMessage elem); - - /** - * This method indicates the start of a - * parallel. - * - * @param elem The parallel - * @return Whether to process the contents - */ - public boolean start(Parallel elem); - - /** - * This method indicates the end of a - * parallel. - * - * @param elem The parallel - */ - public void end(Parallel elem); - - /** - * This method indicates the start of a - * protocol. - * - * @param elem The protocol - * @return Whether to process the contents - */ - public boolean start(Protocol elem); - - /** - * This method indicates the end of a - * protocol. - * - * @param elem The protocol - */ - public void end(Protocol elem); - - /** - * This method indicates the start of a - * repeat. - * - * @param elem The repeat - * @return Whether to process the contents - */ - public boolean start(Repeat elem); - - /** - * This method indicates the end of a - * repeat. - * - * @param elem The repeat - */ - public void end(Repeat elem); - - /** - * This method indicates the start of a - * labelled block. - * - * @param elem The labelled block - * @return Whether to process the contents - */ - public boolean start(RecBlock elem); - - /** - * This method indicates the end of a - * labelled block. - * - * @param elem The labelled block - */ - public void end(RecBlock elem); - - /** - * This method indicates the start of a - * unordered block. - * - * @param elem The unordered block - * @return Whether to process the contents - */ - public boolean start(Unordered elem); - - /** - * This method indicates the end of a - * unordered block. - * - * @param elem The unordered block - */ - public void end(Unordered elem); - - /** - * This method indicates the start of a - * try escape. - * - * @param elem The try escape - * @return Whether to process the contents - */ - public boolean start(Do elem); - - /** - * This method indicates the end of a - * try escape. - * - * @param elem The try escape - */ - public void end(Do elem); - - /** - * This method indicates the start of a - * catch block. - * - * @param elem The catch block - * @return Whether to process the contents - */ - public boolean start(Interrupt elem); - - /** - * This method indicates the end of a - * catch block. - * - * @param elem The catch block - */ - public void end(Interrupt elem); - - /** - * This method visits a - * run construct. - * - * @param elem The run - */ - public void accept(Run elem); - - /** - * This method visits an import component. - * - * @param elem The import - */ - public void accept(TypeImportList elem); - - /** - * This method visits an import component. - * - * @param elem The import - */ - public void accept(ProtocolImportList elem); - - /** - * This method visits an interaction component. - * - * @param elem The interaction - */ - public void accept(Interaction elem); - - /** - * This method visits the role list. - * - * @param elem The role list - */ - public void accept(Introduces elem); - - /** - * This method visits a recursion component. - * - * @param elem The recursion - */ - public void accept(Recursion elem); - - /** - * This method visits an inline component. - * - * @param elem The inline - */ - public void accept(Inline elem); - - /** - * This method visits a type import component. - * - * @param elem The type import - */ - public void accept(TypeImport elem); - - /** - * This method visits a protocol import component. - * - * @param elem The protocol import - */ - public void accept(ProtocolImport elem); - - /** - * This method visits an end statement. - * - * @param elem The end statement - */ - public void accept(End elem); - - /** - * This method visits any extensible activity that is not - * part of the base protocol model. - * - * @param elem The activity - */ - public void accept(CustomActivity elem); - -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/osgi/Activator.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/osgi/Activator.java deleted file mode 100644 index 727cf46f1..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/osgi/Activator.java +++ /dev/null @@ -1,209 +0,0 @@ -/* - * Copyright 2009 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.osgi; - -import java.util.Properties; -import java.util.logging.Logger; - -import org.osgi.framework.BundleActivator; -import org.osgi.framework.BundleContext; -import org.osgi.framework.ServiceReference; -import org.osgi.util.tracker.ServiceTracker; -import org.scribble.common.logging.ConsoleJournal; -import org.scribble.common.logging.Journal; -import org.scribble.protocol.export.DefaultProtocolExportManager; -import org.scribble.protocol.export.ProtocolExportManager; -import org.scribble.protocol.export.ProtocolExporter; -import org.scribble.protocol.export.text.TextProtocolExporter; -import org.scribble.protocol.export.text.TextProtocolExporterRule; -import org.scribble.protocol.parser.DefaultProtocolParserManager; -import org.scribble.protocol.parser.ProtocolParser; -import org.scribble.protocol.parser.ProtocolParserManager; -import org.scribble.protocol.projection.ProtocolProjector; -import org.scribble.protocol.validation.DefaultProtocolValidationManager; -import org.scribble.protocol.validation.ProtocolValidationManager; -import org.scribble.protocol.validation.ProtocolValidator; -import org.scribble.protocol.validation.rules.DefaultProtocolComponentValidator; - -/** - * Activator. - * - */ -public class Activator implements BundleActivator { - - private static final Logger LOG=Logger.getLogger(Activator.class.getName()); - - private org.osgi.util.tracker.ServiceTracker _protocolParserTracker=null; - private org.osgi.util.tracker.ServiceTracker _protocolValidatorTracker=null; - private org.osgi.util.tracker.ServiceTracker _protocolProjectorTracker=null; - private org.osgi.util.tracker.ServiceTracker _protocolExporterTracker=null; - private org.osgi.util.tracker.ServiceTracker _protocolTextExporterRuleTracker=null; - - /** - * Start the bundle. - * - * @param context The context - * @throws Exception Failed to start - * @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext) - */ - public void start(BundleContext context) throws Exception { - - Properties props = new Properties(); - - // Register parser manager - final ProtocolParserManager pm=new DefaultProtocolParserManager(); - - context.registerService(ProtocolParserManager.class.getName(), - pm, props); - - LOG.fine("Registered Parser Manager"); - - _protocolParserTracker = new ServiceTracker(context, - org.scribble.protocol.parser.ProtocolParser.class.getName(), - null) { - - public Object addingService(ServiceReference ref) { - Object ret=super.addingService(ref); - - LOG.fine("Parser has been added: "+ret); - - pm.getParsers().add((ProtocolParser)ret); - - return (ret); - } - }; - - _protocolParserTracker.open(); - - // Register validation manager - final ProtocolValidationManager vm=new DefaultProtocolValidationManager(); - - context.registerService(ProtocolValidationManager.class.getName(), - vm, props); - - LOG.fine("Registered Validation Manager"); - - _protocolValidatorTracker = new ServiceTracker(context, - org.scribble.protocol.validation.ProtocolValidator.class.getName(), - null) { - - public Object addingService(ServiceReference ref) { - Object ret=super.addingService(ref); - - LOG.fine("Validator has been added: "+ret); - - vm.getValidators().add((ProtocolValidator)ret); - - return (ret); - } - }; - - _protocolValidatorTracker.open(); - - _protocolProjectorTracker = new ServiceTracker(context, - org.scribble.protocol.projection.ProtocolProjector.class.getName(), - null) { - - public Object addingService(ServiceReference ref) { - Object ret=super.addingService(ref); - - LOG.fine("Projector has been added to validator manager: "+ret); - - vm.setProtocolProjector((ProtocolProjector)ret); - - return (ret); - } - }; - - _protocolProjectorTracker.open(); - - // Register export manager - final ProtocolExportManager em=new DefaultProtocolExportManager(); - - context.registerService(ProtocolExportManager.class.getName(), - em, props); - - LOG.fine("Registered Export Manager"); - - _protocolExporterTracker = new ServiceTracker(context, - org.scribble.protocol.export.ProtocolExporter.class.getName(), - null) { - - public Object addingService(ServiceReference ref) { - Object ret=super.addingService(ref); - - LOG.fine("Exporter has been added: "+ret); - - em.getExporters().add((ProtocolExporter)ret); - - return (ret); - } - }; - - _protocolExporterTracker.open(); - - // Register console journal - context.registerService(Journal.class.getName(), - new ConsoleJournal(), props); - - // Register protocol validator - props = new Properties(); - - context.registerService(ProtocolValidator.class.getName(), - new DefaultProtocolComponentValidator(), props); - - // Register text based exporter - props = new Properties(); - - final TextProtocolExporter tpe=new TextProtocolExporter(); - - context.registerService(ProtocolExporter.class.getName(), - new TextProtocolExporter(), props); - - LOG.fine("Registered Text Protocol Exporter"); - - _protocolTextExporterRuleTracker = new ServiceTracker(context, - org.scribble.protocol.export.text.TextProtocolExporterRule.class.getName(), - null) { - - public Object addingService(ServiceReference ref) { - Object ret=super.addingService(ref); - - LOG.fine("Text Exporter Rule has been added: "+ret); - - tpe.register((TextProtocolExporterRule)ret); - - return (ret); - } - }; - - _protocolTextExporterRuleTracker.open(); - - } - - /** - * Stop the bundle. - * - * @param context The context - * @throws Exception Failed to stop - * @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext) - */ - public void stop(BundleContext context) throws Exception { - - //context.ungetService(arg0); - } -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/parser/AnnotationProcessor.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/parser/AnnotationProcessor.java deleted file mode 100644 index 150f71ebc..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/parser/AnnotationProcessor.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright 2009-11 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.parser; - -import org.scribble.common.logging.Journal; -import org.scribble.common.model.Annotation; - -/** - * This interface represents an annotation processor, used to process - * free format text annotations. - * - */ -public interface AnnotationProcessor { - - /** - * This method is called when an annotation is found. - * - * @param annotation The annotation text - * @param properties The associated model object's properties - * @param journal The journal - * @return An implementation of the annotation, or null if cannot be processed - */ - public Annotation getAnnotation(String annotation, java.util.Map properties, - Journal journal); - -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/parser/DefaultProtocolParserManager.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/parser/DefaultProtocolParserManager.java deleted file mode 100644 index 4fbad473e..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/parser/DefaultProtocolParserManager.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.parser; - -import org.scribble.common.logging.Journal; -import org.scribble.common.resource.Content; -import org.scribble.protocol.ProtocolContext; -import org.scribble.protocol.model.ProtocolModel; - -/** - * This class represents the default implementation of the ProtocolProtocolManager - * interface. - * - */ -public class DefaultProtocolParserManager implements ProtocolParserManager { - - private java.util.List _parsers= - new java.util.Vector(); - - /** - * This is the default constructor. - */ - public DefaultProtocolParserManager() { - } - - /** - * This method determines whether there is a parser available for the supplied - * content. - * - * @param content The content - * @return Whether a parser is available for the supplied content - */ - public boolean isParserAvailable(Content content) { - - if (_parsers != null) { - for (ProtocolParser p : _parsers) { - if (p.isSupported(content)) { - return (true); - } - } - } - - return (false); - } - - /** - * This method parses the supplied content to create a protocol - * model. Any issues are reported to the supplied journal. The protocol - * context is optionally used by the parser to locate additional artifacts - * required to construct the protocol model. - * - * @param context The protocol context - * @param content The content to be parsed - * @param journal The journal for reporting issues - * @return The protocol model - * @throws java.io.IOException Failed to retrieve content to be parsed - */ - public ProtocolModel parse(ProtocolContext context, Content content, Journal journal) - throws java.io.IOException { - ProtocolModel ret=null; - - if (_parsers != null) { - for (ProtocolParser p : _parsers) { - if (p.isSupported(content)) { - ret = p.parse(context, content, journal); - - if (ret != null) { - break; - } - } - } - } - - return (ret); - } - - /** - * This method returns the list of protocol parsers. - * - * @return The list of protocol parsers - */ - public java.util.List getParsers() { - if (_parsers == null) { - _parsers = new java.util.ArrayList(); - } - - return (_parsers); - } - - /** - * This method sets the list of protocol parsers. - * - * @param parsers The list of protocol parsers - */ - public void setParsers(java.util.List parsers) { - _parsers = parsers; - } - -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/parser/ProtocolParser.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/parser/ProtocolParser.java deleted file mode 100644 index 3ddaa54dc..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/parser/ProtocolParser.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright 2009 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.parser; - -import org.scribble.common.logging.Journal; -import org.scribble.common.resource.Content; -import org.scribble.protocol.ProtocolContext; -import org.scribble.protocol.model.ProtocolModel; - -/** - * This interface represents the protocol parser. - * - */ -public interface ProtocolParser { - - /** - * This method sets an annotation processor. - * - * @param ap The annotation processor - */ - public void setAnnotationProcessor(AnnotationProcessor ap); - - /** - * This method determines whether the parser supports the specified - * content. - * - * @param content The content - * @return Whether the parser supports the content - */ - public boolean isSupported(Content content); - - /** - * This method parses the supplied input stream to create a protocol - * model. Any issues are reported to the supplied journal. The protocol - * context is optionally used by the parser to locate additional artifacts - * required to construct the protocol model. - * - * @param context The protocol context - * @param content The content containing the information to be parsed - * @param journal The journal for reporting issues - * @return The protocol model - * @throws java.io.IOException Failed to retrieve content to be parsed - */ - public ProtocolModel parse(ProtocolContext context, Content content, Journal journal) - throws java.io.IOException; - -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/parser/ProtocolParserManager.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/parser/ProtocolParserManager.java deleted file mode 100644 index 42fe574aa..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/parser/ProtocolParserManager.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.parser; - -import org.scribble.common.logging.Journal; -import org.scribble.common.resource.Content; -import org.scribble.protocol.ProtocolContext; -import org.scribble.protocol.model.ProtocolModel; - -/** - * This interface defines the protocol parser manager, responsible - * for parsing a specified input stream against a parser appropriate - * for the information being parsed. - * - */ -public interface ProtocolParserManager { - - /** - * This method determines whether there is a parser available for the supplied - * content. - * - * @param content The content - * @return Whether a parser is available for the supplied content - */ - public boolean isParserAvailable(Content content); - - /** - * This method parses the supplied content to create a protocol - * model. Any issues are reported to the supplied journal. The protocol - * context is optionally used by the parser to locate additional artifacts - * required to construct the protocol model. - * - * @param context The protocol context - * @param content The content to be parsed - * @param journal The journal for reporting issues - * @return The protocol model - * @throws java.io.IOException Failed to retrieve content to be parsed - */ - public ProtocolModel parse(ProtocolContext context, Content content, Journal journal) - throws java.io.IOException; - - /** - * This method returns the list of protocol parsers. - * - * @return The list of protocol parsers - */ - public java.util.List getParsers(); - - /** - * This method sets the list of protocol parsers. - * - * @param parsers The list of protocol parsers - */ - public void setParsers(java.util.List parsers); - -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/parser/ProtocolParserManagerFactory.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/parser/ProtocolParserManagerFactory.java deleted file mode 100644 index b85fbbb6b..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/parser/ProtocolParserManagerFactory.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.parser; - -/** - * This is the factory class for obtaining the parser - * manager. - * - */ -public final class ProtocolParserManagerFactory { - - private final static ProtocolParserManager INSTANCE= - new org.scribble.protocol.parser.DefaultProtocolParserManager(); - - /** - * Private constructor. - */ - private ProtocolParserManagerFactory() { - } - - /** - * This method returns the parser manager. - * - * @return The parser manager - */ - public static ProtocolParserManager getParserManager() { - return (INSTANCE); - } -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/projection/ProtocolProjector.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/projection/ProtocolProjector.java deleted file mode 100644 index 741d276aa..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/projection/ProtocolProjector.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.projection; - -import org.scribble.common.logging.Journal; -import org.scribble.protocol.ProtocolContext; -import org.scribble.protocol.model.ProtocolModel; -import org.scribble.protocol.model.Role; -import org.scribble.protocol.validation.ProtocolValidationManager; - -/** - * This interface provides a projection capability, from a 'global' - * to 'local' model, for the protocol notation. - * - */ -public interface ProtocolProjector { - - /** - * This method sets the protocol validation manager. - * - * @param pvm The protocol validation manager - */ - public void setProtocolValidationManager(ProtocolValidationManager pvm); - - /** - * This method returns the protocol validation manager. - * - * @return The protocol validation manager - */ - public ProtocolValidationManager getProtocolValidationManager(); - - /** - * This method projects a 'global' protocol model to a specified - * role's 'local' protocol model. - * - * @param context The protocol context - * @param model The 'global' protocol model - * @param role The role to project - * @param journal Journal for reporting issues - * @return The 'local' protocol model - */ - public ProtocolModel project(ProtocolContext context, ProtocolModel model, Role role, - Journal journal); - -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/util/ActivityUtil.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/util/ActivityUtil.java deleted file mode 100644 index 756f7c7d4..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/util/ActivityUtil.java +++ /dev/null @@ -1,138 +0,0 @@ -/* - * Copyright 2009-11 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.util; - -import org.scribble.protocol.model.Activity; -import org.scribble.protocol.model.Block; -import org.scribble.protocol.model.Introduces; -import org.scribble.protocol.model.ModelObject; - -/** - * This class provides utility functions associated with activities. - * - */ -public final class ActivityUtil { - - /** - * Private constructor. - */ - private ActivityUtil() { - } - - /** - * This method determines whether the activity is - * a declaration. - * - * @param act The activity - * @return Whether the activity is a declaration - */ - public static boolean isDeclaration(Activity act) { - boolean ret=false; - - if (act instanceof Introduces) { - ret = true; - } - - return (ret); - } - - /** - * This method determines whether the activity is - * a behavioural element. - * - * @param act The activity - * @return Whether the activity is a behavioural element - */ - public static boolean isBehaviour(Activity act) { - return (!isDeclaration(act)); - } - - /** - * This method returns the innermost block that encloses all of the blocks supplied. - * - * @param blockList The list of blocks to check - * @return The block - */ - public static Block getEnclosingBlock(java.util.List blockList) { - Block ret=null; - - if (blockList.size() == 1) { - ret = blockList.get(0); - - } else if (blockList.size() > 1) { - // Find common parent block - java.util.List> listOfBlocks= - new java.util.Vector>(); - - for (Block block : blockList) { - java.util.List lb=getBlockPath(block); - - if (lb != null && lb.size() > 0) { - listOfBlocks.add(lb); - } - } - - // Find common lowest level block - int pos=-1; - java.util.List refblocks=listOfBlocks.get(0); - - for (int j=0; j < refblocks.size(); j++) { - boolean same=true; - Block ref=refblocks.get(j); - - for (int i=1; same && i < listOfBlocks.size(); i++) { - java.util.List lb=listOfBlocks.get(i); - - if (lb.size() <= j || ref != lb.get(j)) { - same = false; - } - } - - if (same) { - pos = j; - } - } - - if (pos != -1) { - ret = refblocks.get(pos); - } - } - - return (ret); - } - - /** - * This method returns the list of blocks from the root to the supplied block. - * - * @param b The block - * @return The path from the root block to the supplied block - */ - protected static java.util.List getBlockPath(Block b) { - java.util.List ret=new java.util.Vector(); - ModelObject cur=b; - - while (cur instanceof Block) { - ret.add(0, (Block)cur); - - do { - cur = cur.getParent(); - } while (cur != null && !(cur instanceof Block)); - } - - return (ret); - } -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/util/ChoiceUtil.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/util/ChoiceUtil.java deleted file mode 100644 index 12f62f006..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/util/ChoiceUtil.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.util; - -import org.scribble.protocol.model.MessageSignature; -import org.scribble.protocol.model.TypeReference; - -/** - * Utility functions for the choice construct. - * - */ -public final class ChoiceUtil { - - private static final String LABEL_SEPARATOR = "_"; - - /** - * Private constructor. - */ - private ChoiceUtil() { - } - - /** - * This method returns the label associated with the message signature. - * - * @param sig The message signature - * @return The label - */ - public static String getLabel(MessageSignature sig) { - StringBuffer ret=new StringBuffer(); - - if (sig.getOperation() != null) { - ret.append(sig.getOperation()); - } - - for (TypeReference tref : sig.getTypeReferences()) { - ret.append(LABEL_SEPARATOR); - ret.append(tref.getName()); - } - - return (ret.toString()); - } -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/util/InteractionUtil.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/util/InteractionUtil.java deleted file mode 100644 index 24eab9359..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/util/InteractionUtil.java +++ /dev/null @@ -1,220 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.util; - -import org.scribble.protocol.model.Block; -import org.scribble.protocol.model.Choice; -import org.scribble.protocol.model.DefaultVisitor; -import org.scribble.protocol.model.Interaction; -import org.scribble.protocol.model.MessageSignature; -import org.scribble.protocol.model.ModelObject; -import org.scribble.protocol.model.Protocol; -import org.scribble.protocol.model.Role; -import org.scribble.protocol.model.Run; - -/** - * This class provides utility functions for the interaction construct. - * - */ -public final class InteractionUtil { - - /** - * Private constructor. - */ - private InteractionUtil() { - } - - /** - * This method gets the 'from' role associated with the - * activity. - * - * @param act The activity - * @return The 'from' role if found - */ - public static Role getFromRole(ModelObject act) { - Role ret=null; - - if (act instanceof Interaction) { - ret = ((Interaction)act).getFromRole(); - } - - return (ret); - } - - /** - * This method gets the 'to' role associated with the - * activity. - * - * @param act The activity - * @return The 'to' role if found - */ - public static Role getToRole(ModelObject act) { - Role ret=null; - - if (act instanceof Interaction) { - // TODO: Need to handle multiple 'to' roles - if (((Interaction)act).getToRoles().size() > 0) { - ret = ((Interaction)act).getToRoles().get(0); - } - } - - return (ret); - } - - /** - * This method gets the message signature associated with the - * activity. - * - * @param act The activity - * @return The message signature if found - */ - public static MessageSignature getMessageSignature(ModelObject act) { - MessageSignature ret=null; - - if (act instanceof Interaction) { - ret = ((Interaction)act).getMessageSignature(); - } - - return (ret); - } - - /** - * This method determines the initial interactions associated with the - * supplied model object. - * - * @param scope The scope within which the search for initial interactions should be conducted - * @return The list of initial 'interaction' based activities - */ - public static java.util.List getInitialInteractions(ModelObject scope) { - java.util.List ret=new java.util.Vector(); - - scope.visit(new InitialInteractionVisitor(ret)); - - return (ret); - } - - /** - * This method determines whether the supplied interaction is the first within - * the supplied scope. - * - * @param scope The scope - * @param interaction The interaction - * @return Whether the interaction is an initial interaction in the supplied scope - */ - public static boolean isInitialInteraction(ModelObject scope, ModelObject interaction) { - boolean ret=false; - - java.util.List initial=getInitialInteractions(scope); - - for (int i=0; !ret && i < initial.size(); i++) { - ret = (initial.get(i) == interaction); - } - - return (ret); - } - - /** - * This class identifies the initial interaction. - * - */ - public static class InitialInteractionVisitor extends DefaultVisitor { - - private java.util.List _interactions=null; - private boolean _record=true; - private java.util.Map _savedState= - new java.util.HashMap(); - - /** - * This is the constructor. - * - * @param list The list to contain the interactions - */ - public InitialInteractionVisitor(java.util.List list) { - _interactions = list; - } - - @Override - public boolean start(Protocol elem) { - // If top level protocol, then continue, otherwise finish. - // Nested protocols should only be processed as part of a - // 'run' activity. - return (!(elem.getParent() instanceof Protocol)); - } - - @Override - public boolean start(Choice elem) { - return (_record); - } - - @Override - public void end(Choice elem) { - // TODO: SCRIBBLE-61 for now assume anything following - // choice cannot be initial interaction - _record = false; - } - - @Override - public boolean start(Block elem) { - - // If choice block, then need to save state so that can detect - // first interactions across all paths - if (elem.getParent() instanceof Choice) { - _savedState.put(elem, _record); - } - - return (true); - } - - @Override - public void end(Block elem) { - if (elem.getParent() instanceof Choice) { - _record = _savedState.get(elem); - } - - // TODO: SCRIBBLE-61 Need to accumulate results from when paths - // to determine if subsequent interactions should still be counted - // as 'initial' - but then could end up with situation where - // choice has initial interactions followed by another interaction - // that could potentially be initial - } - - @Override - public void accept(Interaction elem) { - - if (_record) { - _interactions.add(elem); - - _record = false; - } - } - - @Override - public void accept(Run elem) { - Protocol protocol=RunUtil.getInnerProtocol(elem.getEnclosingProtocol(), - elem.getProtocolReference()); //elem.getProtocol(); - - if (protocol != null) { - // TODO: Need to consider whether returned interactions need to have - // roles mapped? Only problem is that we can't update the interaction - // directly, so might need to have a mock copy some how? - - protocol.getBlock().visit(this); - } - } - } - -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/util/ProtocolModelUtil.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/util/ProtocolModelUtil.java deleted file mode 100644 index cae9bf1d1..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/util/ProtocolModelUtil.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright 2009-11 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.util; - -import org.scribble.protocol.model.ImportList; -import org.scribble.protocol.model.ProtocolImport; -import org.scribble.protocol.model.ProtocolImportList; -import org.scribble.protocol.model.ProtocolModel; -import org.scribble.protocol.model.ProtocolReference; - -/** - * This class provides utility functions related to the protocol model. - * - */ -public final class ProtocolModelUtil { - - /** - * Private constructor. - */ - private ProtocolModelUtil() { - } - - /** - * This method attempts to locate a protocol import statement associated - * with the supplied protocol reference. - * - * @param model The protocol model - * @param ref The protocol reference - * @return The protocol import statement, or null if not found - */ - public static ProtocolImport getProtocolImport(ProtocolModel model, ProtocolReference ref) { - ProtocolImport ret=null; - - for (ImportList il : model.getImports()) { - if (il instanceof ProtocolImportList) { - - for (ProtocolImport pi : ((ProtocolImportList)il).getProtocolImports()) { - if (pi.getName().equals(ref.getName())) { - ret = pi; - break; - } - } - } - } - - return (ret); - } - -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/util/RoleUtil.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/util/RoleUtil.java deleted file mode 100644 index b41bbd0a9..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/util/RoleUtil.java +++ /dev/null @@ -1,482 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.util; - -import org.scribble.protocol.model.Activity; -import org.scribble.protocol.model.Block; -import org.scribble.protocol.model.Choice; -import org.scribble.protocol.model.DefaultVisitor; -import org.scribble.protocol.model.DirectedChoice; -import org.scribble.protocol.model.Do; -import org.scribble.protocol.model.End; -import org.scribble.protocol.model.Inline; -import org.scribble.protocol.model.Interaction; -import org.scribble.protocol.model.Interrupt; -import org.scribble.protocol.model.Introduces; -import org.scribble.protocol.model.ModelObject; -import org.scribble.protocol.model.OnMessage; -import org.scribble.protocol.model.Parallel; -import org.scribble.protocol.model.Parameter; -import org.scribble.protocol.model.ParameterDefinition; -import org.scribble.protocol.model.Protocol; -import org.scribble.protocol.model.RecBlock; -import org.scribble.protocol.model.Recursion; -import org.scribble.protocol.model.Repeat; -import org.scribble.protocol.model.Role; -import org.scribble.protocol.model.Run; -import org.scribble.protocol.model.Unordered; - -/** - * This class provides utility functions related to the Role protocol - * component. - * - */ -public final class RoleUtil { - - /** - * Private constructor. - */ - private RoleUtil() { - } - - /** - * This method returns the roles defined within the parent scope of the - * supplied activity. - * - * @param block The parent scope - * @return The set of roles - */ - public static java.util.Set getDeclaredRoles(Block block) { - final java.util.Set roles=new java.util.HashSet(); - - block.visit(new DefaultVisitor() { - - protected void addRole(Role r) { - if (r != null && !roles.contains(r)) { - roles.add(r); - } - } - - public void accept(Introduces elem) { - for (Role r : elem.getIntroducedRoles()) { - addRole(r); - } - } - - public boolean start(Protocol elem) { - return (false); - } - }); - - return (roles); - } - - /** - * This method returns the enclosing protocol associated with the - * supplied role. - * - * @param role The role - * @return The protocol - */ - public static Protocol getEnclosingProtocol(Role role) { - Protocol ret=null; - - if (role.getParent() instanceof Introduces) { - ret = ((Introduces)role.getParent()).getEnclosingProtocol(); - } else if (role.getParent() instanceof ParameterDefinition - && role.getParent().getParent() instanceof Protocol) { - ret = (Protocol)role.getParent().getParent(); - } - - return (ret); - } - - /** - * This method returns the set of roles that are associated with - * the supplied activity. - * - * @param act The activity - * @return The set of roles associated with the activity and its - * sub components if a grouping construct - */ - public static java.util.Set getUsedRoles(final ModelObject act) { - final java.util.Set roles=new java.util.HashSet(); - - act.visit(new DefaultVisitor() { - - protected void addRole(Role r) { - if (r != null && !roles.contains(r)) { - roles.add(r); - } - } - - public void accept(Interaction elem) { - addRole(elem.getFromRole()); - for (Role r : elem.getToRoles()) { - addRole(r); - } - } - - public void accept(Inline elem) { - java.util.Set inscope=getRolesInScope(elem); - - for (Parameter p : elem.getParameters()) { - - // Determine if the parameter is a role - for (Role r : inscope) { - if (r.getName().equals(p.getName())) { - addRole(r); - break; - } - } - } - } - - public void accept(Run elem) { - java.util.Set inscope=getRolesInScope(elem); - - for (Parameter p : elem.getParameters()) { - - // Determine if the parameter is a role - for (Role r : inscope) { - if (r.getName().equals(p.getName())) { - addRole(r); - break; - } - } - } - } - - public boolean start(Choice elem) { - addRole(elem.getRole()); - return (true); - } - - public boolean start(DirectedChoice elem) { - addRole(elem.getFromRole()); - for (Role r : elem.getToRoles()) { - addRole(r); - } - return (true); - } - - public boolean start(Protocol elem) { - // If protocol was initial activity, then traverse, otherwise - // don't enter nested protocol - return (elem == act); - } - }); - - return (roles); - } - - /** - * This method determines the set of roles that are in the - * scope for the supplied activity. - * - * @param activity The activity - * @return The set of roles in scope for the supplied activity - */ - public static java.util.Set getRolesInScope(Activity activity) { - java.util.Set ret=new java.util.HashSet(); - - if (activity != null) { - - // Identify enclosing protocol definition - Protocol protocol=activity.getEnclosingProtocol(); - - if (protocol != null) { - - // Add role parameters - for (ParameterDefinition pd : protocol.getParameterDefinitions()) { - if (pd.isRole()) { - ret.add(new Role(pd.getName())); - } - } - - RoleLocator visitor=new RoleLocator(protocol, activity, ret); - - protocol.visit(visitor); - } - } - - return (ret); - } - - /** - * This method returns the innermost block that encloses all of the activities - * associated with the supplied role. - * - * @param protocol The protocol - * @param role The role - * @param includeDeclaration Whether the role's declaration should be taken into account - * @return The block - */ - public static Block getEnclosingBlock(final Protocol protocol, final Role role, - final boolean includeDeclaration) { - final java.util.List blocks=new java.util.Vector(); - - // Find all blocks enclosing an activity associated with the supplied role - protocol.visit(new DefaultVisitor() { - - public boolean start(Protocol elem) { - - if (protocol == elem) { - if (protocol.getParameterDefinition(role.getName()) != null) { - blocks.add(elem.getBlock()); - } - } - - // Don't visit contained protocols - return (protocol == elem); - } - - public void accept(org.scribble.protocol.model.Interaction elem) { - if (role.equals(elem.getFromRole()) || elem.getToRoles().contains(role) - || ((elem.getFromRole() == null || elem.getToRoles().size() == 0) - && role.equals(elem.getEnclosingProtocol().getLocatedRole()))) { - blocks.add((Block)elem.getParent()); - } - } - - public boolean start(Choice elem) { - if (role.equals(elem.getRole()) /*|| (elem.getRole() == null && - role.equals(elem.enclosingProtocol().getRole()))*/) { - blocks.add((Block)elem.getParent()); - } - - return (true); - } - - public boolean start(DirectedChoice elem) { - if (role.equals(elem.getFromRole()) || elem.getToRoles().contains(role) - || ((elem.getFromRole() == null || elem.getToRoles().size() == 0) - && role.equals(elem.getEnclosingProtocol().getLocatedRole()))) { - blocks.add((Block)elem.getParent()); - } - - return (true); - } - - public void accept(Introduces elem) { - if (includeDeclaration && elem.getIntroducedRoles().contains(role)) { - blocks.add((Block)elem.getParent()); - } - } - }); - - return (ActivityUtil.getEnclosingBlock(blocks)); - } - - /** - * Visitor for locating roles. - * - */ - public static class RoleLocator extends DefaultVisitor { - - private boolean _recurse=true; - private Protocol _protocol=null; - private Activity _activity=null; - private java.util.Set _result=null; - private java.util.List> _roleStack= - new java.util.Vector>(); - - /** - * Constructor. - * - * @param protocol The protocol - * @param activity The activity - * @param result The set of roles - */ - public RoleLocator(Protocol protocol, Activity activity, - java.util.Set result) { - _protocol = protocol; - _activity = activity; - _result = result; - } - - @Override - public boolean start(Block elem) { - return (startBlock(elem)); - } - - /** - * Indicates the start of a block. - * - * @param elem The block - * @return Whether to process contents - */ - protected boolean startBlock(Block elem) { - // Push new role list onto the stack - _roleStack.add(new java.util.Vector()); - - return (true); - } - - @Override - public void end(Block elem) { - endBlock(elem); - } - - /** - * Process the end of the block. - * - * @param elem The block - */ - protected void endBlock(Block elem) { - // Pop top role list from the stack - _roleStack.remove(_roleStack.size()-1); - } - - @Override - public boolean start(Choice elem) { - checkActivity(elem); - return (_recurse); - } - - @Override - public boolean start(DirectedChoice elem) { - checkActivity(elem); - return (_recurse); - } - - @Override - public boolean start(OnMessage elem) { - return (_recurse); - } - - @Override - public boolean start(Unordered elem) { - checkActivity(elem); - return (_recurse); - } - - @Override - public boolean start(Parallel elem) { - checkActivity(elem); - return (_recurse); - } - - @Override - public boolean start(Protocol elem) { - // If this is the enclosing protocol, then - // recursively visit it - otherwise don't - boolean ret=(_protocol == elem); - - if (ret) { - java.util.List rlist=new java.util.Vector(); - _roleStack.add(rlist); - - if (elem.getLocatedRole() != null) { - rlist.add(elem.getLocatedRole()); - } - - for (ParameterDefinition p : elem.getParameterDefinitions()) { - if (p.getType() == null) { - rlist.add(new Role(p.getName())); - } - } - - } - - return (ret); - } - - @Override - public boolean start(Repeat elem) { - checkActivity(elem); - return (_recurse); - } - - @Override - public boolean start(RecBlock elem) { - checkActivity(elem); - return (_recurse); - } - - @Override - public boolean start(Do elem) { - checkActivity(elem); - return (_recurse); - } - - @Override - public boolean start(Interrupt elem) { - return (_recurse); - } - - @Override - public void accept(Run elem) { - checkActivity(elem); - } - - @Override - public void accept(Interaction elem) { - checkActivity(elem); - } - - @Override - public void accept(Introduces elem) { - java.util.List rlist=_roleStack.get(_roleStack.size()-1); - - rlist.addAll(elem.getIntroducedRoles()); - } - - @Override - public void accept(Inline elem) { - checkActivity(elem); - } - - @Override - public void accept(Recursion elem) { - checkActivity(elem); - } - - /** - * This method visits an end statement. - * - * @param elem The end statement - */ - public void accept(End elem) { - checkActivity(elem); - } - - /** - * This method checks the supplied activity to - * determine if it is the activity being searched - * for, and if so identifies the roles in scope - * as the result. - * - * @param elem The activity - */ - protected void checkActivity(Activity elem) { - - if (elem == _activity) { - // Record the current stack of roles in the result - for (java.util.List plist : _roleStack) { - - for (Role p : plist) { - _result.add(p); - } - } - - // Remainder of description should be traversed quickly - _recurse = false; - } - } - } -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/util/RunUtil.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/util/RunUtil.java deleted file mode 100644 index e5527d0ce..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/util/RunUtil.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.util; - -import org.scribble.protocol.model.Protocol; -import org.scribble.protocol.model.ProtocolReference; - -/** - * This class provides helper functions for the Run construct. - * - */ -public final class RunUtil { - - /** - * Private constructor. - */ - private RunUtil() { - } - - /** - * This method attempts to locate an inner protocol associated with the supplied - * protocol reference. - * - * @param protocol The parent protocol - * @param protocolRef The protocol reference - * @return The inner protocol, or null if not found - */ - public static Protocol getInnerProtocol(Protocol protocol, ProtocolReference protocolRef) { - Protocol ret=null; - - for (int i=0; ret == null && i < protocol.getNestedProtocols().size(); i++) { - Protocol nested=protocol.getNestedProtocols().get(i); - - if (protocolRef.getName().equals(nested.getName()) - && ((protocolRef.getRole() == null && nested.getLocatedRole() == null) - || (protocolRef.getRole() != null && nested.getLocatedRole() != null - && protocolRef.getRole().equals(nested.getLocatedRole())))) { - ret = nested; - } - } - - return (ret); - } -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/util/TypesUtil.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/util/TypesUtil.java deleted file mode 100644 index 07621b7c3..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/util/TypesUtil.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.util; - -import org.scribble.protocol.model.ImportList; -import org.scribble.protocol.model.ModelObject; -import org.scribble.protocol.model.ProtocolModel; -import org.scribble.protocol.model.TypeImport; -import org.scribble.protocol.model.TypeImportList; -import org.scribble.protocol.model.TypeReference; - -/** - * Helper functions for dealing with protocol types. - * - */ -public final class TypesUtil { - - /** - * Private constructor. - */ - private TypesUtil() { - } - - /** - * This method identifies the type import for the supplied - * type reference. - * - * @param typeRef The type reference - * @return The type import, or null if not found - */ - public static TypeImport getTypeImport(TypeReference typeRef) { - TypeImport ret=null; - - String typeName=typeRef.getName(); - - ProtocolModel pm=null; - - ModelObject cur=typeRef; - while (cur != null) { - if (cur instanceof ProtocolModel) { - pm = (ProtocolModel)cur; - } - cur = cur.getParent(); - } - - if (pm != null) { - - for (int i=0; ret == null && i < pm.getImports().size(); i++) { - ImportList imp=pm.getImports().get(i); - - if (imp instanceof TypeImportList) { - ret = ((TypeImportList)imp).getTypeImport(typeName); - } - } - } - - return (ret); - } - - /** - * This method identifies the type import for the supplied - * protocol model and type name. - * - * @param pm The protocol model - * @param typeName The type name - * @return The type import, or null if not found - */ - public static TypeImport getTypeImport(ProtocolModel pm, String typeName) { - TypeImport ret=null; - - if (pm != null && typeName != null) { - - for (int i=0; ret == null && i < pm.getImports().size(); i++) { - ImportList imp=pm.getImports().get(i); - - if (imp instanceof TypeImportList) { - ret = ((TypeImportList)imp).getTypeImport(typeName); - } - } - } - - return (ret); - } - - /** - * This method determines whether the protocol model has concrete types - * defined. - * - * @param model The model - * @return Whether concrete types have been defined - */ - public static boolean isConcreteTypesDefined(ProtocolModel model) { - boolean ret=false; - - for (ImportList imp : model.getImports()) { - - if (imp instanceof TypeImportList) { - for (TypeImport ti : ((TypeImportList)imp).getTypeImports()) { - - if (ti.getDataType() != null) { - ret = true; - break; - } - } - } - - if (ret) { - break; - } - } - - return (ret); - } -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/validation/DefaultProtocolValidationManager.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/validation/DefaultProtocolValidationManager.java deleted file mode 100644 index b759f037d..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/validation/DefaultProtocolValidationManager.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright 2009 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.validation; - -import org.scribble.protocol.ProtocolContext; -import org.scribble.protocol.projection.ProtocolProjector; - -/** - * This class represents the default implementation of the ProtocolValidationManager - * interface. - * - */ -public class DefaultProtocolValidationManager implements ProtocolValidationManager { - - private java.util.List _validators= - new java.util.Vector(); - private ProtocolProjector _projector=null; - - /** - * This is the default constructor. - */ - public DefaultProtocolValidationManager() { - } - - /** - * This method sets the protocol projector. - * - * @param pp The protocol projector - */ - public void setProtocolProjector(ProtocolProjector pp) { - _projector = pp; - } - - /** - * This method gets the protocol projector. - * - * @return The protocol projector - */ - public ProtocolProjector getProtocolProjector() { - return (_projector); - } - - /** - /** - * This method invokes the validation of the supplied - * model against the registered validators. Any issues - * found during validation will be reported to the - * supplied journal. - * - * @param pc The protocol context - * @param model The protocol model - * @param journal The journal - */ - public void validate(ProtocolContext pc, org.scribble.protocol.model.ProtocolModel model, - org.scribble.common.logging.Journal journal) { - - if (_validators != null) { - ProtocolValidatorContext pvc=new DefaultProtocolValidatorContext(pc, _projector); - - for (ProtocolValidator v : _validators) { - v.validate(pvc, model, journal); - } - } - } - - /** - * This method returns the list of protocol validators. - * - * @return The list of validators - */ - public java.util.List getValidators() { - if (_validators == null) { - _validators = new java.util.ArrayList(); - } - - return (_validators); - } - - /** - * This method sets the list of protocol validators. - * - * @param validators The list of validators - */ - public void setValidators(java.util.List validators) { - _validators = validators; - } -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/validation/DefaultProtocolValidatorContext.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/validation/DefaultProtocolValidatorContext.java deleted file mode 100644 index 1fac09988..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/validation/DefaultProtocolValidatorContext.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Copyright 2009-11 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.validation; - -import java.util.logging.Logger; - -import org.scribble.protocol.ProtocolContext; -import org.scribble.protocol.projection.ProtocolProjector; - -/** - * This class provides access to capabilities offered by the - * protocol validator. - * - */ -public class DefaultProtocolValidatorContext implements ProtocolValidatorContext { - - private static final Logger LOG=Logger.getLogger(DefaultProtocolValidatorContext.class.getName()); - - private ProtocolContext _protocolContext=null; - private ProtocolProjector _projector=null; - private Scope _scope=new Scope(); - private java.util.List _scopeStack=new java.util.Vector(); - - /** - * This is the constructor. - * - * @param pc The protocol context - * @param pp The protocol projector - */ - public DefaultProtocolValidatorContext(ProtocolContext pc, ProtocolProjector pp) { - _protocolContext = pc; - _projector = pp; - } - - /** - * {@inheritDoc} - */ - public ProtocolContext getProtocolContext() { - return (_protocolContext); - } - - /** - * {@inheritDoc} - */ - public ProtocolProjector getProtocolProjector() { - return (_projector); - } - - /** - * {@inheritDoc} - */ - public Object getState(String name) { - return (_scope.getState(name)); - } - - /** - * {@inheritDoc} - */ - public void setState(String name, Object value) { - _scope.setState(name, value); - } - - /** - * {@inheritDoc} - */ - public void pushState() { - _scope.pushState(); - } - - /** - * {@inheritDoc} - */ - public void popState() { - _scope.popState(); - } - - /** - * {@inheritDoc} - */ - public void pushScope() { - _scopeStack.add(0, _scope); - _scope = new Scope(); - } - - /** - * {@inheritDoc} - */ - public void popScope() { - if (_scopeStack.size() > 0) { - _scope = _scopeStack.remove(0); - } else { - LOG.severe("No state entry to pop from stack"); - } - } - -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/validation/ProtocolComponentValidator.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/validation/ProtocolComponentValidator.java deleted file mode 100644 index 44412bb9d..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/validation/ProtocolComponentValidator.java +++ /dev/null @@ -1,157 +0,0 @@ -/* - * Copyright 2009 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.validation; - -import org.scribble.common.logging.Journal; -import org.scribble.protocol.model.Block; -import org.scribble.protocol.model.ModelObject; -import org.scribble.protocol.model.Protocol; - -//import java.util.logging.*; - -/** - * This class provides an implementation of the ProtocolValidator - * interface. It enables individual validation rules, associated with - * specific model components, to be registered and invoked when - * validating a protocol model. - */ -public class ProtocolComponentValidator implements ProtocolValidator { - - private java.util.List _rules=null; - - /** - * The default constructor. - */ - public ProtocolComponentValidator() { - } - - /** - * This method returns the validator rules. - * - * @return The rules - */ - public java.util.List getRules() { - if (_rules == null) { - _rules = new java.util.ArrayList(); - } - - return (_rules); - } - - /** - * This method sets the validator rules. - * - * @param rules The rules - */ - public void setRules(java.util.List rules) { - _rules = rules; - } - - /** - * {@inheritDoc} - */ - public void validate(ProtocolValidatorContext pvc, - org.scribble.protocol.model.ProtocolModel model, Journal journal) { - ValidatingVisitor vv=new ValidatingVisitor(pvc, journal); - - model.visit(vv); - - // Validate the process model - this needs to be done separately as the - // model is not included in the visitor, only its contents - vv.process(model); - } - - /** - * This class traverses the protocol model to validate the individual constructs. - * - */ - public class ValidatingVisitor extends org.scribble.protocol.model.AbstractModelObjectVisitor { - - private ProtocolValidatorContext _pvc=null; - private Journal _logger=null; - - /** - * This is the constructor for the vaidating visitor. - * - * @param pvc The protocol validator context - * @param logger The journal - */ - public ValidatingVisitor(ProtocolValidatorContext pvc, Journal logger) { - _pvc = pvc; - _logger = logger; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean start(Protocol elem) { - _pvc.pushScope(); - return (super.start(elem)); - } - - /** - * {@inheritDoc} - */ - @Override - public void end(Protocol elem) { - super.end(elem); - _pvc.popScope(); - } - - /** - * {@inheritDoc} - */ - @Override - public boolean start(Block elem) { - _pvc.pushState(); - return (super.start(elem)); - } - - /** - * {@inheritDoc} - */ - @Override - public void end(Block elem) { - super.end(elem); - _pvc.popState(); - } - - /** - * This method can be implemented to process all of the model - * objects within a particular protocol model. - * - * @param obj The model object - * @return Whether to process the contents - */ - public boolean process(ModelObject obj) { - - // Iterate through rules processing those that support the supplied - // model object - java.util.Iterator iter=getRules().iterator(); - - while (iter.hasNext()) { - ProtocolComponentValidatorRule rule=iter.next(); - - if (rule.isSupported(obj)) { - rule.validate(_pvc, obj, _logger); - } - } - - return (true); - } - } -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/validation/ProtocolComponentValidatorRule.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/validation/ProtocolComponentValidatorRule.java deleted file mode 100644 index 084475dc8..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/validation/ProtocolComponentValidatorRule.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright 2009 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.validation; - -import org.scribble.common.logging.Journal; -import org.scribble.protocol.model.ModelObject; - -/** - * This interface represents the validation rule for the - * model components. - * - */ -public interface ProtocolComponentValidatorRule { - - /** - * This method determines whether the rule is applicable - * for the supplied model object. - * - * @param obj The object to check - * @return Whether the rule can be used to validate the - * supplied model object - */ - public boolean isSupported(ModelObject obj); - - /** - * This method validates the supplied model object. - * - * @param pvc The protocol validator context - * @param obj The model object being validated - * @param logger The logger - */ - public void validate(ProtocolValidatorContext pvc, ModelObject obj, - Journal logger); - -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/validation/ProtocolValidationManager.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/validation/ProtocolValidationManager.java deleted file mode 100644 index 53208c8f8..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/validation/ProtocolValidationManager.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright 2009 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.validation; - -import org.scribble.protocol.ProtocolContext; -import org.scribble.protocol.projection.ProtocolProjector; - -/** - * This interface defines the protocol validation manager, responsible - * for validating a protocol model against a set of registered - * protocol validators. - * - */ -public interface ProtocolValidationManager { - - /** - * This method invokes the validation of the supplied - * model against the registered validators. Any issues - * found during validation will be reported to the - * supplied journal. - * - * @param context The protocol context - * @param model The protocol model - * @param journal The journal - */ - public void validate(ProtocolContext context, org.scribble.protocol.model.ProtocolModel model, - org.scribble.common.logging.Journal journal); - - /** - * This method returns the list of protocol validators. - * - * @return The list of validators - */ - public java.util.List getValidators(); - - /** - * This method sets the list of protocol validators. - * - * @param validators The list of validators - */ - public void setValidators(java.util.List validators); - - /** - * This method sets the protocol projector. - * - * @param pp The protocol projector - */ - public void setProtocolProjector(ProtocolProjector pp); - - /** - * This method gets the protocol projector. - * - * @return The protocol projector - */ - public ProtocolProjector getProtocolProjector(); - -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/validation/ProtocolValidationManagerFactory.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/validation/ProtocolValidationManagerFactory.java deleted file mode 100644 index 45c59b344..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/validation/ProtocolValidationManagerFactory.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright 2009 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.validation; - -/** - * This is the factory class for obtaining the validation - * manager. - * - */ -public final class ProtocolValidationManagerFactory { - - private final static ProtocolValidationManager INSTANCE= - new org.scribble.protocol.validation.DefaultProtocolValidationManager(); - - /** - * Private constructor. - */ - private ProtocolValidationManagerFactory() { - } - - /** - * This method returns the validation manager. - * - * @return The validation manager - */ - public static ProtocolValidationManager getValidationManager() { - return (INSTANCE); - } -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/validation/ProtocolValidator.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/validation/ProtocolValidator.java deleted file mode 100644 index cca2c12e7..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/validation/ProtocolValidator.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright 2009 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.validation; - -/** - * This interface represents the Protocol Validator. - * - */ -public interface ProtocolValidator { - - /** - * This method invokes the validation of the supplied - * model against the registered validators. Any issues - * found during validation will be reported to the - * supplied journal. - * - * @param pvc The protocol validator context - * @param model The protocol model - * @param journal The journal - */ - public void validate(ProtocolValidatorContext pvc, - org.scribble.protocol.model.ProtocolModel model, - org.scribble.common.logging.Journal journal); - -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/validation/ProtocolValidatorContext.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/validation/ProtocolValidatorContext.java deleted file mode 100644 index 543cd16ef..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/validation/ProtocolValidatorContext.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright 2009-11 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.validation; - -import org.scribble.protocol.ProtocolContext; -import org.scribble.protocol.projection.ProtocolProjector; - -/** - * This interface provides access to capabilities offered by the - * protocol validator. - * - */ -public interface ProtocolValidatorContext { - - /** - * This method returns the context in which the protocol - * is being processed. - * - * @return The protocol context - */ - public ProtocolContext getProtocolContext(); - - /** - * This method returns the protocol projector. - * - * @return The protocol projector - */ - public ProtocolProjector getProtocolProjector(); - - /** - * This method returns the named state from the current - * scope. - * - * @param name The state name - * @return The state value, or null if not found - */ - public Object getState(String name); - - /** - * This method sets the value associated with the supplied - * name in the current state. - * - * @param name The state name - * @param value The state value - */ - public void setState(String name, Object value); - - /** - * This method pushes the current state onto a stack. - */ - public void pushState(); - - /** - * This method pops the current state from the stack. - */ - public void popState(); - - /** - * This method pushes the current scope onto a stack. - */ - public void pushScope(); - - /** - * This method pops the current scope from the stack. - */ - public void popScope(); - -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/validation/Scope.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/validation/Scope.java deleted file mode 100644 index 788ce2337..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/validation/Scope.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright 2009-11 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.validation; - -import java.util.logging.Logger; - -/** - * This class represents information associated with a scope. - */ -public class Scope { - - private final static Logger LOG = Logger.getLogger(Scope.class.getName()); - - private java.util.List> _stateStack= - new java.util.Vector>(); - - /** - * The default constructor for the scope. - */ - public Scope() { - // Initialize the state - pushState(); - } - - /** - * This is the copy constructor for the scope. - * - * @param copy The copy - */ - public Scope(Scope copy) { - - for (int i=0; i < copy._stateStack.size(); i++) { - java.util.Map current=copy._stateStack.get(i); - - java.util.Map copyStackEntry= - new java.util.Hashtable(); - - java.util.Iterator iter=current.keySet().iterator(); - - while (iter.hasNext()) { - String key=iter.next(); - Object value=current.get(key); - - copyStackEntry.put(key, value); - } - - _stateStack.add(copyStackEntry); - } - } - - /** - * This method returns the named state from the current - * scope. - * - * @param name The state name - * @return The state value, or null if not found - */ - public Object getState(String name) { - Object ret=null; - - if (_stateStack.size() > 0) { - for (int i=0; ret == null && i < _stateStack.size(); i++) { - java.util.Map current=_stateStack.get(i); - ret = current.get(name); - } - } - - return (ret); - } - - /** - * This method sets the value associated with the supplied - * name in the current state scope. - * - * @param name The state name - * @param value The state value - */ - public void setState(String name, Object value) { - if (_stateStack.size() > 0) { - java.util.Map current=_stateStack.get(0); - current.put(name, value); - } - } - - /** - * This method pushes the current state onto a stack. - */ - public void pushState() { - _stateStack.add(0, new java.util.Hashtable()); - } - - /** - * This method pops the current state from the stack. - */ - public void popState() { - if (_stateStack.size() > 0) { - _stateStack.remove(0); - } else { - LOG.severe("No state entry to pop from stack"); - } - } - -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/validation/rules/ChoiceValidatorRule.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/validation/rules/ChoiceValidatorRule.java deleted file mode 100644 index 326794ca7..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/validation/rules/ChoiceValidatorRule.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.validation.rules; - -import java.text.MessageFormat; -import java.util.Collections; - -import org.scribble.common.logging.Journal; -import org.scribble.protocol.model.Block; -import org.scribble.protocol.model.Choice; -import org.scribble.protocol.model.ModelObject; -import org.scribble.protocol.model.Role; -import org.scribble.protocol.util.InteractionUtil; -import org.scribble.protocol.util.RoleUtil; -import org.scribble.protocol.validation.ProtocolComponentValidatorRule; -import org.scribble.protocol.validation.ProtocolValidatorContext; - -/** - * This class provides the validation rule for the Choice - * model component. - * - */ -public class ChoiceValidatorRule implements ProtocolComponentValidatorRule { - - /** - * This method determines whether the rule is applicable - * for the supplied model object. - * - * @param obj The object to check - * @return Whether the rule can be used to validate the - * supplied model object - */ - public boolean isSupported(ModelObject obj) { - return (obj.getClass() == org.scribble.protocol.model.Choice.class); - } - - /** - * {@inheritDoc} - */ - public void validate(ProtocolValidatorContext pvc, ModelObject obj, - Journal logger) { - Choice elem=(Choice)obj; - - // Identify definition and whether it has a located role - Role locatedRole=null; - - if (elem.getEnclosingProtocol() != null) { - locatedRole = elem.getEnclosingProtocol().getLocatedRole(); - } - - if (elem.getRole() != null) { - - // Check that the role has been defined in scope - java.util.Set roles=RoleUtil.getRolesInScope(elem); - - if (!roles.contains(elem.getRole())) { - logger.error(MessageFormat.format( - java.util.PropertyResourceBundle.getBundle("org.scribble.protocol.Messages").getString("_UNKNOWN_ROLE"), - elem.getRole().getName()), obj.getProperties()); - } - } - - if (locatedRole != null && elem.getRole() != null && !elem.getRole().equals(locatedRole)) { - logger.error(MessageFormat.format( - java.util.PropertyResourceBundle.getBundle( - "org.scribble.protocol.Messages").getString("_UNRELATED_TO_LOCATED_ROLE"), - locatedRole.getName()), obj.getProperties()); - } - - checkForAmbiguity(elem, logger); - } - - /** - * This method checks for ambiguity in the choce paths. - * - * @param choice The choice - * @param l The journal - */ - protected static void checkForAmbiguity(Choice choice, Journal l) { - // Confirm each path has distinct initial interactions - java.util.List interactions=new java.util.Vector(); - - for (Block path : choice.getPaths()) { - java.util.List initial=InteractionUtil.getInitialInteractions(path); - - if (!Collections.disjoint(interactions, initial)) { - l.error(MessageFormat.format( - java.util.PropertyResourceBundle.getBundle("org.scribble.protocol.Messages"). - getString("_AMBIGUOUS_CHOICE"), initial), choice.getProperties()); - } else { - interactions.addAll(initial); - } - } - } -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/validation/rules/DefaultProtocolComponentValidator.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/validation/rules/DefaultProtocolComponentValidator.java deleted file mode 100644 index 131753f0b..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/validation/rules/DefaultProtocolComponentValidator.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.validation.rules; - -import org.scribble.protocol.validation.ProtocolComponentValidator; - -/** - * This class provides the default implementation of the protocol component - * validator, initialized with the set of rules to validate the basic syntax - * and semantics for the protocol model. - * - */ -public class DefaultProtocolComponentValidator extends ProtocolComponentValidator { - - /** - * This is the default constructor. - */ - public DefaultProtocolComponentValidator() { - getRules().add(new ChoiceValidatorRule()); - getRules().add(new InteractionValidatorRule()); - getRules().add(new IntroducesValidatorRule()); - getRules().add(new ProtocolModelValidatorRule()); - getRules().add(new ProtocolValidatorRule()); - getRules().add(new RecursionValidatorRule()); - getRules().add(new RepeatValidatorRule()); - } -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/validation/rules/InteractionValidatorRule.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/validation/rules/InteractionValidatorRule.java deleted file mode 100644 index 2d7af6c1e..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/validation/rules/InteractionValidatorRule.java +++ /dev/null @@ -1,185 +0,0 @@ -/* - * Copyright 2009 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.validation.rules; - -import java.text.MessageFormat; - -import org.scribble.common.logging.Journal; -import org.scribble.protocol.ProtocolDefinitions; -import org.scribble.protocol.model.Interaction; -import org.scribble.protocol.model.ModelObject; -import org.scribble.protocol.model.Role; -import org.scribble.protocol.model.TypeImport; -import org.scribble.protocol.model.TypeReference; -import org.scribble.protocol.util.RoleUtil; -import org.scribble.protocol.util.TypesUtil; -import org.scribble.protocol.validation.ProtocolComponentValidatorRule; -import org.scribble.protocol.validation.ProtocolValidatorContext; - -/** - * This class provides the validation rule for the Interaction - * model component. - * - */ -public class InteractionValidatorRule implements ProtocolComponentValidatorRule { - - /** - * This method determines whether the rule is applicable - * for the supplied model object. - * - * @param obj The object to check - * @return Whether the rule can be used to validate the - * supplied model object - */ - public boolean isSupported(ModelObject obj) { - return (obj.getClass() == org.scribble.protocol.model.Interaction.class); - } - - /** - * {@inheritDoc} - */ - public void validate(ProtocolValidatorContext pvc, ModelObject obj, - Journal logger) { - Interaction elem=(Interaction)obj; - - // Identify definition and whether it has a located role - Role locatedRole=null; - boolean locatedRoleUsed=false; - - if (elem.getEnclosingProtocol() != null) { - locatedRole = elem.getEnclosingProtocol().getLocatedRole(); - } - - // Check there are 'to' and 'from' roles defined - if (elem.getFromRole() == null) { - - // Check if local model and 'to' is not the same as the - // located role - if (locatedRole == null || elem.getToRoles().size() == 0 - || elem.getToRoles().contains(locatedRole)) { - - logger.error(MessageFormat.format( - java.util.PropertyResourceBundle.getBundle( - "org.scribble.protocol.Messages").getString( - "_INTERACTION_ROLE"), "from"), elem.getProperties()); - } - - if (locatedRole != null) { - locatedRoleUsed = true; - } - } else { - // Check that the role has been defined in scope - java.util.Set roles=RoleUtil.getRolesInScope(elem); - - if (!roles.contains(elem.getFromRole())) { - logger.error(MessageFormat.format( - java.util.PropertyResourceBundle.getBundle( - "org.scribble.protocol.Messages").getString( - "_UNKNOWN_ROLE"), - elem.getFromRole().getName()), - elem.getFromRole().getProperties()); - } - - // Check if 'from' role was the located role - if (locatedRole != null && elem.getFromRole().equals(locatedRole)) { - locatedRoleUsed = true; - } - } - - if (elem.getToRoles().size() == 0) { - - // Check if local model and 'from' is not the same as the - // located role - if (locatedRole == null || elem.getFromRole() == null - || locatedRole.equals(elem.getFromRole())) { - - logger.error(MessageFormat.format( - java.util.PropertyResourceBundle.getBundle( - "org.scribble.protocol.Messages").getString( - "_INTERACTION_ROLE"), "to"), elem.getProperties()); - } - - if (locatedRole != null) { - locatedRoleUsed = true; - } - } else { - // Check that the role has been defined in scope - java.util.Set roles=RoleUtil.getRolesInScope(elem); - - for (Role r : elem.getToRoles()) { - if (!roles.contains(r)) { - logger.error(MessageFormat.format( - java.util.PropertyResourceBundle.getBundle( - "org.scribble.protocol.Messages").getString( - "_UNKNOWN_ROLE"), r.getName()), r.getProperties()); - } - } - - // Check if 'to' role was the located role - if (locatedRole != null && elem.getToRoles().contains(locatedRole)) { - locatedRoleUsed = true; - - // TODO: Should the located role be the only role here? - } - } - - if (locatedRole != null && !locatedRoleUsed) { - logger.error(MessageFormat.format( - java.util.PropertyResourceBundle.getBundle( - "org.scribble.protocol.Messages").getString("_UNRELATED_TO_LOCATED_ROLE"), - locatedRole.getName()), elem.getProperties()); - } - - checkMessageType(pvc, elem, logger); - } - - protected void checkMessageType(ProtocolValidatorContext pvc, Interaction interaction, - Journal logger) { - if (interaction.getMessageSignature() != null) { - for (TypeReference tref : interaction.getMessageSignature().getTypeReferences()) { - // Check if Type Import exists - TypeImport ti=TypesUtil.getTypeImport(tref); - - if (ti == null) { - logger.error(MessageFormat.format( - java.util.PropertyResourceBundle.getBundle( - "org.scribble.protocol.Messages").getString("_NO_TYPE_IMPORT"), - tref.getName()), tref.getProperties()); - } - - // Make sure reserved word not used - String name=tref.getName().toLowerCase(); - - boolean reservedWord=false; - - for (String reserved : ProtocolDefinitions.RESERVED_WORDS) { - if (reserved.equals(name)) { - reservedWord = true; - break; - } - } - - if (reservedWord) { - logger.error(MessageFormat.format( - java.util.PropertyResourceBundle.getBundle( - "org.scribble.protocol.Messages").getString("_CANNOT_USE_RESERVED_WORD"), - tref.getName()), tref.getProperties()); - } - - } - } - } -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/validation/rules/IntroducesValidatorRule.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/validation/rules/IntroducesValidatorRule.java deleted file mode 100644 index 9575e6301..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/validation/rules/IntroducesValidatorRule.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright 2009-11 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.validation.rules; - -import java.text.MessageFormat; - -import org.scribble.common.logging.Journal; -import org.scribble.protocol.model.Introduces; -import org.scribble.protocol.model.Role; -import org.scribble.protocol.model.ModelObject; -import org.scribble.protocol.validation.ProtocolComponentValidatorRule; -import org.scribble.protocol.validation.ProtocolValidatorContext; - -/** - * This class provides the validation rule for the Introduces - * model component. - * - */ -public class IntroducesValidatorRule implements ProtocolComponentValidatorRule { - - /** - * This method determines whether the rule is applicable - * for the supplied model object. - * - * @param obj The object to check - * @return Whether the rule can be used to validate the - * supplied model object - */ - public boolean isSupported(ModelObject obj) { - return (obj.getClass() == Introduces.class); - } - - /** - * {@inheritDoc} - */ - public void validate(ProtocolValidatorContext pvc, ModelObject obj, - Journal logger) { - Introduces elem=(Introduces)obj; - - // Check whether introduced roles already exist - for (Role r : elem.getIntroducedRoles()) { - if (pvc.getState(r.getName()) != null) { - logger.error(MessageFormat.format( - java.util.PropertyResourceBundle.getBundle( - "org.scribble.protocol.Messages").getString("_NAME_ALREADY_DEFINED"), - r.getName()), r.getProperties()); - } else { - pvc.setState(r.getName(), r); - } - } - } -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/validation/rules/ProtocolModelValidatorRule.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/validation/rules/ProtocolModelValidatorRule.java deleted file mode 100644 index b835a10a3..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/validation/rules/ProtocolModelValidatorRule.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.validation.rules; - -import java.text.MessageFormat; - -import org.scribble.common.logging.CachedJournal; -import org.scribble.common.logging.Journal; -import org.scribble.protocol.model.ModelObject; -import org.scribble.protocol.model.ProtocolModel; -import org.scribble.protocol.model.Role; -import org.scribble.protocol.validation.ProtocolComponentValidatorRule; -import org.scribble.protocol.validation.ProtocolValidatorContext; - -/** - * This class provides the validation rule for the ProtocolModel - * model component. - * - */ -public class ProtocolModelValidatorRule implements ProtocolComponentValidatorRule { - - /** - * This method determines whether the rule is applicable - * for the supplied model object. - * - * @param obj The object to check - * @return Whether the rule can be used to validate the - * supplied model object - */ - public boolean isSupported(ModelObject obj) { - // Check model object is ProtocolModel and is global - return (obj.getClass() == ProtocolModel.class - && !((ProtocolModel)obj).isLocated()); - } - - /** - * {@inheritDoc} - */ - public void validate(ProtocolValidatorContext pvc, ModelObject obj, - Journal logger) { - ProtocolModel elem=(ProtocolModel)obj; - java.util.List unprojectable=new java.util.Vector(); - - for (Role role : elem.getRoles()) { - CachedJournal l=new CachedJournal(); - pvc.getProtocolProjector().project(pvc.getProtocolContext(), elem, role, l); - - if (l.hasErrors()) { - unprojectable.add(role); - - l.apply(logger, "["+role.getName()+"] "); - } - } - - if (unprojectable.size() > 0) { - String roleNames=""; - for (int i=0; i < unprojectable.size(); i++) { - if (i > 0) { - if (i == unprojectable.size()-1) { - roleNames += " & "; - } else { - roleNames += ", "; - } - } - roleNames += unprojectable.get(i).getName(); - } - - logger.error(MessageFormat.format( - java.util.PropertyResourceBundle.getBundle( - "org.scribble.protocol.Messages").getString("_UNPROJECTABLE_ROLES"), - roleNames), obj.getProperties()); - } - } -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/validation/rules/ProtocolValidatorRule.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/validation/rules/ProtocolValidatorRule.java deleted file mode 100644 index f8a52aee6..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/validation/rules/ProtocolValidatorRule.java +++ /dev/null @@ -1,354 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.validation.rules; - -import java.text.MessageFormat; - -import org.scribble.common.logging.Journal; -import org.scribble.protocol.ProtocolDefinitions; -import org.scribble.protocol.model.Activity; -import org.scribble.protocol.model.Block; -import org.scribble.protocol.model.Choice; -import org.scribble.protocol.model.DefaultVisitor; -import org.scribble.protocol.model.DirectedChoice; -import org.scribble.protocol.model.Interaction; -import org.scribble.protocol.model.Introduces; -import org.scribble.protocol.model.ParameterDefinition; -import org.scribble.protocol.model.RecBlock; -import org.scribble.protocol.model.Repeat; -import org.scribble.protocol.model.Role; -import org.scribble.protocol.model.Run; -import org.scribble.protocol.model.ModelObject; -import org.scribble.protocol.model.Protocol; -import org.scribble.protocol.validation.ProtocolComponentValidatorRule; -import org.scribble.protocol.validation.ProtocolValidatorContext; - -/** - * This class provides the validation rule for the Protocol - * model component. - * - */ -public class ProtocolValidatorRule implements ProtocolComponentValidatorRule { - - /** - * This method determines whether the rule is applicable - * for the supplied model object. - * - * @param obj The object to check - * @return Whether the rule can be used to validate the - * supplied model object - */ - public boolean isSupported(ModelObject obj) { - return (obj.getClass() == Protocol.class); - } - - /** - * {@inheritDoc} - */ - public void validate(ProtocolValidatorContext pvc, ModelObject obj, - Journal logger) { - Protocol elem=(Protocol)obj; - - // If non-located protocol, then check for connectedness - if (elem.getLocatedRole() == null) { - elem.visit(new ConnectednessVisitor(elem, logger)); - } - - // Check protocol name - if (elem.getName() != null) { - String name=elem.getName().toLowerCase(); - - boolean reservedWord=false; - - for (String reserved : ProtocolDefinitions.RESERVED_WORDS) { - if (reserved.equals(name)) { - reservedWord = true; - break; - } - } - - if (reservedWord) { - logger.error(MessageFormat.format( - java.util.PropertyResourceBundle.getBundle( - "org.scribble.protocol.Messages").getString("_CANNOT_USE_RESERVED_WORD"), - elem.getName()), elem.getProperties()); - } - } - - if (pvc != null) { - for (ParameterDefinition pd : elem.getParameterDefinitions()) { - if (pvc.getState(pd.getName()) != null) { - logger.error(MessageFormat.format( - java.util.PropertyResourceBundle.getBundle( - "org.scribble.protocol.Messages").getString("_NAME_ALREADY_DEFINED"), - pd.getName()), pd.getProperties()); - } else { - if (pd.isRole()) { - pvc.setState(pd.getName(), new Role(pd.getName())); - } else { - pvc.setState(pd.getName(), pd); - } - } - } - } - } - - /** - * This class checks for connectedness between the visited components. - * - */ - protected class ConnectednessVisitor extends DefaultVisitor { - - private Protocol _protocol=null; - private Journal _logger=null; - private java.util.Stack> _roleStack= - new java.util.Stack>(); - private java.util.Stack>> _saveStack= - new java.util.Stack>>(); - - /** - * Constructor for the connectness visitor. - * - * @param p The protocol to traverse - * @param logger The journal - */ - public ConnectednessVisitor(Protocol p, Journal logger) { - _protocol = p; - _logger = logger; - } - - /** - * This method determines whether the supplied role is already known. - * - * @param r The role - * @return Whether known - */ - protected boolean isRoleKnown(Role r) { - boolean ret=false; - - for (java.util.Set roles : _roleStack) { - if (roles.contains(r)) { - ret = true; - break; - } - } - - return (ret); - } - - /** - * This method validates the supplied activity with the supplied - * role to determine if they are connected. - * - * @param act The activity - * @param r The role - */ - protected void validate(Activity act, Role r) { - if (r != null && !isRoleKnown(r)) { - _logger.error(MessageFormat.format( - java.util.PropertyResourceBundle.getBundle( - "org.scribble.protocol.Messages").getString("_UNCONNECTED_ROLE"), - r.getName()), act.getProperties()); - } - } - - /** - * This method adds the role. - * - * @param r The role - */ - protected void addRole(Role r) { - if (!isRoleKnown(r)) { - java.util.Set roles=_roleStack.peek(); - - roles.add(r); - } - } - - /** - * This method pushes the role stack. - */ - protected void push() { - if (_roleStack == null) { - _roleStack = new java.util.Stack>(); - } - _roleStack.push(new java.util.HashSet()); - } - - /** - * This method pops the role stack. - */ - protected void pop() { - _roleStack.pop(); - } - - /** - * This method saves the current stack. - */ - protected void saveStack() { - _saveStack.push(_roleStack); - _roleStack = null; - push(); - } - - /** - * This method restores the stack. - */ - protected void restoreStack() { - _roleStack = _saveStack.pop(); - } - - @Override - public boolean start(Block elem) { - push(); - return true; - } - - @Override - public void end(Block elem) { - pop(); - } - - @Override - public boolean start(Choice elem) { - validate(elem, elem.getRole()); - saveStack(); - addRole(elem.getRole()); - return (true); - } - - @Override - public void end(Choice elem) { - restoreStack(); - } - - @Override - public boolean start(DirectedChoice elem) { - // Validate that the from role is already known, but - // add the from and to roles, so that the to roles - // can subsequently be used for validation - validate(elem, elem.getFromRole()); - - saveStack(); - - addRole(elem.getFromRole()); - for (Role r : elem.getToRoles()) { - addRole(r); - } - return (true); - } - - @Override - public void end(DirectedChoice elem) { - restoreStack(); - } - - @Override - public boolean start(Protocol elem) { - if (elem == _protocol) { - push(); - for (ParameterDefinition pd : elem.getParameterDefinitions()) { - if (pd.getType() == null) { - addRole(new Role(pd.getName())); - } - } - return (true); - } else { - return (false); - } - } - - @Override - public void end(Protocol elem) { - if (elem == _protocol) { - pop(); - } - } - - @Override - public boolean start(Repeat elem) { - for (Role r : elem.getRoles()) { - validate(elem, r); - } - - if (elem.getRoles().size()>0) { - saveStack(); - } - - for (Role r : elem.getRoles()) { - addRole(r); - } - return (true); - } - - @Override - public void end(Repeat elem) { - if (elem.getRoles().size()>0) { - restoreStack(); - } - } - - @Override - public boolean start(RecBlock elem) { - push(); - return (true); - } - - @Override - public void end(RecBlock elem) { - pop(); - } - - @Override - public void accept(Run elem) { - - /* SCRIBBLE-140 - run parameters should not be validated, but - * possibly the ran protocol's first activty should be validated - * - for (Parameter p : elem.getParameters()) { - validate(elem, new Role(p.getName())); - } - */ - - if (elem.getFromRole() != null) { - validate(elem, elem.getFromRole()); - } - } - - @Override - public void accept(Interaction elem) { - // Validate that the from role is already known, but - // add the from and to roles, so that the to roles - // can subsequently be used for validation - validate(elem, elem.getFromRole()); - - addRole(elem.getFromRole()); - for (Role r : elem.getToRoles()) { - addRole(r); - } - } - - @Override - public void accept(Introduces elem) { - validate(elem, elem.getIntroducer()); - addRole(elem.getIntroducer()); - for (Role r : elem.getIntroducedRoles()) { - addRole(r); - } - } - - } -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/validation/rules/RecursionValidatorRule.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/validation/rules/RecursionValidatorRule.java deleted file mode 100644 index c04930a7b..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/validation/rules/RecursionValidatorRule.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.validation.rules; - -import java.text.MessageFormat; - -import org.scribble.common.logging.Journal; -import org.scribble.protocol.model.ModelObject; -import org.scribble.protocol.model.Protocol; -import org.scribble.protocol.model.RecBlock; -import org.scribble.protocol.model.Recursion; -import org.scribble.protocol.validation.ProtocolComponentValidatorRule; -import org.scribble.protocol.validation.ProtocolValidatorContext; - -/** - * This class provides the validation rule for the Recursion - * model component. - * - */ -public class RecursionValidatorRule implements ProtocolComponentValidatorRule { - - /** - * This method determines whether the rule is applicable - * for the supplied model object. - * - * @param obj The object to check - * @return Whether the rule can be used to validate the - * supplied model object - */ - public boolean isSupported(ModelObject obj) { - return (obj.getClass() == org.scribble.protocol.model.Recursion.class); - } - - /** - * {@inheritDoc} - */ - public void validate(ProtocolValidatorContext pvc, ModelObject obj, - Journal logger) { - Recursion elem=(Recursion)obj; - ModelObject act=elem.getParent(); - - if (elem.getLabel() != null) { - boolean found=false; - - while (!found && act != null && !(act instanceof Protocol)) { - - if (act instanceof RecBlock && ((RecBlock)act).getLabel() != null - && ((RecBlock)act).getLabel().equals(elem.getLabel())) { - found = true; - } - - act = act.getParent(); - } - - if (!found) { - logger.error(MessageFormat.format( - java.util.PropertyResourceBundle.getBundle("org.scribble.protocol.Messages").getString("_NO_ENCLOSING_RECUR"), - elem.getLabel()), obj.getProperties()); - } - } - } -} diff --git a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/validation/rules/RepeatValidatorRule.java b/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/validation/rules/RepeatValidatorRule.java deleted file mode 100644 index 3a46d633c..000000000 --- a/bundles/org.scribble.protocol/src/main/java/org/scribble/protocol/validation/rules/RepeatValidatorRule.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.validation.rules; - -import java.text.MessageFormat; - -import org.scribble.common.logging.Journal; -import org.scribble.protocol.model.ModelObject; -import org.scribble.protocol.model.Repeat; -import org.scribble.protocol.model.Role; -import org.scribble.protocol.util.RoleUtil; -import org.scribble.protocol.validation.ProtocolComponentValidatorRule; -import org.scribble.protocol.validation.ProtocolValidatorContext; - -/** - * This class provides the validation rule for the Repeat - * model component. - * - */ -public class RepeatValidatorRule implements ProtocolComponentValidatorRule { - - /** - * This method determines whether the rule is applicable - * for the supplied model object. - * - * @param obj The object to check - * @return Whether the rule can be used to validate the - * supplied model object - */ - public boolean isSupported(ModelObject obj) { - return (obj.getClass() == org.scribble.protocol.model.Repeat.class); - } - - /** - * {@inheritDoc} - */ - public void validate(ProtocolValidatorContext pvc, ModelObject obj, - Journal logger) { - Repeat elem=(Repeat)obj; - - // Check that the role has been defined in scope - java.util.Set roles=RoleUtil.getRolesInScope(elem); - - for (Role role : elem.getRoles()) { - if (!roles.contains(role)) { - logger.error(MessageFormat.format( - java.util.PropertyResourceBundle.getBundle("org.scribble.protocol.Messages").getString("_UNKNOWN_ROLE"), - role.getName()), obj.getProperties()); - } - } - } -} diff --git a/bundles/org.scribble.protocol/src/main/resources/org/scribble/protocol/Messages.properties b/bundles/org.scribble.protocol/src/main/resources/org/scribble/protocol/Messages.properties deleted file mode 100644 index 28c2fcffc..000000000 --- a/bundles/org.scribble.protocol/src/main/resources/org/scribble/protocol/Messages.properties +++ /dev/null @@ -1,35 +0,0 @@ -#/* -# * Copyright 2009-10 Scribble.org -# * -# * 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 -# * -# * http://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. -# * -# */ - -# Export messages -_EXPORT_FAILED=Export failed due to: {0} - -# Validation rule messages -_AMBIGUOUS_CHOICE=Choice is ambiguous, multiple paths have a common interaction(s) ''{0}'' -_CANNOT_USE_RESERVED_WORD= Name ''{0}'' is a reserved word -_EXISTING_DECLARATION=Declaration already exists for name ''{0}'' -_NO_ENCLOSING_RECUR=No enclosing block found with label ''{0}'' -_NO_TYPE_IMPORT=Import statement does not exist for type ''{0}'' -_NOT_FOUND_BOUND_DECLARATION=Bound declaration ''{0}'' not found in definition ''{1}'' -_NOT_FOUND_REFERENCE=Definition ''{0}'' of type ''{1}'' could not be found -_INTERACTION_ROLE=Interaction needs to define a ''{0}'' role -_NAME_ALREADY_DEFINED=Name ''{0}'' has already been declared -_RAISED_TYPE_NOT_CAUGHT=Raised type ''{0}'' is not caught within the enclosing definition -_UNKNOWN_ROLE=Unknown role ''{0}'' -_UNCONNECTED_ROLE=Activity at role ''{0}'' is not connected to preceding activities -_UNPROJECTABLE_ROLES=Role(s) ''{0}'' cannot be projected -_UNRELATED_TO_LOCATED_ROLE=Unrelated to located role ''{0}'' diff --git a/bundles/org.scribble.protocol/src/test/java/org/scribble/protocol/DefaultProtocolToolsTest.java b/bundles/org.scribble.protocol/src/test/java/org/scribble/protocol/DefaultProtocolToolsTest.java deleted file mode 100644 index 736f064cb..000000000 --- a/bundles/org.scribble.protocol/src/test/java/org/scribble/protocol/DefaultProtocolToolsTest.java +++ /dev/null @@ -1,176 +0,0 @@ -/* - * Copyright 2009-11 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol; - - -import static org.junit.Assert.*; - -import java.io.IOException; - -import org.scribble.common.logging.CachedJournal; -import org.scribble.common.logging.Journal; -import org.scribble.common.resource.Content; -import org.scribble.common.resource.DefaultResourceLocator; -import org.scribble.protocol.model.ProtocolImport; -import org.scribble.protocol.model.ProtocolImportList; -import org.scribble.protocol.model.ProtocolModel; -import org.scribble.protocol.parser.DefaultProtocolParserManager; -import org.scribble.protocol.parser.ProtocolParserManager; - -/** - * Test for DefaultProtocolTools. - * - */ -public class DefaultProtocolToolsTest { - - private static final String CONTENT_PROPERTY = "content"; - - @org.junit.Test - public void testGetProtocolModelSameFolder() { - String refFile="Ref1.spr"; - - java.net.URL url=ClassLoader.getSystemResource("context"); - - if (url == null) { - fail("Couldn't find base directory"); - } - - ProtocolParserManager parserManager=new TestProtocolParserManager(); - - DefaultProtocolContext context=new DefaultProtocolContext(parserManager, - new DefaultResourceLocator(new java.io.File(url.getFile()))); - - ProtocolImportList imports=new ProtocolImportList(); - - ProtocolImport pi=new ProtocolImport(); - pi.setName("Ref1"); - pi.setLocation(refFile); - - imports.getProtocolImports().add(pi); - - CachedJournal journal=new CachedJournal(); - - ProtocolModel pm=context.getProtocolModel(pi, journal); - - if (journal.hasErrors()) { - fail("Journal has reported errors"); - } - - if (pm == null) { - fail("Protocol model not returned"); - } - - if (pm.getProperties().get(CONTENT_PROPERTY).equals(pi.getName()) == false) { - fail("Protocol model content property not as expected '"+pm.getProperties().get(CONTENT_PROPERTY)+ - "', expecting: "+pi.getName()); - } - } - - @org.junit.Test - public void testGetProtocolModelRelativeFolder() { - String refFile="../subref/Ref2.spr"; - - java.net.URL url=ClassLoader.getSystemResource("context/submain"); - - if (url == null) { - fail("Couldn't find base directory"); - } - - ProtocolParserManager parserManager=new TestProtocolParserManager(); - - DefaultProtocolContext context=new DefaultProtocolContext(parserManager, - new DefaultResourceLocator(new java.io.File(url.getFile()))); - - ProtocolImportList imports=new ProtocolImportList(); - - ProtocolImport pi=new ProtocolImport(); - pi.setName("Ref2"); - pi.setLocation(refFile); - - imports.getProtocolImports().add(pi); - - CachedJournal journal=new CachedJournal(); - - ProtocolModel pm=context.getProtocolModel(pi, journal); - - if (journal.hasErrors()) { - fail("Journal has reported errors"); - } - - if (pm == null) { - fail("Protocol model not returned"); - } - - if (pm.getProperties().get(CONTENT_PROPERTY).equals(pi.getName()) == false) { - fail("Protocol model content property not as expected '"+pm.getProperties().get(CONTENT_PROPERTY)+ - "', expecting: "+pi.getName()); - } - } - - @org.junit.Test - @org.junit.Ignore - public void testGetProtocolModelScribbleURL() { - ProtocolParserManager parserManager=new TestProtocolParserManager(); - - DefaultProtocolContext context=new DefaultProtocolContext(parserManager, - new DefaultResourceLocator(null)); - - ProtocolImportList imports=new ProtocolImportList(); - - ProtocolImport pi=new ProtocolImport(); - pi.setName("Ref1"); - pi.setLocation("http://www.scribble.org"); - - imports.getProtocolImports().add(pi); - - CachedJournal journal=new CachedJournal(); - - ProtocolModel pm=context.getProtocolModel(pi, journal); - - if (journal.hasErrors()) { - fail("Journal has reported errors"); - } - - if (pm == null) { - fail("Protocol model not returned"); - } - - if (((String)pm.getProperties().get(CONTENT_PROPERTY)). - contains("Scribble - JBoss Community") == false) { - fail("Protocol model content property did not contain scribble home page"); - } - } - - public class TestProtocolParserManager extends DefaultProtocolParserManager { - - @Override - public ProtocolModel parse(ProtocolContext context, Content content, Journal journal) - throws IOException { - java.io.InputStream is=content.getInputStream(); - byte[] b=new byte[is.available()]; - - is.read(b); - - is.close(); - - ProtocolModel ret=new ProtocolModel(); - ret.getProperties().put(CONTENT_PROPERTY, new String(b)); - - return (ret); - } - - } -} diff --git a/bundles/org.scribble.protocol/src/test/java/org/scribble/protocol/export/text/TextExportVisitorTest.java b/bundles/org.scribble.protocol/src/test/java/org/scribble/protocol/export/text/TextExportVisitorTest.java deleted file mode 100644 index d03d3a6ca..000000000 --- a/bundles/org.scribble.protocol/src/test/java/org/scribble/protocol/export/text/TextExportVisitorTest.java +++ /dev/null @@ -1,1903 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.export.text; - -import org.scribble.common.logging.CachedJournal; -import org.scribble.common.model.DefaultAnnotation; -import org.scribble.protocol.model.*; - -import static org.junit.Assert.*; - -public class TextExportVisitorTest { - - private static final String RECUR_LABEL_TRANSACTION = "Transaction"; - - @org.junit.Test - public void testImportTypeSingle() { - - TypeImportList elem=new TypeImportList(); - TypeImport t=new TypeImport(); - t.setName("testname"); - elem.getTypeImports().add(t); - - java.io.ByteArrayOutputStream baos=new java.io.ByteArrayOutputStream(); - - Visitor visitor=new TextProtocolExporterVisitor(new CachedJournal(), baos); - - elem.visit(visitor); - - try { - baos.close(); - } catch (Exception e) { - fail("Failed to close stream"); - } - - String str=baos.toString(); - - String expected="import "+t.getName()+";\r\n"; - - if (str.equals(expected) == false) { - fail("Expected:\r\n"+expected+"\r\nGot:\r\n"+str); - } - } - - @org.junit.Test - public void testImportTypeSingleWithAnnotation() { - - TypeImportList elem=new TypeImportList(); - TypeImport t=new TypeImport(); - t.setName("testname"); - elem.getTypeImports().add(t); - - DefaultAnnotation annotation1=new DefaultAnnotation("annotation1"); - elem.getAnnotations().add(annotation1); - - DefaultAnnotation annotation2=new DefaultAnnotation("annotation2"); - elem.getAnnotations().add(annotation2); - - java.io.ByteArrayOutputStream baos=new java.io.ByteArrayOutputStream(); - - Visitor visitor=new TextProtocolExporterVisitor(new CachedJournal(), baos); - - elem.visit(visitor); - - try { - baos.close(); - } catch (Exception e) { - fail("Failed to close stream"); - } - - String str=baos.toString(); - - String expected="[["+annotation1.toString()+"]]\r\n"+ - "[["+annotation2.toString()+"]]\r\n"+ - "import "+t.getName()+";\r\n"; - - if (str.equals(expected) == false) { - fail("Expected:\r\n"+expected+"\r\nGot:\r\n"+str); - } - } - - @org.junit.Test - public void testImportTypeMultiple() { - - TypeImportList elem=new TypeImportList(); - TypeImport t1=new TypeImport(); - t1.setName("testname1"); - elem.getTypeImports().add(t1); - - TypeImport t2=new TypeImport(); - t2.setName("testname2"); - elem.getTypeImports().add(t2); - - java.io.ByteArrayOutputStream baos=new java.io.ByteArrayOutputStream(); - - Visitor visitor=new TextProtocolExporterVisitor(new CachedJournal(), baos); - - elem.visit(visitor); - - try { - baos.close(); - } catch (Exception e) { - fail("Failed to close stream"); - } - - String str=baos.toString(); - - String expected="import "+t1.getName()+", "+t2.getName()+";\r\n"; - - if (str.equals(expected) == false) { - fail("Expected:\r\n"+expected+"\r\nGot:\r\n"+str); - } - } - - @org.junit.Test - public void testImportProtocolSingle() { - - ProtocolImportList elem=new ProtocolImportList(); - ProtocolImport t=new ProtocolImport(); - t.setName("testname"); - t.setLocation("testlocation"); - elem.getProtocolImports().add(t); - - java.io.ByteArrayOutputStream baos=new java.io.ByteArrayOutputStream(); - - Visitor visitor=new TextProtocolExporterVisitor(new CachedJournal(), baos); - - elem.visit(visitor); - - try { - baos.close(); - } catch (Exception e) { - fail("Failed to close stream"); - } - - String str=baos.toString(); - - String expected="import protocol "+t.getName()+" from \"testlocation\";\r\n"; - - if (str.equals(expected) == false) { - fail("Expected:\r\n"+expected+"\r\nGot:\r\n"+str); - } - } - - @org.junit.Test - public void testImportProtocolSingleWithAnnotation() { - - ProtocolImportList elem=new ProtocolImportList(); - ProtocolImport t=new ProtocolImport(); - t.setName("testname"); - t.setLocation("testlocation"); - elem.getProtocolImports().add(t); - - DefaultAnnotation annotation1=new DefaultAnnotation("annotation1"); - elem.getAnnotations().add(annotation1); - - DefaultAnnotation annotation2=new DefaultAnnotation("annotation2"); - elem.getAnnotations().add(annotation2); - - java.io.ByteArrayOutputStream baos=new java.io.ByteArrayOutputStream(); - - Visitor visitor=new TextProtocolExporterVisitor(new CachedJournal(), baos); - - elem.visit(visitor); - - try { - baos.close(); - } catch (Exception e) { - fail("Failed to close stream"); - } - - String str=baos.toString(); - - String expected="[["+annotation1.toString()+"]]\r\n"+ - "[["+annotation2.toString()+"]]\r\n"+ - "import protocol "+t.getName()+" from \"testlocation\";\r\n"; - - if (str.equals(expected) == false) { - fail("Expected:\r\n"+expected+"\r\nGot:\r\n"+str); - } - } - - @org.junit.Test - public void testImportProtocolMultiple() { - - ProtocolImportList elem=new ProtocolImportList(); - ProtocolImport t1=new ProtocolImport(); - t1.setName("testname1"); - t1.setLocation("testlocation1"); - elem.getProtocolImports().add(t1); - - ProtocolImport t2=new ProtocolImport(); - t2.setName("testname2"); - t2.setLocation("testlocation1"); - elem.getProtocolImports().add(t2); - - java.io.ByteArrayOutputStream baos=new java.io.ByteArrayOutputStream(); - - Visitor visitor=new TextProtocolExporterVisitor(new CachedJournal(), baos); - - elem.visit(visitor); - - try { - baos.close(); - } catch (Exception e) { - fail("Failed to close stream"); - } - - String str=baos.toString(); - - String expected="import protocol "+t1.getName()+" from \""+t1.getLocation()+ - "\", "+t2.getName()+" from \""+t2.getLocation()+"\";\r\n"; - - if (str.equals(expected) == false) { - fail("Expected:\r\n"+expected+"\r\nGot:\r\n"+str); - } - } - - @org.junit.Test - public void testProtocol() { - - Protocol elem=new Protocol(); - elem.setName("test"); - - java.io.ByteArrayOutputStream baos=new java.io.ByteArrayOutputStream(); - - Visitor visitor=new TextProtocolExporterVisitor(new CachedJournal(), baos); - - elem.visit(visitor); - - try { - baos.close(); - } catch (Exception e) { - fail("Failed to close stream"); - } - - String str=baos.toString(); - - String expected="protocol "+elem.getName()+" {\r\n}\r\n"; - - if (str.equals(expected) == false) { - fail("Expected:\r\n"+expected+"\r\nGot:\r\n"+str); - } - } - - @org.junit.Test - public void testProtocolWithAnnotation() { - - Protocol elem=new Protocol(); - elem.setName("test"); - - DefaultAnnotation annotation1=new DefaultAnnotation("annotation1"); - elem.getAnnotations().add(annotation1); - - DefaultAnnotation annotation2=new DefaultAnnotation("annotation2"); - elem.getAnnotations().add(annotation2); - - java.io.ByteArrayOutputStream baos=new java.io.ByteArrayOutputStream(); - - Visitor visitor=new TextProtocolExporterVisitor(new CachedJournal(), baos); - - elem.visit(visitor); - - try { - baos.close(); - } catch (Exception e) { - fail("Failed to close stream"); - } - - String str=baos.toString(); - - String expected="[["+annotation1.toString()+"]]\r\n"+ - "[["+annotation2.toString()+"]]\r\n"+ - "protocol "+elem.getName()+" {\r\n}\r\n"; - - if (str.equals(expected) == false) { - fail("Expected:\r\n"+expected+"\r\nGot:\r\n"+str); - } - } - - @org.junit.Test - public void testProtocolLocated() { - - Protocol elem=new Protocol(); - elem.setName("test"); - - Role p1=new Role(); - p1.setName("p1"); - - elem.setLocatedRole(p1); - - java.io.ByteArrayOutputStream baos=new java.io.ByteArrayOutputStream(); - - Visitor visitor=new TextProtocolExporterVisitor(new CachedJournal(), baos); - - elem.visit(visitor); - - try { - baos.close(); - } catch (Exception e) { - fail("Failed to close stream"); - } - - String str=baos.toString(); - - String expected="protocol "+elem.getName()+" at "+elem.getLocatedRole().getName()+" {\r\n}\r\n"; - - if (str.equals(expected) == false) { - fail("Expected:\r\n"+expected+"\r\nGot:\r\n"+str); - } - } - - @org.junit.Test - public void testRoleList() { - - Introduces elem=new Introduces(); - - Role i1=new Role(); - i1.setName("I1"); - - elem.setIntroducer(i1); - - Role p1=new Role(); - p1.setName("P1"); - - elem.getIntroducedRoles().add(p1); - - Role p2=new Role(); - p2.setName("P2"); - - elem.getIntroducedRoles().add(p2); - - java.io.ByteArrayOutputStream baos=new java.io.ByteArrayOutputStream(); - - Visitor visitor=new TextProtocolExporterVisitor(new CachedJournal(), baos); - - elem.visit(visitor); - - try { - baos.close(); - } catch (Exception e) { - fail("Failed to close stream"); - } - - String str=baos.toString(); - - String expected=i1.getName()+" introduces "+p1.getName()+", "+p2.getName()+";\r\n"; - - if (str.equals(expected) == false) { - fail("Expected:\r\n"+expected+"\r\nGot:\r\n"+str); - } - } - - @org.junit.Test - public void testRoleListWithAnnotation() { - - Introduces elem=new Introduces(); - - Role i1=new Role(); - i1.setName("I1"); - - elem.setIntroducer(i1); - - Role p1=new Role(); - p1.setName("P1"); - - elem.getIntroducedRoles().add(p1); - - Role p2=new Role(); - p2.setName("P2"); - - elem.getIntroducedRoles().add(p2); - - DefaultAnnotation annotation1=new DefaultAnnotation("annotation1"); - elem.getAnnotations().add(annotation1); - - DefaultAnnotation annotation2=new DefaultAnnotation("annotation2"); - elem.getAnnotations().add(annotation2); - - java.io.ByteArrayOutputStream baos=new java.io.ByteArrayOutputStream(); - - Visitor visitor=new TextProtocolExporterVisitor(new CachedJournal(), baos); - - elem.visit(visitor); - - try { - baos.close(); - } catch (Exception e) { - fail("Failed to close stream"); - } - - String str=baos.toString(); - - String expected="[["+annotation1.toString()+"]]\r\n"+ - "[["+annotation2.toString()+"]]\r\n"+ - i1.getName()+" introduces "+p1.getName()+", "+p2.getName()+";\r\n"; - - if (str.equals(expected) == false) { - fail("Expected:\r\n"+expected+"\r\nGot:\r\n"+str); - } - } - - @org.junit.Test - public void testInteraction() { - - Interaction elem=new Interaction(); - - Role p1=new Role(); - p1.setName("A"); - - elem.setFromRole(p1); - - Role p2=new Role(); - p2.setName("B"); - - elem.getToRoles().add(p2); - - TypeReference ref1=new TypeReference(); - ref1.setName("Type1"); - - MessageSignature sig1=new MessageSignature(); - sig1.getTypeReferences().add(ref1); - - elem.setMessageSignature(sig1); - - java.io.ByteArrayOutputStream baos=new java.io.ByteArrayOutputStream(); - - Visitor visitor=new TextProtocolExporterVisitor(new CachedJournal(), baos); - - elem.visit(visitor); - - try { - baos.close(); - } catch (Exception e) { - fail("Failed to close stream"); - } - - String str=baos.toString(); - - String expected=ref1.getName()+" from "+p1.getName()+" to "+p2.getName()+";\r\n"; - - if (str.equals(expected) == false) { - fail("Expected:\r\n"+expected+"\r\nGot:\r\n"+str); - } - } - - @org.junit.Test - public void testInteractionWithAnnotation() { - - Interaction elem=new Interaction(); - - Role p1=new Role(); - p1.setName("A"); - - elem.setFromRole(p1); - - Role p2=new Role(); - p2.setName("B"); - - elem.getToRoles().add(p2); - - TypeReference ref1=new TypeReference(); - ref1.setName("Type1"); - - MessageSignature sig1=new MessageSignature(); - sig1.getTypeReferences().add(ref1); - - elem.setMessageSignature(sig1); - - DefaultAnnotation annotation1=new DefaultAnnotation("annotation1"); - elem.getAnnotations().add(annotation1); - - DefaultAnnotation annotation2=new DefaultAnnotation("annotation2"); - elem.getAnnotations().add(annotation2); - - java.io.ByteArrayOutputStream baos=new java.io.ByteArrayOutputStream(); - - Visitor visitor=new TextProtocolExporterVisitor(new CachedJournal(), baos); - - elem.visit(visitor); - - try { - baos.close(); - } catch (Exception e) { - fail("Failed to close stream"); - } - - String str=baos.toString(); - - String expected="[["+annotation1.toString()+"]]\r\n"+ - "[["+annotation2.toString()+"]]\r\n"+ - ref1.getName()+" from "+p1.getName()+" to "+p2.getName()+";\r\n"; - - if (str.equals(expected) == false) { - fail("Expected:\r\n"+expected+"\r\nGot:\r\n"+str); - } - } - - @org.junit.Test - public void testInteractionSend() { - - Interaction elem=new Interaction(); - - Role p1=new Role(); - p1.setName("A"); - - elem.setFromRole(p1); - - TypeReference ref1=new TypeReference(); - ref1.setName("Type1"); - - MessageSignature sig1=new MessageSignature(); - sig1.getTypeReferences().add(ref1); - - elem.setMessageSignature(sig1); - - java.io.ByteArrayOutputStream baos=new java.io.ByteArrayOutputStream(); - - Visitor visitor=new TextProtocolExporterVisitor(new CachedJournal(), baos); - - elem.visit(visitor); - - try { - baos.close(); - } catch (Exception e) { - fail("Failed to close stream"); - } - - String str=baos.toString(); - - String expected=ref1.getName()+" from "+p1.getName()+";\r\n"; - - if (str.equals(expected) == false) { - fail("Expected:\r\n"+expected+"\r\nGot:\r\n"+str); - } - } - - @org.junit.Test - public void testInteractionReceive() { - - Interaction elem=new Interaction(); - - Role p2=new Role(); - p2.setName("B"); - - elem.getToRoles().add(p2); - - TypeReference ref1=new TypeReference(); - ref1.setName("Type1"); - - MessageSignature sig1=new MessageSignature(); - sig1.getTypeReferences().add(ref1); - - elem.setMessageSignature(sig1); - - java.io.ByteArrayOutputStream baos=new java.io.ByteArrayOutputStream(); - - Visitor visitor=new TextProtocolExporterVisitor(new CachedJournal(), baos); - - elem.visit(visitor); - - try { - baos.close(); - } catch (Exception e) { - fail("Failed to close stream"); - } - - String str=baos.toString(); - - String expected=ref1.getName()+" to "+p2.getName()+";\r\n"; - - if (str.equals(expected) == false) { - fail("Expected:\r\n"+expected+"\r\nGot:\r\n"+str); - } - } - - @org.junit.Test - public void testChoice() { - - Choice elem=new Choice(); - - Role p1=new Role(); - p1.setName("A"); - - elem.setRole(p1); - - Role p2=new Role(); - p2.setName("B"); - - Interaction i1=new Interaction(); - i1.setFromRole(p1); - i1.getToRoles().add(p2); - - Block b1=new Block(); - b1.add(i1); - elem.getPaths().add(b1); - - TypeReference ref1=new TypeReference(); - ref1.setName("Type1"); - - MessageSignature sig1=new MessageSignature(); - sig1.getTypeReferences().add(ref1); - - i1.setMessageSignature(sig1); - - Interaction i2=new Interaction(); - i2.setFromRole(p1); - i2.getToRoles().add(p2); - - Block b2=new Block(); - b2.add(i2); - - elem.getPaths().add(b2); - - TypeReference ref2=new TypeReference(); - ref2.setName("Type2"); - - MessageSignature sig2=new MessageSignature(); - sig2.getTypeReferences().add(ref2); - - i2.setMessageSignature(sig2); - - java.io.ByteArrayOutputStream baos=new java.io.ByteArrayOutputStream(); - - Visitor visitor=new TextProtocolExporterVisitor(new CachedJournal(), baos); - - elem.visit(visitor); - - try { - baos.close(); - } catch (Exception e) { - fail("Failed to close stream"); - } - - String str=baos.toString(); - - String expected="choice at "+p1.getName()+" {\r\n"+ - "\t"+ref1.getName()+" from "+p1.getName()+" to "+p2.getName()+";\r\n"+ - "} or {\r\n"+ - "\t"+ref2.getName()+" from "+p1.getName()+" to "+p2.getName()+";\r\n"+ - "}\r\n"; - - if (str.equals(expected) == false) { - fail("Expected:\r\n"+expected+"\r\nGot:\r\n"+str); - } - } - - @org.junit.Test - public void testChoiceWithAnnotation() { - - Choice elem=new Choice(); - - Role p1=new Role(); - p1.setName("A"); - - elem.setRole(p1); - - Role p2=new Role(); - p2.setName("B"); - - Interaction i1=new Interaction(); - i1.setFromRole(p1); - i1.getToRoles().add(p2); - - Block b1=new Block(); - b1.add(i1); - elem.getPaths().add(b1); - - TypeReference ref1=new TypeReference(); - ref1.setName("Type1"); - - MessageSignature sig1=new MessageSignature(); - sig1.getTypeReferences().add(ref1); - - i1.setMessageSignature(sig1); - - Interaction i2=new Interaction(); - i2.setFromRole(p1); - i2.getToRoles().add(p2); - - Block b2=new Block(); - b2.add(i2); - - elem.getPaths().add(b2); - - TypeReference ref2=new TypeReference(); - ref2.setName("Type2"); - - MessageSignature sig2=new MessageSignature(); - sig2.getTypeReferences().add(ref2); - - i2.setMessageSignature(sig2); - - DefaultAnnotation annotation1=new DefaultAnnotation("annotation1"); - elem.getAnnotations().add(annotation1); - - DefaultAnnotation annotation2=new DefaultAnnotation("annotation2"); - elem.getAnnotations().add(annotation2); - - java.io.ByteArrayOutputStream baos=new java.io.ByteArrayOutputStream(); - - Visitor visitor=new TextProtocolExporterVisitor(new CachedJournal(), baos); - - elem.visit(visitor); - - try { - baos.close(); - } catch (Exception e) { - fail("Failed to close stream"); - } - - String str=baos.toString(); - - String expected="[["+annotation1.toString()+"]]\r\n"+ - "[["+annotation2.toString()+"]]\r\n"+ - "choice at "+p1.getName()+" {\r\n"+ - "\t"+ref1.getName()+" from "+p1.getName()+" to "+p2.getName()+";\r\n"+ - "} or {\r\n"+ - "\t"+ref2.getName()+" from "+p1.getName()+" to "+p2.getName()+";\r\n"+ - "}\r\n"; - - if (str.equals(expected) == false) { - fail("Expected:\r\n"+expected+"\r\nGot:\r\n"+str); - } - } - - @org.junit.Test - public void testChoiceSend() { - - Choice elem=new Choice(); - - Role p1=new Role(); - p1.setName("A"); - - elem.setRole(p1); - - Interaction i1=new Interaction(); - i1.setFromRole(p1); - - Block b1=new Block(); - b1.add(i1); - elem.getPaths().add(b1); - - TypeReference ref1=new TypeReference(); - ref1.setName("Type1"); - - MessageSignature sig1=new MessageSignature(); - sig1.getTypeReferences().add(ref1); - - i1.setMessageSignature(sig1); - - Interaction i2=new Interaction(); - i2.setFromRole(p1); - - Block b2=new Block(); - b2.add(i2); - - elem.getPaths().add(b2); - - TypeReference ref2=new TypeReference(); - ref2.setName("Type2"); - - MessageSignature sig2=new MessageSignature(); - sig2.getTypeReferences().add(ref2); - - i2.setMessageSignature(sig2); - - java.io.ByteArrayOutputStream baos=new java.io.ByteArrayOutputStream(); - - Visitor visitor=new TextProtocolExporterVisitor(new CachedJournal(), baos); - - elem.visit(visitor); - - try { - baos.close(); - } catch (Exception e) { - fail("Failed to close stream"); - } - - String str=baos.toString(); - - String expected="choice at "+p1.getName()+" {\r\n"+ - "\t"+ref1.getName()+" from "+p1.getName()+";\r\n"+ - "} or {\r\n"+ - "\t"+ref2.getName()+" from "+p1.getName()+";\r\n"+ - "}\r\n"; - - if (str.equals(expected) == false) { - fail("Expected:\r\n"+expected+"\r\nGot:\r\n"+str); - } - } - - @org.junit.Test - public void testChoiceReceive() { - - Choice elem=new Choice(); - - Role p2=new Role(); - p2.setName("B"); - - Interaction i1=new Interaction(); - i1.getToRoles().add(p2); - - Block b1=new Block(); - b1.add(i1); - elem.getPaths().add(b1); - - TypeReference ref1=new TypeReference(); - ref1.setName("Type1"); - - MessageSignature sig1=new MessageSignature(); - sig1.getTypeReferences().add(ref1); - - i1.setMessageSignature(sig1); - - Interaction i2=new Interaction(); - i2.getToRoles().add(p2); - - Block b2=new Block(); - b2.add(i2); - - elem.getPaths().add(b2); - - TypeReference ref2=new TypeReference(); - ref2.setName("Type2"); - - MessageSignature sig2=new MessageSignature(); - sig2.getTypeReferences().add(ref2); - - i2.setMessageSignature(sig2); - - java.io.ByteArrayOutputStream baos=new java.io.ByteArrayOutputStream(); - - Visitor visitor=new TextProtocolExporterVisitor(new CachedJournal(), baos); - - elem.visit(visitor); - - try { - baos.close(); - } catch (Exception e) { - fail("Failed to close stream"); - } - - String str=baos.toString(); - - String expected="choice {\r\n"+ - "\t"+ref1.getName()+" to "+p2.getName()+";\r\n"+ - "} or {\r\n"+ - "\t"+ref2.getName()+" to "+p2.getName()+";\r\n"+ - "}\r\n"; - - if (str.equals(expected) == false) { - fail("Expected:\r\n"+expected+"\r\nGot:\r\n"+str); - } - } - - @org.junit.Test - public void testRepeat() { - - Repeat elem=new Repeat(); - - Role p1=new Role(); - p1.setName("A"); - - elem.getRoles().add(p1); - - Role p2=new Role(); - p2.setName("B"); - - elem.getRoles().add(p2); - - TypeReference ref1=new TypeReference(); - ref1.setName("Type1"); - - MessageSignature sig1=new MessageSignature(); - sig1.getTypeReferences().add(ref1); - - Interaction i1=new Interaction(); - - i1.setMessageSignature(sig1); - i1.setFromRole(p1); - i1.getToRoles().add(p2); - - elem.getBlock().add(i1); - - java.io.ByteArrayOutputStream baos=new java.io.ByteArrayOutputStream(); - - Visitor visitor=new TextProtocolExporterVisitor(new CachedJournal(), baos); - - elem.visit(visitor); - - try { - baos.close(); - } catch (Exception e) { - fail("Failed to close stream"); - } - - String str=baos.toString(); - - String expected="repeat at "+p1.getName()+","+p2.getName()+" {\r\n"+ - "\t"+ref1.getName()+" from "+p1.getName()+" to "+p2.getName()+";\r\n}\r\n"; - - if (str.equals(expected) == false) { - fail("Expected:\r\n"+expected+"\r\nGot:\r\n"+str); - } - } - - @org.junit.Test - public void testRepeatWithAnnotation() { - - Repeat elem=new Repeat(); - - Role p1=new Role(); - p1.setName("A"); - - elem.getRoles().add(p1); - - Role p2=new Role(); - p2.setName("B"); - - elem.getRoles().add(p2); - - TypeReference ref1=new TypeReference(); - ref1.setName("Type1"); - - MessageSignature sig1=new MessageSignature(); - sig1.getTypeReferences().add(ref1); - - Interaction i1=new Interaction(); - - i1.setMessageSignature(sig1); - i1.setFromRole(p1); - i1.getToRoles().add(p2); - - elem.getBlock().add(i1); - - DefaultAnnotation annotation1=new DefaultAnnotation("annotation1"); - elem.getAnnotations().add(annotation1); - - DefaultAnnotation annotation2=new DefaultAnnotation("annotation2"); - elem.getAnnotations().add(annotation2); - - java.io.ByteArrayOutputStream baos=new java.io.ByteArrayOutputStream(); - - Visitor visitor=new TextProtocolExporterVisitor(new CachedJournal(), baos); - - elem.visit(visitor); - - try { - baos.close(); - } catch (Exception e) { - fail("Failed to close stream"); - } - - String str=baos.toString(); - - String expected="[["+annotation1.toString()+"]]\r\n"+ - "[["+annotation2.toString()+"]]\r\n"+ - "repeat at "+p1.getName()+","+p2.getName()+" {\r\n"+ - "\t"+ref1.getName()+" from "+p1.getName()+" to "+p2.getName()+";\r\n}\r\n"; - - if (str.equals(expected) == false) { - fail("Expected:\r\n"+expected+"\r\nGot:\r\n"+str); - } - } - - @org.junit.Test - public void testUnordered() { - - Unordered elem=new Unordered(); - - Role p1=new Role(); - p1.setName("A"); - - Role p2=new Role(); - p2.setName("B"); - - TypeReference ref1=new TypeReference(); - ref1.setName("Type1"); - - MessageSignature sig1=new MessageSignature(); - sig1.getTypeReferences().add(ref1); - - Interaction i1=new Interaction(); - - i1.setMessageSignature(sig1); - i1.setFromRole(p1); - i1.getToRoles().add(p2); - - elem.getBlock().add(i1); - - java.io.ByteArrayOutputStream baos=new java.io.ByteArrayOutputStream(); - - Visitor visitor=new TextProtocolExporterVisitor(new CachedJournal(), baos); - - elem.visit(visitor); - - try { - baos.close(); - } catch (Exception e) { - fail("Failed to close stream"); - } - - String str=baos.toString(); - - String expected="unordered {\r\n"+ - "\t"+ref1.getName()+" from "+p1.getName()+" to "+p2.getName()+";\r\n}\r\n"; - - if (str.equals(expected) == false) { - fail("Expected:\r\n"+expected+"\r\nGot:\r\n"+str); - } - } - - @org.junit.Test - public void testUnorderedWithAnnotation() { - - Unordered elem=new Unordered(); - - Role p1=new Role(); - p1.setName("A"); - - Role p2=new Role(); - p2.setName("B"); - - TypeReference ref1=new TypeReference(); - ref1.setName("Type1"); - - MessageSignature sig1=new MessageSignature(); - sig1.getTypeReferences().add(ref1); - - Interaction i1=new Interaction(); - - i1.setMessageSignature(sig1); - i1.setFromRole(p1); - i1.getToRoles().add(p2); - - elem.getBlock().add(i1); - - DefaultAnnotation annotation1=new DefaultAnnotation("annotation1"); - elem.getAnnotations().add(annotation1); - - DefaultAnnotation annotation2=new DefaultAnnotation("annotation2"); - elem.getAnnotations().add(annotation2); - - java.io.ByteArrayOutputStream baos=new java.io.ByteArrayOutputStream(); - - Visitor visitor=new TextProtocolExporterVisitor(new CachedJournal(), baos); - - elem.visit(visitor); - - try { - baos.close(); - } catch (Exception e) { - fail("Failed to close stream"); - } - - String str=baos.toString(); - - String expected="[["+annotation1.toString()+"]]\r\n"+ - "[["+annotation2.toString()+"]]\r\n"+ - "unordered {\r\n"+ - "\t"+ref1.getName()+" from "+p1.getName()+" to "+p2.getName()+";\r\n}\r\n"; - - if (str.equals(expected) == false) { - fail("Expected:\r\n"+expected+"\r\nGot:\r\n"+str); - } - } - - @org.junit.Test - public void testRecur() { - - RecBlock elem=new RecBlock(); - elem.setLabel(RECUR_LABEL_TRANSACTION); - - Role p1=new Role(); - p1.setName("A"); - - Role p2=new Role(); - p2.setName("B"); - - TypeReference ref1=new TypeReference(); - ref1.setName("Type1"); - - MessageSignature sig1=new MessageSignature(); - sig1.getTypeReferences().add(ref1); - - Interaction i1=new Interaction(); - - i1.setMessageSignature(sig1); - i1.setFromRole(p1); - i1.getToRoles().add(p2); - - elem.getBlock().add(i1); - - Recursion recursion=new Recursion(); - recursion.setLabel(RECUR_LABEL_TRANSACTION); - - elem.getBlock().add(recursion); - - java.io.ByteArrayOutputStream baos=new java.io.ByteArrayOutputStream(); - - Visitor visitor=new TextProtocolExporterVisitor(new CachedJournal(), baos); - - elem.visit(visitor); - - try { - baos.close(); - } catch (Exception e) { - fail("Failed to close stream"); - } - - String str=baos.toString(); - - String expected="rec "+elem.getLabel()+" {\r\n"+ - "\t"+ref1.getName()+" from "+p1.getName()+" to "+p2.getName()+";\r\n"+ - "\t"+elem.getLabel()+";\r\n}\r\n"; - - if (str.equals(expected) == false) { - fail("Expected:\r\n"+expected+"\r\nGot:\r\n"+str); - } - } - - @org.junit.Test - public void testRecurWithAnnotation() { - - RecBlock elem=new RecBlock(); - elem.setLabel(RECUR_LABEL_TRANSACTION); - - Role p1=new Role(); - p1.setName("A"); - - Role p2=new Role(); - p2.setName("B"); - - TypeReference ref1=new TypeReference(); - ref1.setName("Type1"); - - MessageSignature sig1=new MessageSignature(); - sig1.getTypeReferences().add(ref1); - - Interaction i1=new Interaction(); - - i1.setMessageSignature(sig1); - i1.setFromRole(p1); - i1.getToRoles().add(p2); - - elem.getBlock().add(i1); - - Recursion recursion=new Recursion(); - recursion.setLabel(RECUR_LABEL_TRANSACTION); - - elem.getBlock().add(recursion); - - DefaultAnnotation annotation1=new DefaultAnnotation("annotation1"); - elem.getAnnotations().add(annotation1); - - DefaultAnnotation annotation2=new DefaultAnnotation("annotation2"); - elem.getAnnotations().add(annotation2); - - java.io.ByteArrayOutputStream baos=new java.io.ByteArrayOutputStream(); - - Visitor visitor=new TextProtocolExporterVisitor(new CachedJournal(), baos); - - elem.visit(visitor); - - try { - baos.close(); - } catch (Exception e) { - fail("Failed to close stream"); - } - - String str=baos.toString(); - - String expected="[["+annotation1.toString()+"]]\r\n"+ - "[["+annotation2.toString()+"]]\r\n"+ - "rec "+elem.getLabel()+" {\r\n"+ - "\t"+ref1.getName()+" from "+p1.getName()+" to "+p2.getName()+";\r\n"+ - "\t"+elem.getLabel()+";\r\n}\r\n"; - - if (str.equals(expected) == false) { - fail("Expected:\r\n"+expected+"\r\nGot:\r\n"+str); - } - } - - @org.junit.Test - public void testRunNoBinding() { - - Run elem=new Run(); - - ProtocolReference pref=new ProtocolReference(); - pref.setName("SubProtocol"); - - elem.setProtocolReference(pref); - - java.io.ByteArrayOutputStream baos=new java.io.ByteArrayOutputStream(); - - Visitor visitor=new TextProtocolExporterVisitor(new CachedJournal(), baos); - - elem.visit(visitor); - - try { - baos.close(); - } catch (Exception e) { - fail("Failed to close stream"); - } - - String str=baos.toString(); - - String expected="run "+pref.getName()+";\r\n"; - - if (str.equals(expected) == false) { - fail("Expected:\r\n"+expected+"\r\nGot:\r\n"+str); - } - } - - @org.junit.Test - public void testRunNoBindingWithAnnotation() { - - Run elem=new Run(); - - ProtocolReference pref=new ProtocolReference(); - pref.setName("SubProtocol"); - - elem.setProtocolReference(pref); - - DefaultAnnotation annotation1=new DefaultAnnotation("annotation1"); - elem.getAnnotations().add(annotation1); - - DefaultAnnotation annotation2=new DefaultAnnotation("annotation2"); - elem.getAnnotations().add(annotation2); - - java.io.ByteArrayOutputStream baos=new java.io.ByteArrayOutputStream(); - - Visitor visitor=new TextProtocolExporterVisitor(new CachedJournal(), baos); - - elem.visit(visitor); - - try { - baos.close(); - } catch (Exception e) { - fail("Failed to close stream"); - } - - String str=baos.toString(); - - String expected="[["+annotation1.toString()+"]]\r\n"+ - "[["+annotation2.toString()+"]]\r\n"+ - "run "+pref.getName()+";\r\n"; - - if (str.equals(expected) == false) { - fail("Expected:\r\n"+expected+"\r\nGot:\r\n"+str); - } - } - - @org.junit.Test - public void testRunLocatedNoBinding() { - - Run elem=new Run(); - - ProtocolReference pref=new ProtocolReference(); - pref.setName("SubProtocol"); - - Role p1=new Role(); - p1.setName("P1"); - - pref.setRole(p1); - - elem.setProtocolReference(pref); - - java.io.ByteArrayOutputStream baos=new java.io.ByteArrayOutputStream(); - - Visitor visitor=new TextProtocolExporterVisitor(new CachedJournal(), baos); - - elem.visit(visitor); - - try { - baos.close(); - } catch (Exception e) { - fail("Failed to close stream"); - } - - String str=baos.toString(); - - String expected="run "+pref.getName()+" at "+pref.getRole().getName()+";\r\n"; - - if (str.equals(expected) == false) { - fail("Expected:\r\n"+expected+"\r\nGot:\r\n"+str); - } - } - - @org.junit.Test - public void testRunWithBinding() { - - Run elem=new Run(); - - ProtocolReference pref=new ProtocolReference(); - pref.setName("SubProtocol"); - - elem.setProtocolReference(pref); - - Parameter db1=new Parameter(); - db1.setName("Parent1"); - //db1.setBoundName("Child1"); - - elem.getParameters().add(db1); - - Parameter db2=new Parameter(); - db2.setName("Parent2"); - //db2.setBoundName("Child2"); - - elem.getParameters().add(db2); - - java.io.ByteArrayOutputStream baos=new java.io.ByteArrayOutputStream(); - - Visitor visitor=new TextProtocolExporterVisitor(new CachedJournal(), baos); - - elem.visit(visitor); - - try { - baos.close(); - } catch (Exception e) { - fail("Failed to close stream"); - } - - String str=baos.toString(); - - String expected="run "+pref.getName()+"("+db1.getName()+", "+ - db2.getName()+");\r\n"; - - if (str.equals(expected) == false) { - fail("Expected:\r\n"+expected+"\r\nGot:\r\n"+str); - } - } - - @org.junit.Test - public void testRunLocatedWithBinding() { - - Run elem=new Run(); - - ProtocolReference pref=new ProtocolReference(); - pref.setName("SubProtocol"); - - elem.setProtocolReference(pref); - - Role p1=new Role(); - p1.setName("P1"); - - pref.setRole(p1); - - Parameter db1=new Parameter(); - db1.setName("Parent1"); - //db1.setBoundName("Child1"); - - elem.getParameters().add(db1); - - Parameter db2=new Parameter(); - db2.setName("Parent2"); - //db2.setBoundName("Child2"); - - elem.getParameters().add(db2); - - java.io.ByteArrayOutputStream baos=new java.io.ByteArrayOutputStream(); - - Visitor visitor=new TextProtocolExporterVisitor(new CachedJournal(), baos); - - elem.visit(visitor); - - try { - baos.close(); - } catch (Exception e) { - fail("Failed to close stream"); - } - - String str=baos.toString(); - - String expected="run "+pref.getName()+" at "+pref.getRole().getName()+ - "("+db1.getName()+", "+db2.getName()+");\r\n"; - - if (str.equals(expected) == false) { - fail("Expected:\r\n"+expected+"\r\nGot:\r\n"+str); - } - } - - @org.junit.Test - public void testRunInlineNoBinding() { - - Run elem=new Run(); - - ProtocolReference pref=new ProtocolReference(); - - elem.setProtocolReference(pref); - - java.io.ByteArrayOutputStream baos=new java.io.ByteArrayOutputStream(); - - Visitor visitor=new TextProtocolExporterVisitor(new CachedJournal(), baos); - - elem.visit(visitor); - - try { - baos.close(); - } catch (Exception e) { - fail("Failed to close stream"); - } - - String str=baos.toString(); - - String expected="run "+pref.getName()+";\r\n"; - - if (str.equals(expected) == false) { - fail("Expected:\r\n"+expected+"\r\nGot:\r\n"+str); - } - } - - @org.junit.Test - public void testRunInlineLocatedNoBinding() { - - Run elem=new Run(); - - ProtocolReference pref=new ProtocolReference(); - - Role p1=new Role(); - p1.setName("P1"); - - pref.setRole(p1); - - elem.setProtocolReference(pref); - - java.io.ByteArrayOutputStream baos=new java.io.ByteArrayOutputStream(); - - Visitor visitor=new TextProtocolExporterVisitor(new CachedJournal(), baos); - - elem.visit(visitor); - - try { - baos.close(); - } catch (Exception e) { - fail("Failed to close stream"); - } - - String str=baos.toString(); - - String expected="run "+pref.getName()+" at "+pref.getRole().getName()+";\r\n"; - - if (str.equals(expected) == false) { - fail("Expected:\r\n"+expected+"\r\nGot:\r\n"+str); - } - } - - @org.junit.Test - public void testRunInlineWithBinding() { - - Run elem=new Run(); - - ProtocolReference pref=new ProtocolReference(); - - elem.setProtocolReference(pref); - - Parameter db1=new Parameter(); - db1.setName("Parent1"); - //db1.setBoundName("Child1"); - - elem.getParameters().add(db1); - - Parameter db2=new Parameter(); - db2.setName("Parent2"); - //db2.setBoundName("Child2"); - - elem.getParameters().add(db2); - - java.io.ByteArrayOutputStream baos=new java.io.ByteArrayOutputStream(); - - Visitor visitor=new TextProtocolExporterVisitor(new CachedJournal(), baos); - - elem.visit(visitor); - - try { - baos.close(); - } catch (Exception e) { - fail("Failed to close stream"); - } - - String str=baos.toString(); - - String expected="run "+pref.getName()+"("+db1.getName()+", "+ - db2.getName()+");\r\n"; - - if (str.equals(expected) == false) { - fail("Expected:\r\n"+expected+"\r\nGot:\r\n"+str); - } - } - - @org.junit.Test - public void testRunInlineLocatedWithBinding() { - - Run elem=new Run(); - - ProtocolReference pref=new ProtocolReference(); - - elem.setProtocolReference(pref); - - Role p1=new Role(); - p1.setName("P1"); - - pref.setRole(p1); - - Parameter db1=new Parameter(); - db1.setName("Parent1"); - //db1.setBoundName("Child1"); - - elem.getParameters().add(db1); - - Parameter db2=new Parameter(); - db2.setName("Parent2"); - //db2.setBoundName("Child2"); - - elem.getParameters().add(db2); - - java.io.ByteArrayOutputStream baos=new java.io.ByteArrayOutputStream(); - - Visitor visitor=new TextProtocolExporterVisitor(new CachedJournal(), baos); - - elem.visit(visitor); - - try { - baos.close(); - } catch (Exception e) { - fail("Failed to close stream"); - } - - String str=baos.toString(); - - String expected="run "+pref.getName()+" at "+pref.getRole().getName()+ - "("+db1.getName()+", "+db2.getName()+");\r\n"; - - if (str.equals(expected) == false) { - fail("Expected:\r\n"+expected+"\r\nGot:\r\n"+str); - } - } - - @org.junit.Test - public void testParallel() { - - Parallel elem=new Parallel(); - - Block b1=new Block(); - elem.getPaths().add(b1); - - Block b2=new Block(); - elem.getPaths().add(b2); - - Role p1=new Role(); - p1.setName("P1"); - - Role p2=new Role(); - p2.setName("P2"); - - Role p3=new Role(); - p3.setName("P3"); - - TypeReference ref1=new TypeReference(); - ref1.setName("Type1"); - - TypeReference ref2=new TypeReference(); - ref2.setName("Type2"); - - MessageSignature sig1=new MessageSignature(); - sig1.getTypeReferences().add(ref1); - - MessageSignature sig2=new MessageSignature(); - sig2.getTypeReferences().add(ref2); - - Interaction i1=new Interaction(); - - i1.setMessageSignature(sig1); - i1.setFromRole(p1); - i1.getToRoles().add(p2); - - b1.add(i1); - - Interaction i2=new Interaction(); - - i2.setMessageSignature(sig2); - i2.setFromRole(p1); - i2.getToRoles().add(p3); - - b2.add(i2); - - java.io.ByteArrayOutputStream baos=new java.io.ByteArrayOutputStream(); - - Visitor visitor=new TextProtocolExporterVisitor(new CachedJournal(), baos); - - elem.visit(visitor); - - try { - baos.close(); - } catch (Exception e) { - fail("Failed to close stream"); - } - - String str=baos.toString(); - - String expected="parallel {\r\n"+ - "\t"+ref1.getName()+" from "+p1.getName()+" to "+p2.getName()+";\r\n} and {\r\n"+ - "\t"+ref2.getName()+" from "+p1.getName()+" to "+p3.getName()+";\r\n}\r\n"; - - if (str.equals(expected) == false) { - fail("Expected:\r\n"+expected+"\r\nGot:\r\n"+str); - } - } - - @org.junit.Test - public void testParallelWithAnnotation() { - - Parallel elem=new Parallel(); - - Block b1=new Block(); - elem.getPaths().add(b1); - - Block b2=new Block(); - elem.getPaths().add(b2); - - Role p1=new Role(); - p1.setName("P1"); - - Role p2=new Role(); - p2.setName("P2"); - - Role p3=new Role(); - p3.setName("P3"); - - TypeReference ref1=new TypeReference(); - ref1.setName("Type1"); - - TypeReference ref2=new TypeReference(); - ref2.setName("Type2"); - - MessageSignature sig1=new MessageSignature(); - sig1.getTypeReferences().add(ref1); - - MessageSignature sig2=new MessageSignature(); - sig2.getTypeReferences().add(ref2); - - Interaction i1=new Interaction(); - - i1.setMessageSignature(sig1); - i1.setFromRole(p1); - i1.getToRoles().add(p2); - - b1.add(i1); - - Interaction i2=new Interaction(); - - i2.setMessageSignature(sig2); - i2.setFromRole(p1); - i2.getToRoles().add(p3); - - b2.add(i2); - - DefaultAnnotation annotation1=new DefaultAnnotation("annotation1"); - elem.getAnnotations().add(annotation1); - - DefaultAnnotation annotation2=new DefaultAnnotation("annotation2"); - elem.getAnnotations().add(annotation2); - - java.io.ByteArrayOutputStream baos=new java.io.ByteArrayOutputStream(); - - Visitor visitor=new TextProtocolExporterVisitor(new CachedJournal(), baos); - - elem.visit(visitor); - - try { - baos.close(); - } catch (Exception e) { - fail("Failed to close stream"); - } - - String str=baos.toString(); - - String expected="[["+annotation1.toString()+"]]\r\n"+ - "[["+annotation2.toString()+"]]\r\n"+ - "parallel {\r\n"+ - "\t"+ref1.getName()+" from "+p1.getName()+" to "+p2.getName()+";\r\n} and {\r\n"+ - "\t"+ref2.getName()+" from "+p1.getName()+" to "+p3.getName()+";\r\n}\r\n"; - - if (str.equals(expected) == false) { - fail("Expected:\r\n"+expected+"\r\nGot:\r\n"+str); - } - } - - @org.junit.Test - public void testDoInterrupt() { - - Do elem=new Do(); - - Interrupt c1=new Interrupt(); - - Block b1=new Block(); - c1.setBlock(b1); - - elem.getInterrupts().add(c1); - - Interrupt c2=new Interrupt(); - - Block b2=new Block(); - c2.setBlock(b2); - - elem.getInterrupts().add(c2); - - Role p1=new Role(); - p1.setName("P1"); - - Role p2=new Role(); - p2.setName("P2"); - - Role p3=new Role(); - p3.setName("P3"); - - TypeReference ref1=new TypeReference(); - ref1.setName("Type1"); - - TypeReference ref2=new TypeReference(); - ref2.setName("Type2"); - - TypeReference ref3=new TypeReference(); - ref3.setName("Type3"); - - MessageSignature sig1=new MessageSignature(); - sig1.getTypeReferences().add(ref1); - - MessageSignature sig2=new MessageSignature(); - sig2.getTypeReferences().add(ref2); - - MessageSignature sig3=new MessageSignature(); - sig3.getTypeReferences().add(ref3); - - Interaction i1=new Interaction(); - - i1.setMessageSignature(sig1); - i1.setFromRole(p1); - i1.getToRoles().add(p2); - - c1.getBlock().add(i1); - - Interaction i2=new Interaction(); - - i2.setMessageSignature(sig2); - i2.setFromRole(p1); - i2.getToRoles().add(p3); - - c2.getBlock().add(i2); - - Interaction i3=new Interaction(); - - i3.setMessageSignature(sig3); - i3.setFromRole(p1); - i3.getToRoles().add(p3); - - c2.getBlock().add(i3); - - java.io.ByteArrayOutputStream baos=new java.io.ByteArrayOutputStream(); - - Visitor visitor=new TextProtocolExporterVisitor(new CachedJournal(), baos); - - elem.visit(visitor); - - try { - baos.close(); - } catch (Exception e) { - fail("Failed to close stream"); - } - - String str=baos.toString(); - - String expected="do {\r\n"+ - "} interrupt {\r\n" + - "\t"+ref1.getName()+" from "+p1.getName()+" to "+p2.getName()+";\r\n"+ - "} interrupt {\r\n"+ - "\t"+ref2.getName()+" from "+p1.getName()+" to "+p3.getName()+";\r\n"+ - "\t"+ref3.getName()+" from "+p1.getName()+" to "+p3.getName()+";\r\n"+ - "}\r\n"; - - if (str.equals(expected) == false) { - fail("Expected:\r\n"+expected+"\r\nGot:\r\n"+str); - } - } - - @org.junit.Test - public void testDoInterruptWithAnnotation() { - - Do elem=new Do(); - - Interrupt c1=new Interrupt(); - - Block b1=new Block(); - c1.setBlock(b1); - - elem.getInterrupts().add(c1); - - Interrupt c2=new Interrupt(); - - Block b2=new Block(); - c2.setBlock(b2); - - elem.getInterrupts().add(c2); - - Role p1=new Role(); - p1.setName("P1"); - - Role p2=new Role(); - p2.setName("P2"); - - Role p3=new Role(); - p3.setName("P3"); - - TypeReference ref1=new TypeReference(); - ref1.setName("Type1"); - - TypeReference ref2=new TypeReference(); - ref2.setName("Type2"); - - TypeReference ref3=new TypeReference(); - ref3.setName("Type3"); - - MessageSignature sig1=new MessageSignature(); - sig1.getTypeReferences().add(ref1); - - MessageSignature sig2=new MessageSignature(); - sig2.getTypeReferences().add(ref2); - - MessageSignature sig3=new MessageSignature(); - sig3.getTypeReferences().add(ref3); - - Interaction i1=new Interaction(); - - i1.setMessageSignature(sig1); - i1.setFromRole(p1); - i1.getToRoles().add(p2); - - c1.getBlock().add(i1); - - Interaction i2=new Interaction(); - - i2.setMessageSignature(sig2); - i2.setFromRole(p1); - i2.getToRoles().add(p3); - - c2.getBlock().add(i2); - - Interaction i3=new Interaction(); - - i3.setMessageSignature(sig3); - i3.setFromRole(p1); - i3.getToRoles().add(p3); - - c2.getBlock().add(i3); - - DefaultAnnotation annotation1=new DefaultAnnotation("annotation1"); - elem.getAnnotations().add(annotation1); - - DefaultAnnotation annotation2=new DefaultAnnotation("annotation2"); - elem.getAnnotations().add(annotation2); - - java.io.ByteArrayOutputStream baos=new java.io.ByteArrayOutputStream(); - - Visitor visitor=new TextProtocolExporterVisitor(new CachedJournal(), baos); - - elem.visit(visitor); - - try { - baos.close(); - } catch (Exception e) { - fail("Failed to close stream"); - } - - String str=baos.toString(); - - String expected="[["+annotation1.toString()+"]]\r\n"+ - "[["+annotation2.toString()+"]]\r\n"+ - "do {\r\n"+ - "} interrupt {\r\n"+ - "\t"+ref1.getName()+" from "+p1.getName()+" to "+p2.getName()+";\r\n"+ - "} interrupt {\r\n"+ - "\t"+ref2.getName()+" from "+p1.getName()+" to "+p3.getName()+";\r\n"+ - "\t"+ref3.getName()+" from "+p1.getName()+" to "+p3.getName()+";\r\n"+ - "}\r\n"; - - if (str.equals(expected) == false) { - fail("Expected:\r\n"+expected+"\r\nGot:\r\n"+str); - } - } -} diff --git a/bundles/org.scribble.protocol/src/test/java/org/scribble/protocol/model/ProtocolTest.java b/bundles/org.scribble.protocol/src/test/java/org/scribble/protocol/model/ProtocolTest.java deleted file mode 100644 index d9737b719..000000000 --- a/bundles/org.scribble.protocol/src/test/java/org/scribble/protocol/model/ProtocolTest.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright 2009-11 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.model; - -import static org.junit.Assert.*; - -public class ProtocolTest { - - @org.junit.Test - public void testGetTopLevelProtocol() { - ProtocolModel model=new ProtocolModel(); - - Protocol top=new Protocol(); - model.setProtocol(top); - - Protocol inner=new Protocol(); - top.getNestedProtocols().add(inner); - - if (inner.getTopLevelProtocol() != top) { - fail("Top level protocol is incorrect"); - } - } -} diff --git a/bundles/org.scribble.protocol/src/test/java/org/scribble/protocol/util/InteractionUtilTest.java b/bundles/org.scribble.protocol/src/test/java/org/scribble/protocol/util/InteractionUtilTest.java deleted file mode 100644 index 162a19ba3..000000000 --- a/bundles/org.scribble.protocol/src/test/java/org/scribble/protocol/util/InteractionUtilTest.java +++ /dev/null @@ -1,304 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.util; - -import static org.junit.Assert.*; - -import org.scribble.protocol.model.*; - -public class InteractionUtilTest { - - @org.junit.Test - public void testGetInitialInteractionsSimple() { - ProtocolModel pm=new ProtocolModel(); - - Protocol p=new Protocol(); - pm.setProtocol(p); - - Interaction i1=new Interaction(); - p.getBlock().add(i1); - - Interaction i2=new Interaction(); - p.getBlock().add(i2); - - java.util.List results=InteractionUtil.getInitialInteractions(pm); - - if (results.size() != 1) { - fail("Should only be 1 result: "+results.size()); - } - - if (results.get(0) != i1) { - fail("Interaction not as expected"); - } - } - - @org.junit.Test - public void testGetInitialInteractionsChoice() { - ProtocolModel pm=new ProtocolModel(); - - Protocol p=new Protocol(); - pm.setProtocol(p); - - Choice choice=new Choice(); - choice.setRole(new Role()); - p.getBlock().add(choice); - - Block b1=new Block(); - choice.getPaths().add(b1); - - Interaction i0=new Interaction(); - i0.setMessageSignature(new MessageSignature(new TypeReference())); - b1.add(i0); - - Interaction i1=new Interaction(); - i1.setMessageSignature(new MessageSignature(new TypeReference())); - b1.add(i1); - - Block b2=new Block(); - choice.getPaths().add(b2); - - Interaction i3=new Interaction(); - i3.setMessageSignature(new MessageSignature(new TypeReference())); - b2.add(i3); - - Interaction i2=new Interaction(); - i2.setMessageSignature(new MessageSignature(new TypeReference())); - b2.add(i2); - - java.util.List results=InteractionUtil.getInitialInteractions(pm); - - if (results.size() != 2) { - fail("Should be 2 results: "+results.size()); - } - - if (results.get(0) != i0) { - fail("Interaction 1 not as expected"); - } - - if (results.get(1) != i3) { - fail("Interaction 2 not as expected"); - } - } - - @org.junit.Test - public void testGetInitialInteractionsEmbeddedChoice() { - ProtocolModel pm=new ProtocolModel(); - - Protocol p=new Protocol(); - pm.setProtocol(p); - - Choice choice1=new Choice(); - choice1.setRole(new Role()); - p.getBlock().add(choice1); - - Block wb1=new Block(); - choice1.getPaths().add(wb1); - - Choice choice2=new Choice(); - choice2.setRole(new Role()); - wb1.add(choice2); - - Block wb1_1=new Block(); - Interaction i1_1=new Interaction(); - i1_1.setMessageSignature(new MessageSignature(new TypeReference())); - wb1_1.add(i1_1); - choice2.getPaths().add(wb1_1); - - Interaction i1=new Interaction(); - wb1_1.add(i1); - - Block wb1_2=new Block(); - Interaction i1_2=new Interaction(); - i1_2.setMessageSignature(new MessageSignature(new TypeReference())); - wb1_2.add(i1_2); - choice2.getPaths().add(wb1_2); - - Interaction i2=new Interaction(); - wb1_2.add(i2); - - Block wb2=new Block(); - choice1.getPaths().add(wb2); - - Interaction i3=new Interaction(); - wb2.add(i3); - - java.util.List results=InteractionUtil.getInitialInteractions(pm); - - if (results.size() != 3) { - fail("Should be 3 results: "+results.size()); - } - - if (results.get(0) != i1_1) { - fail("Interaction 1 not as expected"); - } - - if (results.get(1) != i1_2) { - fail("Interaction 2 not as expected"); - } - - if (results.get(2) != i3) { - fail("Interaction 3 not as expected"); - } - } - - @org.junit.Test - public void testGetInitialInteractionsChoiceNestedProtocol() { - ProtocolModel pm=new ProtocolModel(); - - Protocol p=new Protocol(); - pm.setProtocol(p); - - Choice choice=new Choice(); - choice.setRole(new Role()); - p.getBlock().add(choice); - - Block b1=new Block(); - choice.getPaths().add(b1); - - Run run=new Run(); - b1.add(run); - - ProtocolReference pref=new ProtocolReference(); - pref.setName("sub"); - run.setProtocolReference(pref); - - Block b2=new Block(); - choice.getPaths().add(b2); - - Interaction i3=new Interaction(); - i3.setMessageSignature(new MessageSignature(new TypeReference())); - b2.add(i3); - - Interaction i2=new Interaction(); - i2.setMessageSignature(new MessageSignature(new TypeReference())); - b2.add(i2); - - Protocol sub=new Protocol(); - sub.setName("sub"); - p.getNestedProtocols().add(sub); - - Block sb1=new Block(); - sub.setBlock(sb1); - - Interaction i0=new Interaction(); - i0.setMessageSignature(new MessageSignature(new TypeReference())); - sb1.add(i0); - - Interaction i1=new Interaction(); - i1.setMessageSignature(new MessageSignature(new TypeReference())); - sb1.add(i1); - - - java.util.List results=InteractionUtil.getInitialInteractions(pm); - - if (results.size() != 2) { - fail("Should be 2 results: "+results.size()); - } - - if (results.get(0) != i0) { - fail("Interaction 1 not as expected"); - } - - if (results.get(1) != i3) { - fail("Interaction 2 not as expected"); - } - } - - @org.junit.Test - public void testIsInitialInteractionSimple() { - ProtocolModel pm=new ProtocolModel(); - - Protocol p=new Protocol(); - pm.setProtocol(p); - - Interaction i1=new Interaction(); - p.getBlock().add(i1); - - Interaction i2=new Interaction(); - p.getBlock().add(i2); - - if (InteractionUtil.isInitialInteraction(pm, i1) == false) { - fail("Interaction 1 not as expected"); - } - - if (InteractionUtil.isInitialInteraction(pm, i2)) { - fail("Interaction 2 is NOT initial"); - } - } - - @org.junit.Test - public void testIsInitialInteractionsEmbeddedChoice() { - ProtocolModel pm=new ProtocolModel(); - - Protocol p=new Protocol(); - pm.setProtocol(p); - - Choice choice1=new Choice(); - choice1.setRole(new Role()); - p.getBlock().add(choice1); - - Block wb1=new Block(); - choice1.getPaths().add(wb1); - - Choice choice2=new Choice(); - choice2.setRole(new Role()); - wb1.add(choice2); - - Block wb1_1=new Block(); - Interaction i1_1=new Interaction(); - i1_1.setMessageSignature(new MessageSignature(new TypeReference())); - wb1_1.add(i1_1); - choice2.getPaths().add(wb1_1); - - Interaction i1=new Interaction(); - wb1_1.add(i1); - - Block wb1_2=new Block(); - Interaction i1_2=new Interaction(); - i1_2.setMessageSignature(new MessageSignature(new TypeReference())); - wb1_2.add(i1_2); - choice2.getPaths().add(wb1_2); - - Interaction i2=new Interaction(); - wb1_2.add(i2); - - Block wb2=new Block(); - choice1.getPaths().add(wb2); - - Interaction i3=new Interaction(); - wb2.add(i3); - - Interaction i4=new Interaction(); - p.getBlock().add(i4); - - if (InteractionUtil.isInitialInteraction(pm, i1_1) == false) { - fail("Interaction 1 not as expected"); - } - - if (InteractionUtil.isInitialInteraction(pm, i1_2) == false) { - fail("Interaction 2 not as expected"); - } - - if (InteractionUtil.isInitialInteraction(pm, i3) == false) { - fail("Interaction 3 not as expected"); - } - - if (InteractionUtil.isInitialInteraction(pm, i4)) { - fail("Interaction 4 is NOT initial"); - } - } -} diff --git a/bundles/org.scribble.protocol/src/test/java/org/scribble/protocol/util/RoleUtilTest.java b/bundles/org.scribble.protocol/src/test/java/org/scribble/protocol/util/RoleUtilTest.java deleted file mode 100644 index 66f513128..000000000 --- a/bundles/org.scribble.protocol/src/test/java/org/scribble/protocol/util/RoleUtilTest.java +++ /dev/null @@ -1,292 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.util; - -import static org.junit.Assert.*; - -import org.scribble.protocol.model.*; - -public class RoleUtilTest { - - @org.junit.Test - public void testGetRolesInScope1() { - - Protocol prot1=new Protocol(); - - Introduces plist1=new Introduces(); - prot1.getBlock().add(plist1); - - Role part1=new Role(); - part1.setName("part1"); - plist1.getIntroducedRoles().add(part1); - - Role part2=new Role(); - part2.setName("part2"); - plist1.getIntroducedRoles().add(part2); - - Interaction i1=new Interaction(); - prot1.getBlock().add(i1); - - java.util.Set result=RoleUtil.getRolesInScope(i1); - - if (result.size() != 2) { - fail("Number of roles expected=2, but got: "+result.size()); - } - - if (result.contains(part1) == false) { - fail("Role "+part1+" not in list"); - } - - if (result.contains(part2) == false) { - fail("Role "+part2+" not in list"); - } - } - - @org.junit.Test - public void testGetRolesInScope2() { - - Protocol prot1=new Protocol(); - - Introduces plist1=new Introduces(); - prot1.getBlock().add(plist1); - - Role part1=new Role(); - part1.setName("part1"); - plist1.getIntroducedRoles().add(part1); - - Role part2=new Role(); - part2.setName("part2"); - plist1.getIntroducedRoles().add(part2); - - Choice choice=new Choice(); - prot1.getBlock().add(choice); - - Block wb1=new Block(); - choice.getPaths().add(wb1); - - Introduces plist2=new Introduces(); - wb1.add(plist2); - - Role part3=new Role(); - part3.setName("part3"); - plist2.getIntroducedRoles().add(part3); - - Role part4=new Role(); - part4.setName("part4"); - plist2.getIntroducedRoles().add(part4); - - Block wb2=new Block(); - choice.getPaths().add(wb2); - - Introduces plist3=new Introduces(); - wb2.add(plist3); - - Role part5=new Role(); - part5.setName("part5"); - plist3.getIntroducedRoles().add(part5); - - Role part6=new Role(); - part6.setName("part6"); - plist3.getIntroducedRoles().add(part6); - - Interaction i1=new Interaction(); - wb2.add(i1); - - java.util.Set result=RoleUtil.getRolesInScope(i1); - - if (result.size() != 4) { - fail("Number of roles expected=4, but got: "+result.size()); - } - - if (result.contains(part1) == false) { - fail("Role "+part1+" not in list"); - } - - if (result.contains(part2) == false) { - fail("Role "+part2+" not in list"); - } - - if (result.contains(part5) == false) { - fail("Role "+part5+" not in list"); - } - - if (result.contains(part6) == false) { - fail("Role "+part6+" not in list"); - } - } - - @org.junit.Test - public void testGetEnclosingBlockSingleActivities() { - Protocol p=new Protocol(); - - Role r0=new Role(); - r0.setName("r0"); - - Interaction i0=new Interaction(); - i0.setFromRole(r0); - p.getBlock().add(i0); - - Role r1=new Role(); - r1.setName("r1"); - - Role r2=new Role(); - r2.setName("r2"); - - Parallel par=new Parallel(); - p.getBlock().add(par); - - Block parb1=new Block(); - par.getPaths().add(parb1); - - Interaction i1=new Interaction(); - i1.setFromRole(r1); - - parb1.add(i1); - - Block parb2=new Block(); - par.getPaths().add(parb2); - - Choice choice1=new Choice(); - parb2.add(choice1); - - Block wb1=new Block(); - choice1.getPaths().add(wb1); - - Interaction i2=new Interaction(); - i2.setFromRole(r2); - - wb1.add(i2); - - // Check results - Block b0=RoleUtil.getEnclosingBlock(p, r0, false); - - if (b0 == null) { - fail("b0 is null"); - } - - if (b0 != p.getBlock()) { - fail("b0 not protocol block"); - } - - Block b1=RoleUtil.getEnclosingBlock(p, r1, false); - - if (b1 == null) { - fail("b1 is null"); - } - - if (b1 != parb1) { - fail("b1 not parallel block"); - } - - Block b2=RoleUtil.getEnclosingBlock(p, r2, false); - - if (b2 == null) { - fail("b2 is null"); - } - - if (b2 != wb1) { - fail("b2 not when block"); - } - } - - @org.junit.Test - public void testGetEnclosingBlockMultiActivities() { - Protocol p=new Protocol(); - - Role r0=new Role(); - r0.setName("r0"); - - Interaction i0=new Interaction(); - i0.setFromRole(r0); - p.getBlock().add(i0); - - Role r1=new Role(); - r1.setName("r1"); - - Role r2=new Role(); - r2.setName("r2"); - - Parallel par=new Parallel(); - p.getBlock().add(par); - - Block parb1=new Block(); - par.getPaths().add(parb1); - - Interaction i11=new Interaction(); - i11.setFromRole(r1); - - parb1.add(i11); - - Block parb2=new Block(); - par.getPaths().add(parb2); - - Interaction i12=new Interaction(); - i12.setFromRole(r1); - - parb2.add(i12); - - Choice choice1=new Choice(); - parb2.add(choice1); - - Block wb1=new Block(); - choice1.getPaths().add(wb1); - - Interaction i21=new Interaction(); - i21.setFromRole(r2); - - wb1.add(i21); - - Block wb2=new Block(); - choice1.getPaths().add(wb2); - - Interaction i22=new Interaction(); - i22.setFromRole(r2); - - wb2.add(i22); - - // Check results - Block b0=RoleUtil.getEnclosingBlock(p, r0, false); - - if (b0 == null) { - fail("b0 is null"); - } - - if (b0 != p.getBlock()) { - fail("b0 not protocol block"); - } - - Block b1=RoleUtil.getEnclosingBlock(p, r1, false); - - if (b1 == null) { - fail("b1 is null"); - } - - if (b1 != p.getBlock()) { - fail("b1 not parallel parent block (i.e. protocol block)"); - } - - Block b2=RoleUtil.getEnclosingBlock(p, r2, false); - - if (b2 == null) { - fail("b2 is null"); - } - - if (b2 != parb2) { - fail("b2 not parallel block containing choice"); - } - } -} diff --git a/bundles/org.scribble.protocol/src/test/java/org/scribble/protocol/util/RunUtilTest.java b/bundles/org.scribble.protocol/src/test/java/org/scribble/protocol/util/RunUtilTest.java deleted file mode 100644 index 1ad40917f..000000000 --- a/bundles/org.scribble.protocol/src/test/java/org/scribble/protocol/util/RunUtilTest.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.util; - -import static org.junit.Assert.*; - -import org.scribble.protocol.model.*; - -public class RunUtilTest { - - private static final String SUBPROTOCOL = "subprotocol"; - - @org.junit.Test - public void testGetInnerProtocol() { - ProtocolModel pm=new ProtocolModel(); - - Protocol p=new Protocol(); - pm.setProtocol(p); - - Run act=new Run(); - ProtocolReference pref=new ProtocolReference(); - pref.setName(SUBPROTOCOL); - act.setProtocolReference(pref); - - p.getBlock().add(act); - - Protocol subp=new Protocol(); - subp.setName(SUBPROTOCOL); - - p.getNestedProtocols().add(subp); - - Protocol result=RunUtil.getInnerProtocol(p, pref); - - if (result != subp) { - fail("Inner protocol not returned"); - } - } - - @org.junit.Test - public void testGetInnerProtocolLocated() { - ProtocolModel pm=new ProtocolModel(); - - Protocol p=new Protocol(); - pm.setProtocol(p); - - Role p1=new Role(); - p1.setName("p1"); - p.setLocatedRole(p1); - - Run act=new Run(); - ProtocolReference pref=new ProtocolReference(); - pref.setName(SUBPROTOCOL); - pref.setRole(p1); - act.setProtocolReference(pref); - - p.getBlock().add(act); - - Protocol subp=new Protocol(); - subp.setName(SUBPROTOCOL); - subp.setLocatedRole(p1); - - p.getNestedProtocols().add(subp); - - Protocol result=RunUtil.getInnerProtocol(p, pref); - - if (result != subp) { - fail("Inner protocol not returned"); - } - } -} diff --git a/bundles/org.scribble.protocol/src/test/java/org/scribble/protocol/util/TypesUtilTest.java b/bundles/org.scribble.protocol/src/test/java/org/scribble/protocol/util/TypesUtilTest.java deleted file mode 100644 index 240502ff1..000000000 --- a/bundles/org.scribble.protocol/src/test/java/org/scribble/protocol/util/TypesUtilTest.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.util; - -import static org.junit.Assert.*; - -import org.scribble.protocol.model.*; - -public class TypesUtilTest { - - //private static final String ORDER_FORMAT = "xsdtype"; - private static final String ORDER_TYPE = "{http://www.example.org/types}Order"; - private static final String ORDER = "Order"; - - @org.junit.Test - public void testGetTypeImport() { - ProtocolModel pm=new ProtocolModel(); - TypeImportList imp1=new TypeImportList(); - imp1.setFormat("xml"); - - TypeImport t1=new TypeImport(); - t1.setName(ORDER); - imp1.getTypeImports().add(t1); - - DataType dt=new DataType(); - dt.setDetails(ORDER_TYPE); - t1.setDataType(dt); - - pm.getImports().add(imp1); - - Protocol p=new Protocol(); - pm.setProtocol(p); - - Interaction i1=new Interaction(); - MessageSignature ms1=new MessageSignature(); - TypeReference tref1=new TypeReference(); - tref1.setName(ORDER); - ms1.getTypeReferences().add(tref1); - i1.setMessageSignature(ms1); - - p.getBlock().add(i1); - - TypeImport ti=TypesUtil.getTypeImport(tref1); - - if (ti == null) { - fail("Failed to get TypeImport for Order"); - } - - if (ti.getDataType() == null) { - fail("No data type"); - } - - if (ti.getDataType().getDetails().equals(ORDER_TYPE) == false) { - fail("Data type detail not as expected: "+ti.getDataType().getDetails()); - } - } - - @org.junit.Test - public void testIsConcreteTypesDefinedTrue() { - ProtocolModel pm=new ProtocolModel(); - TypeImportList imp1=new TypeImportList(); - imp1.setFormat("xml"); - - TypeImport t1=new TypeImport(); - t1.setName(ORDER); - imp1.getTypeImports().add(t1); - - DataType dt=new DataType(); - dt.setDetails(ORDER_TYPE); - t1.setDataType(dt); - - pm.getImports().add(imp1); - - if (TypesUtil.isConcreteTypesDefined(pm) == false) { - fail("Concrete types defined"); - } - } - - @org.junit.Test - public void testIsConcreteTypesDefinedFalse() { - ProtocolModel pm=new ProtocolModel(); - TypeImportList imp1=new TypeImportList(); - imp1.setFormat("xml"); - - TypeImport t1=new TypeImport(); - t1.setName(ORDER); - imp1.getTypeImports().add(t1); - - pm.getImports().add(imp1); - - if (TypesUtil.isConcreteTypesDefined(pm) == true) { - fail("Concrete types defined"); - } - } -} diff --git a/bundles/org.scribble.protocol/src/test/java/org/scribble/protocol/validation/rules/ChoiceValidatorRuleTest.java b/bundles/org.scribble.protocol/src/test/java/org/scribble/protocol/validation/rules/ChoiceValidatorRuleTest.java deleted file mode 100644 index 5790d7e02..000000000 --- a/bundles/org.scribble.protocol/src/test/java/org/scribble/protocol/validation/rules/ChoiceValidatorRuleTest.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.validation.rules; - -import java.text.MessageFormat; - -import org.scribble.protocol.model.*; - -public class ChoiceValidatorRuleTest { - - @org.junit.Test - public void testChoiceAtUnknownRole() { - - Protocol prot1=new Protocol(); - - Introduces plist1=new Introduces(); - prot1.getBlock().add(plist1); - - Role part1=new Role(); - part1.setName("part1"); - plist1.getIntroducedRoles().add(part1); - - Role part2=new Role(); - part2.setName("part2"); - plist1.getIntroducedRoles().add(part2); - - Choice i1=new Choice(); - prot1.getBlock().add(i1); - - Role part3=new Role(); - part3.setName("part3"); - - i1.setRole(part3); - - TestScribbleLogger logger=new TestScribbleLogger(); - - ChoiceValidatorRule rule=new ChoiceValidatorRule(); - rule.validate(null, i1, logger); - - logger.verifyErrors(new String[]{ - MessageFormat.format( - java.util.PropertyResourceBundle.getBundle( - "org.scribble.protocol.Messages").getString("_UNKNOWN_ROLE"), - part3.getName()) - }); - } - - @org.junit.Test - public void testChoiceAtLocatedRole() { - - Protocol prot1=new Protocol(); - - Introduces plist1=new Introduces(); - prot1.getBlock().add(plist1); - - Role part1=new Role(); - part1.setName("part1"); - plist1.getIntroducedRoles().add(part1); - - Role part2=new Role(); - part2.setName("part2"); - plist1.getIntroducedRoles().add(part2); - - prot1.setLocatedRole(part1); - - Choice i1=new Choice(); - prot1.getBlock().add(i1); - - TestScribbleLogger logger=new TestScribbleLogger(); - - ChoiceValidatorRule rule=new ChoiceValidatorRule(); - rule.validate(null, i1, logger); - - logger.verifyErrors(new String[]{ - }); - } -} diff --git a/bundles/org.scribble.protocol/src/test/java/org/scribble/protocol/validation/rules/InteractionValidatorRuleTest.java b/bundles/org.scribble.protocol/src/test/java/org/scribble/protocol/validation/rules/InteractionValidatorRuleTest.java deleted file mode 100644 index 5e7899c3c..000000000 --- a/bundles/org.scribble.protocol/src/test/java/org/scribble/protocol/validation/rules/InteractionValidatorRuleTest.java +++ /dev/null @@ -1,492 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.validation.rules; - -import java.text.MessageFormat; - -import org.scribble.protocol.model.*; - -public class InteractionValidatorRuleTest { - - @org.junit.Test - public void testInteractionFromUnknownRole() { - - Protocol prot1=new Protocol(); - - Introduces plist1=new Introduces(); - prot1.getBlock().add(plist1); - - Role part1=new Role(); - part1.setName("part1"); - plist1.getIntroducedRoles().add(part1); - - Role part2=new Role(); - part2.setName("part2"); - plist1.getIntroducedRoles().add(part2); - - Interaction i1=new Interaction(); - prot1.getBlock().add(i1); - - Role part3=new Role(); - part3.setName("part3"); - - i1.setFromRole(part3); - i1.getToRoles().add(part2); - - TestScribbleLogger logger=new TestScribbleLogger(); - - InteractionValidatorRule rule=new InteractionValidatorRule(); - rule.validate(null, i1, logger); - - logger.verifyErrors(new String[]{ - MessageFormat.format( - java.util.PropertyResourceBundle.getBundle( - "org.scribble.protocol.Messages").getString("_UNKNOWN_ROLE"), - part3.getName()) - }); - } - - @org.junit.Test - public void testInteractionToUnknownRole() { - - Protocol prot1=new Protocol(); - - Introduces plist1=new Introduces(); - prot1.getBlock().add(plist1); - - Role part1=new Role(); - part1.setName("part1"); - plist1.getIntroducedRoles().add(part1); - - Role part2=new Role(); - part2.setName("part2"); - plist1.getIntroducedRoles().add(part2); - - Interaction i1=new Interaction(); - prot1.getBlock().add(i1); - - Role part3=new Role(); - part3.setName("part3"); - - i1.setFromRole(part1); - i1.getToRoles().add(part3); - - TestScribbleLogger logger=new TestScribbleLogger(); - - InteractionValidatorRule rule=new InteractionValidatorRule(); - rule.validate(null, i1, logger); - - logger.verifyErrors(new String[]{ - MessageFormat.format( - java.util.PropertyResourceBundle.getBundle( - "org.scribble.protocol.Messages").getString("_UNKNOWN_ROLE"), - part3.getName()) - }); - } - - @org.junit.Test - public void testInteractionToRequiredRole() { - - Protocol prot1=new Protocol(); - - Introduces plist1=new Introduces(); - prot1.getBlock().add(plist1); - - Role part1=new Role(); - part1.setName("part1"); - plist1.getIntroducedRoles().add(part1); - - Role part2=new Role(); - part2.setName("part2"); - plist1.getIntroducedRoles().add(part2); - - Interaction i1=new Interaction(); - prot1.getBlock().add(i1); - - i1.setFromRole(part1); - //i1.setToParticipant(part2); - - TestScribbleLogger logger=new TestScribbleLogger(); - - InteractionValidatorRule rule=new InteractionValidatorRule(); - rule.validate(null, i1, logger); - - logger.verifyErrors(new String[]{ - MessageFormat.format( - java.util.PropertyResourceBundle.getBundle( - "org.scribble.protocol.Messages").getString("_INTERACTION_ROLE"), - "to") - }); - } - - @org.junit.Test - public void testInteractionFromRequiredRole() { - - Protocol prot1=new Protocol(); - - Introduces plist1=new Introduces(); - prot1.getBlock().add(plist1); - - Role part1=new Role(); - part1.setName("part1"); - plist1.getIntroducedRoles().add(part1); - - Role part2=new Role(); - part2.setName("part2"); - plist1.getIntroducedRoles().add(part2); - - Interaction i1=new Interaction(); - prot1.getBlock().add(i1); - - //i1.setFromParticipant(part1); - i1.getToRoles().add(part2); - - TestScribbleLogger logger=new TestScribbleLogger(); - - InteractionValidatorRule rule=new InteractionValidatorRule(); - rule.validate(null, i1, logger); - - logger.verifyErrors(new String[]{ - MessageFormat.format( - java.util.PropertyResourceBundle.getBundle( - "org.scribble.protocol.Messages").getString("_INTERACTION_ROLE"), - "from") - }); - } - - @org.junit.Test - public void testInteractionToLocatedRole() { - - Protocol prot1=new Protocol(); - - Introduces plist1=new Introduces(); - prot1.getBlock().add(plist1); - - Role part1=new Role(); - part1.setName("part1"); - plist1.getIntroducedRoles().add(part1); - - Role part2=new Role(); - part2.setName("part2"); - plist1.getIntroducedRoles().add(part2); - - prot1.setLocatedRole(part2); - - Interaction i1=new Interaction(); - prot1.getBlock().add(i1); - - i1.setFromRole(part1); - - TestScribbleLogger logger=new TestScribbleLogger(); - - InteractionValidatorRule rule=new InteractionValidatorRule(); - rule.validate(null, i1, logger); - - logger.verifyErrors(new String[]{ - }); - } - - @org.junit.Test - public void testInteractionRequiredFromRoleWithLocatedRole() { - - Protocol prot1=new Protocol(); - - Introduces plist1=new Introduces(); - prot1.getBlock().add(plist1); - - Role part1=new Role(); - part1.setName("part1"); - plist1.getIntroducedRoles().add(part1); - - Role part2=new Role(); - part2.setName("part2"); - plist1.getIntroducedRoles().add(part2); - - prot1.setLocatedRole(part2); - - Interaction i1=new Interaction(); - prot1.getBlock().add(i1); - - i1.getToRoles().add(part2); - - TestScribbleLogger logger=new TestScribbleLogger(); - - InteractionValidatorRule rule=new InteractionValidatorRule(); - rule.validate(null, i1, logger); - - logger.verifyErrors(new String[]{ - MessageFormat.format( - java.util.PropertyResourceBundle.getBundle( - "org.scribble.protocol.Messages").getString("_INTERACTION_ROLE"), - "from") - }); - } - - @org.junit.Test - public void testInteractionRequiredToRoleWithLocatedRole() { - - Protocol prot1=new Protocol(); - - Introduces plist1=new Introduces(); - prot1.getBlock().add(plist1); - - Role part1=new Role(); - part1.setName("part1"); - plist1.getIntroducedRoles().add(part1); - - Role part2=new Role(); - part2.setName("part2"); - plist1.getIntroducedRoles().add(part2); - - prot1.setLocatedRole(part2); - - Interaction i1=new Interaction(); - prot1.getBlock().add(i1); - - i1.setFromRole(part2); - - TestScribbleLogger logger=new TestScribbleLogger(); - - InteractionValidatorRule rule=new InteractionValidatorRule(); - rule.validate(null, i1, logger); - - logger.verifyErrors(new String[]{ - MessageFormat.format( - java.util.PropertyResourceBundle.getBundle( - "org.scribble.protocol.Messages").getString("_INTERACTION_ROLE"), - "to") - }); - } - - @org.junit.Test - public void testInteractionFromLocatedRole() { - - Protocol prot1=new Protocol(); - - Introduces plist1=new Introduces(); - prot1.getBlock().add(plist1); - - Role part1=new Role(); - part1.setName("part1"); - plist1.getIntroducedRoles().add(part1); - - Role part2=new Role(); - part2.setName("part2"); - plist1.getIntroducedRoles().add(part2); - - prot1.setLocatedRole(part1); - - Interaction i1=new Interaction(); - prot1.getBlock().add(i1); - - i1.getToRoles().add(part2); - - TestScribbleLogger logger=new TestScribbleLogger(); - - InteractionValidatorRule rule=new InteractionValidatorRule(); - rule.validate(null, i1, logger); - - logger.verifyErrors(new String[]{ - }); - } - - @org.junit.Test - public void testInteractionUnrelatedToLocatedRole() { - - Protocol prot1=new Protocol(); - - Introduces rlist1=new Introduces(); - prot1.getBlock().add(rlist1); - - Role role1=new Role(); - role1.setName("role1"); - rlist1.getIntroducedRoles().add(role1); - - Role role2=new Role(); - role2.setName("role2"); - rlist1.getIntroducedRoles().add(role2); - - Role role3=new Role(); - role3.setName("role3"); - prot1.setLocatedRole(role3); - - Interaction i1=new Interaction(); - prot1.getBlock().add(i1); - - i1.setFromRole(role1); - i1.getToRoles().add(role2); - - TestScribbleLogger logger=new TestScribbleLogger(); - - InteractionValidatorRule rule=new InteractionValidatorRule(); - rule.validate(null, i1, logger); - - logger.verifyErrors(new String[]{ - MessageFormat.format( - java.util.PropertyResourceBundle.getBundle( - "org.scribble.protocol.Messages").getString("_UNRELATED_TO_LOCATED_ROLE"), - role3.getName()) - }); - } - - @org.junit.Test - public void testInteractionNoImportForMessageType() { - - ProtocolModel pm=new ProtocolModel(); - - Protocol prot1=new Protocol(); - pm.setProtocol(prot1); - - Introduces rlist1=new Introduces(); - prot1.getBlock().add(rlist1); - - Role role1=new Role(); - role1.setName("role1"); - rlist1.getIntroducedRoles().add(role1); - - Role role2=new Role(); - role2.setName("role2"); - rlist1.getIntroducedRoles().add(role2); - - Interaction i1=new Interaction(); - prot1.getBlock().add(i1); - - i1.setFromRole(role1); - i1.getToRoles().add(role2); - - MessageSignature msig=new MessageSignature(); - i1.setMessageSignature(msig); - - TypeReference tref=new TypeReference(); - tref.setName("MyType"); - msig.getTypeReferences().add(tref); - - TestScribbleLogger logger=new TestScribbleLogger(); - - InteractionValidatorRule rule=new InteractionValidatorRule(); - rule.validate(null, i1, logger); - - logger.verifyErrors(new String[]{ - MessageFormat.format( - java.util.PropertyResourceBundle.getBundle( - "org.scribble.protocol.Messages").getString("_NO_TYPE_IMPORT"), - tref.getName()) - }); - } - - @org.junit.Test - public void testInteractionImportForMessageType() { - String tiName="MyType"; - - ProtocolModel pm=new ProtocolModel(); - - TypeImport ti=new TypeImport(); - ti.setName(tiName); - - TypeImportList til=new TypeImportList(); - til.getTypeImports().add(ti); - - pm.getImports().add(til); - - Protocol prot1=new Protocol(); - pm.setProtocol(prot1); - - Introduces rlist1=new Introduces(); - prot1.getBlock().add(rlist1); - - Role role1=new Role(); - role1.setName("role1"); - rlist1.getIntroducedRoles().add(role1); - - Role role2=new Role(); - role2.setName("role2"); - rlist1.getIntroducedRoles().add(role2); - - Interaction i1=new Interaction(); - prot1.getBlock().add(i1); - - i1.setFromRole(role1); - i1.getToRoles().add(role2); - - MessageSignature msig=new MessageSignature(); - i1.setMessageSignature(msig); - - TypeReference tref=new TypeReference(); - tref.setName(tiName); - msig.getTypeReferences().add(tref); - - TestScribbleLogger logger=new TestScribbleLogger(); - - InteractionValidatorRule rule=new InteractionValidatorRule(); - rule.validate(null, i1, logger); - - logger.verifyErrors(new String[]{ - }); - } - - @org.junit.Test - public void testInteractionMessageTypeCannotBeReservedWord() { - String tiName="Choice"; - - ProtocolModel pm=new ProtocolModel(); - - TypeImport ti=new TypeImport(); - ti.setName(tiName); - - TypeImportList til=new TypeImportList(); - til.getTypeImports().add(ti); - - pm.getImports().add(til); - Protocol prot1=new Protocol(); - pm.setProtocol(prot1); - - Introduces rlist1=new Introduces(); - prot1.getBlock().add(rlist1); - - Role role1=new Role(); - role1.setName("role1"); - rlist1.getIntroducedRoles().add(role1); - - Role role2=new Role(); - role2.setName("role2"); - rlist1.getIntroducedRoles().add(role2); - - Interaction i1=new Interaction(); - prot1.getBlock().add(i1); - - i1.setFromRole(role1); - i1.getToRoles().add(role2); - - MessageSignature msig=new MessageSignature(); - i1.setMessageSignature(msig); - - TypeReference tref=new TypeReference(); - tref.setName(tiName); - msig.getTypeReferences().add(tref); - - TestScribbleLogger logger=new TestScribbleLogger(); - - InteractionValidatorRule rule=new InteractionValidatorRule(); - rule.validate(null, i1, logger); - - logger.verifyErrors(new String[]{ - MessageFormat.format( - java.util.PropertyResourceBundle.getBundle( - "org.scribble.protocol.Messages").getString("_CANNOT_USE_RESERVED_WORD"), - tref.getName()) - }); - } -} diff --git a/bundles/org.scribble.protocol/src/test/java/org/scribble/protocol/validation/rules/IntroducesValidatorRuleTest.java b/bundles/org.scribble.protocol/src/test/java/org/scribble/protocol/validation/rules/IntroducesValidatorRuleTest.java deleted file mode 100644 index d5eb87ea5..000000000 --- a/bundles/org.scribble.protocol/src/test/java/org/scribble/protocol/validation/rules/IntroducesValidatorRuleTest.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright 2009-11 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.validation.rules; - -import java.text.MessageFormat; - -import org.scribble.protocol.model.*; -import org.scribble.protocol.validation.DefaultProtocolValidatorContext; - -public class IntroducesValidatorRuleTest { - - @org.junit.Test - public void testValidateNameAlreadyDefined() { - - Protocol prot1=new Protocol(); - - Introduces in1=new Introduces(); - prot1.getBlock().add(in1); - - Role part1=new Role(); - part1.setName("part1"); - in1.getIntroducedRoles().add(part1); - - Role part2=new Role(); - part2.setName("part2"); - in1.getIntroducedRoles().add(part2); - - ParameterDefinition pd=new ParameterDefinition(); - pd.setName("part1"); - - prot1.getParameterDefinitions().add(pd); - - TestScribbleLogger logger=new TestScribbleLogger(); - - DefaultProtocolValidatorContext pvc=new DefaultProtocolValidatorContext(null, null); - - // Initialize state associated with protocol validator context - ProtocolValidatorRule prule=new ProtocolValidatorRule(); - prule.validate(pvc, prot1, logger); - - // Validate the rule to be tested - IntroducesValidatorRule rule=new IntroducesValidatorRule(); - rule.validate(pvc, in1, logger); - - logger.verifyErrors(new String[]{ - MessageFormat.format( - java.util.PropertyResourceBundle.getBundle( - "org.scribble.protocol.Messages").getString("_NAME_ALREADY_DEFINED"), - part1.getName()) - }); - } -} diff --git a/bundles/org.scribble.protocol/src/test/java/org/scribble/protocol/validation/rules/ProtocolModelValidatorRuleTest.java b/bundles/org.scribble.protocol/src/test/java/org/scribble/protocol/validation/rules/ProtocolModelValidatorRuleTest.java deleted file mode 100644 index 4f498e992..000000000 --- a/bundles/org.scribble.protocol/src/test/java/org/scribble/protocol/validation/rules/ProtocolModelValidatorRuleTest.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.validation.rules; - -import java.text.MessageFormat; - -import org.scribble.common.logging.Journal; -import org.scribble.protocol.DefaultProtocolContext; -import org.scribble.protocol.ProtocolContext; -import org.scribble.protocol.model.*; -import org.scribble.protocol.projection.ProtocolProjector; -import org.scribble.protocol.validation.DefaultProtocolValidatorContext; -import org.scribble.protocol.validation.ProtocolValidationManager; -import org.scribble.protocol.validation.ProtocolValidatorContext; - -public class ProtocolModelValidatorRuleTest { - - private static final String TEST_ROLE = "A"; - - @org.junit.Test - public void testUnprojectableRole() { - ProtocolModel pm=new ProtocolModel(); - - Protocol p=new Protocol(); - - ParameterDefinition pd=new ParameterDefinition(); - pd.setName(TEST_ROLE); - - p.getParameterDefinitions().add(pd); - - pm.setProtocol(p); - - TestScribbleLogger logger=new TestScribbleLogger(); - - DefaultProtocolContext pc=new DefaultProtocolContext(); - - ProtocolValidatorContext pvc=new DefaultProtocolValidatorContext(pc, new TestErrorProjector()); - - ProtocolModelValidatorRule rule=new ProtocolModelValidatorRule(); - rule.validate(pvc, pm, logger); - - logger.verifyErrors(new String[]{ - MessageFormat.format( - java.util.PropertyResourceBundle.getBundle( - "org.scribble.protocol.Messages").getString("_UNPROJECTABLE_ROLES"), - TEST_ROLE) - }, false); - } - - public class TestErrorProjector implements ProtocolProjector { - - public ProtocolModel project(ProtocolContext context, - ProtocolModel model, Role role, Journal journal) { - // Log error - journal.error("An error", null); - return null; - } - - public void setProtocolValidationManager(ProtocolValidationManager pvm) { - } - - public ProtocolValidationManager getProtocolValidationManager() { - return null; - } - - } -} diff --git a/bundles/org.scribble.protocol/src/test/java/org/scribble/protocol/validation/rules/ProtocolValidatorRuleTest.java b/bundles/org.scribble.protocol/src/test/java/org/scribble/protocol/validation/rules/ProtocolValidatorRuleTest.java deleted file mode 100644 index dce132fc8..000000000 --- a/bundles/org.scribble.protocol/src/test/java/org/scribble/protocol/validation/rules/ProtocolValidatorRuleTest.java +++ /dev/null @@ -1,481 +0,0 @@ -/* - * Copyright 2009-11 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.validation.rules; - -import java.text.MessageFormat; - -import org.scribble.protocol.model.*; - -public class ProtocolValidatorRuleTest { - - @org.junit.Test - public void testValidateCannotUseReservedWord() { - Protocol p=new Protocol(); - p.setName("Choice"); - - TestScribbleLogger logger=new TestScribbleLogger(); - - ProtocolValidatorRule rule=new ProtocolValidatorRule(); - rule.validate(null, p, logger); - - logger.verifyErrors(new String[]{ - MessageFormat.format( - java.util.PropertyResourceBundle.getBundle( - "org.scribble.protocol.Messages").getString("_CANNOT_USE_RESERVED_WORD"), - p.getName()) - }); - } - - @org.junit.Test - public void testUnconnectedIntroduces() { - Protocol p=new Protocol(); - ParameterDefinition pd=new ParameterDefinition(); - pd.setName("A"); - p.getParameterDefinitions().add(pd); - - Role roleB=new Role("B"); - Role roleC=new Role("C"); - - Introduces intros=new Introduces(); - intros.setIntroducer(roleB); - intros.getIntroducedRoles().add(roleC); - p.getBlock().add(intros); - - TestScribbleLogger logger=new TestScribbleLogger(); - - ProtocolValidatorRule rule=new ProtocolValidatorRule(); - rule.validate(null, p, logger); - - logger.verifyErrors(new String[]{ - MessageFormat.format( - java.util.PropertyResourceBundle.getBundle( - "org.scribble.protocol.Messages").getString("_UNCONNECTED_ROLE"), - roleB.getName()) - }); - } - - @org.junit.Test - public void testConnectedSimpleSequence() { - Protocol p=new Protocol(); - ParameterDefinition pd=new ParameterDefinition(); - pd.setName("A"); - p.getParameterDefinitions().add(pd); - - Role roleA=new Role("A"); - Role roleB=new Role("B"); - Role roleC=new Role("C"); - Role roleD=new Role("D"); - - Introduces intros=new Introduces(); - intros.setIntroducer(roleA); - intros.getIntroducedRoles().add(roleB); - p.getBlock().add(intros); - - Interaction i1=new Interaction(); - i1.setFromRole(roleA); - i1.getToRoles().add(roleB); - p.getBlock().add(i1); - - Interaction i2=new Interaction(); - i2.setFromRole(roleB); - i2.getToRoles().add(roleC); - p.getBlock().add(i2); - - Interaction i3=new Interaction(); - i3.setFromRole(roleC); - i3.getToRoles().add(roleD); - p.getBlock().add(i3); - - TestScribbleLogger logger=new TestScribbleLogger(); - - ProtocolValidatorRule rule=new ProtocolValidatorRule(); - rule.validate(null, p, logger); - - logger.verifyErrors(new String[]{ - }); - } - - @org.junit.Test - public void testUnconnectedSimpleSequence() { - Protocol p=new Protocol(); - ParameterDefinition pd=new ParameterDefinition(); - pd.setName("A"); - p.getParameterDefinitions().add(pd); - - Role roleA=new Role("A"); - Role roleB=new Role("B"); - Role roleC=new Role("C"); - Role roleD=new Role("D"); - - Introduces intros=new Introduces(); - intros.setIntroducer(roleA); - intros.getIntroducedRoles().add(roleB); - p.getBlock().add(intros); - - Interaction i1=new Interaction(); - i1.setFromRole(roleA); - i1.getToRoles().add(roleB); - p.getBlock().add(i1); - - Interaction i2=new Interaction(); - i2.setFromRole(roleC); - i2.getToRoles().add(roleD); - p.getBlock().add(i2); - - TestScribbleLogger logger=new TestScribbleLogger(); - - ProtocolValidatorRule rule=new ProtocolValidatorRule(); - rule.validate(null, p, logger); - - logger.verifyErrors(new String[]{ - MessageFormat.format( - java.util.PropertyResourceBundle.getBundle( - "org.scribble.protocol.Messages").getString("_UNCONNECTED_ROLE"), - roleC.getName()) - }); - } - - @org.junit.Test - public void testUnconnectedChoice() { - Protocol p=new Protocol(); - ParameterDefinition pd=new ParameterDefinition(); - pd.setName("A"); - p.getParameterDefinitions().add(pd); - - Role roleA=new Role("A"); - Role roleB=new Role("B"); - Role roleC=new Role("C"); - - Introduces intros1=new Introduces(); - intros1.setIntroducer(roleA); - intros1.getIntroducedRoles().add(roleB); - p.getBlock().add(intros1); - - Interaction i1=new Interaction(); - i1.setFromRole(roleA); - i1.getToRoles().add(roleB); - p.getBlock().add(i1); - - Choice choice=new Choice(); - choice.setRole(roleC); - p.getBlock().add(choice); - - Block b1=new Block(); - choice.getPaths().add(b1); - - Block b2=new Block(); - choice.getPaths().add(b2); - - TestScribbleLogger logger=new TestScribbleLogger(); - - ProtocolValidatorRule rule=new ProtocolValidatorRule(); - rule.validate(null, p, logger); - - logger.verifyErrors(new String[]{ - MessageFormat.format( - java.util.PropertyResourceBundle.getBundle( - "org.scribble.protocol.Messages").getString("_UNCONNECTED_ROLE"), - roleC.getName()) - }); - } - - @org.junit.Test - public void testUnconnectedChoicePath() { - Protocol p=new Protocol(); - ParameterDefinition pd=new ParameterDefinition(); - pd.setName("A"); - p.getParameterDefinitions().add(pd); - - Role roleA=new Role("A"); - Role roleB=new Role("B"); - Role roleC=new Role("C"); - - Introduces intros1=new Introduces(); - intros1.setIntroducer(roleA); - intros1.getIntroducedRoles().add(roleB); - p.getBlock().add(intros1); - - Introduces intros2=new Introduces(); - intros2.setIntroducer(roleB); - intros2.getIntroducedRoles().add(roleC); - p.getBlock().add(intros2); - - Interaction i1=new Interaction(); - i1.setFromRole(roleA); - i1.getToRoles().add(roleB); - p.getBlock().add(i1); - - Choice choice=new Choice(); - choice.setRole(roleA); - p.getBlock().add(choice); - - Block b1=new Block(); - choice.getPaths().add(b1); - - Interaction i2=new Interaction(); - i2.setFromRole(roleB); - i2.getToRoles().add(roleC); - b1.add(i2); - - TestScribbleLogger logger=new TestScribbleLogger(); - - ProtocolValidatorRule rule=new ProtocolValidatorRule(); - rule.validate(null, p, logger); - - logger.verifyErrors(new String[]{ - MessageFormat.format( - java.util.PropertyResourceBundle.getBundle( - "org.scribble.protocol.Messages").getString("_UNCONNECTED_ROLE"), - roleB.getName()) - }); - } - - @org.junit.Test - public void testConnectedChoicePath() { - Protocol p=new Protocol(); - ParameterDefinition pd=new ParameterDefinition(); - pd.setName("A"); - p.getParameterDefinitions().add(pd); - - Role roleA=new Role("A"); - Role roleB=new Role("B"); - Role roleC=new Role("C"); - - Introduces intros1=new Introduces(); - intros1.setIntroducer(roleA); - intros1.getIntroducedRoles().add(roleB); - p.getBlock().add(intros1); - - Introduces intros2=new Introduces(); - intros2.setIntroducer(roleB); - intros2.getIntroducedRoles().add(roleC); - p.getBlock().add(intros2); - - Interaction i1=new Interaction(); - i1.setFromRole(roleA); - i1.getToRoles().add(roleB); - p.getBlock().add(i1); - - // Make choice at B instead - Choice choice=new Choice(); - choice.setRole(roleB); - p.getBlock().add(choice); - - Block b1=new Block(); - choice.getPaths().add(b1); - - Interaction i2=new Interaction(); - i2.setFromRole(roleB); - i2.getToRoles().add(roleC); - b1.add(i2); - - TestScribbleLogger logger=new TestScribbleLogger(); - - ProtocolValidatorRule rule=new ProtocolValidatorRule(); - rule.validate(null, p, logger); - - logger.verifyErrors(new String[]{ - }); - } - - @org.junit.Test - public void testUnconnectedRepeat() { - Protocol p=new Protocol(); - ParameterDefinition pd=new ParameterDefinition(); - pd.setName("A"); - p.getParameterDefinitions().add(pd); - - Role roleA=new Role("A"); - Role roleB=new Role("B"); - Role roleC=new Role("C"); - - Introduces intros1=new Introduces(); - intros1.setIntroducer(roleA); - intros1.getIntroducedRoles().add(roleB); - p.getBlock().add(intros1); - - Interaction i1=new Interaction(); - i1.setFromRole(roleA); - i1.getToRoles().add(roleB); - p.getBlock().add(i1); - - Repeat repeat=new Repeat(); - repeat.getRoles().add(roleC); - p.getBlock().add(repeat); - - TestScribbleLogger logger=new TestScribbleLogger(); - - ProtocolValidatorRule rule=new ProtocolValidatorRule(); - rule.validate(null, p, logger); - - logger.verifyErrors(new String[]{ - MessageFormat.format( - java.util.PropertyResourceBundle.getBundle( - "org.scribble.protocol.Messages").getString("_UNCONNECTED_ROLE"), - roleC.getName()) - }); - } - - @org.junit.Test - public void testUnconnectedRepeatBody() { - Protocol p=new Protocol(); - ParameterDefinition pd=new ParameterDefinition(); - pd.setName("A"); - p.getParameterDefinitions().add(pd); - - Role roleA=new Role("A"); - Role roleB=new Role("B"); - Role roleC=new Role("C"); - - Introduces intros1=new Introduces(); - intros1.setIntroducer(roleA); - intros1.getIntroducedRoles().add(roleB); - p.getBlock().add(intros1); - - Introduces intros2=new Introduces(); - intros2.setIntroducer(roleB); - intros2.getIntroducedRoles().add(roleC); - p.getBlock().add(intros2); - - Interaction i1=new Interaction(); - i1.setFromRole(roleA); - i1.getToRoles().add(roleB); - p.getBlock().add(i1); - - Repeat repeat=new Repeat(); - repeat.getRoles().add(roleA); - p.getBlock().add(repeat); - - Interaction i2=new Interaction(); - i2.setFromRole(roleB); - i2.getToRoles().add(roleC); - repeat.getBlock().add(i2); - - TestScribbleLogger logger=new TestScribbleLogger(); - - ProtocolValidatorRule rule=new ProtocolValidatorRule(); - rule.validate(null, p, logger); - - logger.verifyErrors(new String[]{ - MessageFormat.format( - java.util.PropertyResourceBundle.getBundle( - "org.scribble.protocol.Messages").getString("_UNCONNECTED_ROLE"), - roleB.getName()) - }); - } - - @org.junit.Test - public void testConnectedRepeatBody() { - Protocol p=new Protocol(); - ParameterDefinition pd=new ParameterDefinition(); - pd.setName("A"); - p.getParameterDefinitions().add(pd); - - Role roleA=new Role("A"); - Role roleB=new Role("B"); - Role roleC=new Role("C"); - - Introduces intros1=new Introduces(); - intros1.setIntroducer(roleA); - intros1.getIntroducedRoles().add(roleB); - p.getBlock().add(intros1); - - Introduces intros2=new Introduces(); - intros2.setIntroducer(roleB); - intros2.getIntroducedRoles().add(roleC); - p.getBlock().add(intros2); - - Interaction i1=new Interaction(); - i1.setFromRole(roleA); - i1.getToRoles().add(roleB); - p.getBlock().add(i1); - - // Make decision at B instead - Repeat repeat=new Repeat(); - repeat.getRoles().add(roleB); - p.getBlock().add(repeat); - - Interaction i2=new Interaction(); - i2.setFromRole(roleB); - i2.getToRoles().add(roleC); - repeat.getBlock().add(i2); - - TestScribbleLogger logger=new TestScribbleLogger(); - - ProtocolValidatorRule rule=new ProtocolValidatorRule(); - rule.validate(null, p, logger); - - logger.verifyErrors(new String[]{ - }); - } - - @org.junit.Test - public void testUnconnectedParallel() { - Protocol p=new Protocol(); - ParameterDefinition pd=new ParameterDefinition(); - pd.setName("A"); - p.getParameterDefinitions().add(pd); - - Role roleA=new Role("A"); - Role roleB=new Role("B"); - Role roleC=new Role("C"); - Role roleD=new Role("D"); - - Introduces intros1=new Introduces(); - intros1.setIntroducer(roleA); - intros1.getIntroducedRoles().add(roleB); - p.getBlock().add(intros1); - - Interaction i1=new Interaction(); - i1.setFromRole(roleA); - i1.getToRoles().add(roleB); - p.getBlock().add(i1); - - Parallel parallel=new Parallel(); - p.getBlock().add(parallel); - - Block b1=new Block(); - parallel.getPaths().add(b1); - - Block b2=new Block(); - parallel.getPaths().add(b2); - - Interaction i2=new Interaction(); - i2.setFromRole(roleB); - i2.getToRoles().add(roleC); - b1.add(i2); - - // Not connected, because this concurrent path is not connected to - // the interaction sentences preceding the parallel - the other parallel - // paths don't count - Interaction i3=new Interaction(); - i3.setFromRole(roleC); - i3.getToRoles().add(roleD); - b2.add(i3); - - TestScribbleLogger logger=new TestScribbleLogger(); - - ProtocolValidatorRule rule=new ProtocolValidatorRule(); - rule.validate(null, p, logger); - - logger.verifyErrors(new String[]{ - MessageFormat.format( - java.util.PropertyResourceBundle.getBundle( - "org.scribble.protocol.Messages").getString("_UNCONNECTED_ROLE"), - roleC.getName()) - }); - } -} diff --git a/bundles/org.scribble.protocol/src/test/java/org/scribble/protocol/validation/rules/RecursionValidatorRuleTest.java b/bundles/org.scribble.protocol/src/test/java/org/scribble/protocol/validation/rules/RecursionValidatorRuleTest.java deleted file mode 100644 index 36242a745..000000000 --- a/bundles/org.scribble.protocol/src/test/java/org/scribble/protocol/validation/rules/RecursionValidatorRuleTest.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.validation.rules; - -import java.text.MessageFormat; - -import org.scribble.protocol.model.*; - -public class RecursionValidatorRuleTest { - - @org.junit.Test - public void testRecursionWithValidLabel() { - - Protocol prot1=new Protocol(); - - Introduces plist1=new Introduces(); - prot1.getBlock().add(plist1); - - Role part1=new Role(); - part1.setName("part1"); - plist1.getIntroducedRoles().add(part1); - - Role part2=new Role(); - part2.setName("part2"); - plist1.getIntroducedRoles().add(part2); - - RecBlock r1=new RecBlock(); - prot1.getBlock().add(r1); - - r1.setLabel("transaction"); - - Recursion rec=new Recursion(); - rec.setLabel("transaction"); - - r1.getBlock().add(rec); - - TestScribbleLogger logger=new TestScribbleLogger(); - - RecursionValidatorRule rule=new RecursionValidatorRule(); - rule.validate(null, rec, logger); - - logger.verifyErrors(new String[]{ - }); - } - - @org.junit.Test - public void testRecursionWithNoEnclosingLabelBlock() { - - Protocol prot1=new Protocol(); - - Introduces plist1=new Introduces(); - prot1.getBlock().add(plist1); - - Role part1=new Role(); - part1.setName("part1"); - plist1.getIntroducedRoles().add(part1); - - Role part2=new Role(); - part2.setName("part2"); - plist1.getIntroducedRoles().add(part2); - - RecBlock r1=new RecBlock(); - prot1.getBlock().add(r1); - - r1.setLabel("notransaction"); - - Recursion rec=new Recursion(); - rec.setLabel("transaction"); - - r1.getBlock().add(rec); - - TestScribbleLogger logger=new TestScribbleLogger(); - - RecursionValidatorRule rule=new RecursionValidatorRule(); - rule.validate(null, rec, logger); - - logger.verifyErrors(new String[]{ - MessageFormat.format( - java.util.PropertyResourceBundle.getBundle( - "org.scribble.protocol.Messages").getString("_NO_ENCLOSING_RECUR"), - rec.getLabel()) - }); - } -} diff --git a/bundles/org.scribble.protocol/src/test/java/org/scribble/protocol/validation/rules/RepeatValidatorRuleTest.java b/bundles/org.scribble.protocol/src/test/java/org/scribble/protocol/validation/rules/RepeatValidatorRuleTest.java deleted file mode 100644 index 2f5126935..000000000 --- a/bundles/org.scribble.protocol/src/test/java/org/scribble/protocol/validation/rules/RepeatValidatorRuleTest.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.validation.rules; - -import java.text.MessageFormat; - -import org.scribble.protocol.model.*; - -public class RepeatValidatorRuleTest { - - @org.junit.Test - public void testRepeatUnknownRole() { - - Protocol prot1=new Protocol(); - - Introduces plist1=new Introduces(); - prot1.getBlock().add(plist1); - - Role part1=new Role(); - part1.setName("part1"); - plist1.getIntroducedRoles().add(part1); - - Role part2=new Role(); - part2.setName("part2"); - plist1.getIntroducedRoles().add(part2); - - Repeat r1=new Repeat(); - prot1.getBlock().add(r1); - - Role part3=new Role(); - part3.setName("part3"); - - r1.getRoles().add(part3); - - TestScribbleLogger logger=new TestScribbleLogger(); - - RepeatValidatorRule rule=new RepeatValidatorRule(); - rule.validate(null, r1, logger); - - logger.verifyErrors(new String[]{ - MessageFormat.format( - java.util.PropertyResourceBundle.getBundle( - "org.scribble.protocol.Messages").getString("_UNKNOWN_ROLE"), - part3.getName()) - }); - } - - @org.junit.Test - public void testRepeatValidRole() { - - Protocol prot1=new Protocol(); - - Introduces plist1=new Introduces(); - prot1.getBlock().add(plist1); - - Role part1=new Role(); - part1.setName("part1"); - plist1.getIntroducedRoles().add(part1); - - Role part2=new Role(); - part2.setName("part2"); - plist1.getIntroducedRoles().add(part2); - - Repeat r1=new Repeat(); - prot1.getBlock().add(r1); - - Role part3=new Role(); - part3.setName("part2"); - - r1.getRoles().add(part3); - - TestScribbleLogger logger=new TestScribbleLogger(); - - RepeatValidatorRule rule=new RepeatValidatorRule(); - rule.validate(null, r1, logger); - - logger.verifyErrors(new String[]{ - }); - } -} diff --git a/bundles/org.scribble.protocol/src/test/java/org/scribble/protocol/validation/rules/TestScribbleLogger.java b/bundles/org.scribble.protocol/src/test/java/org/scribble/protocol/validation/rules/TestScribbleLogger.java deleted file mode 100644 index 80d62f5f8..000000000 --- a/bundles/org.scribble.protocol/src/test/java/org/scribble/protocol/validation/rules/TestScribbleLogger.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright 2009 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.validation.rules; - -import java.util.Map; - -import org.scribble.common.logging.Journal; - -import static org.junit.Assert.*; - -@org.junit.Ignore -public class TestScribbleLogger implements Journal { - - public void debug(String issue, Map props) { - } - - public void error(String issue, Map props) { - m_errors.add(issue); - } - - /** - * This method verifies the supplied list of errors, - * not expecting any other errors to have occurred. - * - * @param errors The errors - */ - public void verifyErrors(String[] errors) { - verifyErrors(errors, true); - } - - /** - * This method verifies the supplied errors. If the 'completeList' - * flag is true, then the supplied list of errors is the complete - * list of expected errors, so any additional errors should be - * flagged as an error. - * - * @param errors The list of errors - * @param completeList Whether this is a complete list - */ - public void verifyErrors(String[] errors, boolean completeList) { - java.util.List logged=new java.util.Vector(m_errors); - - for (int i=0; i < errors.length; i++) { - int ind=logged.indexOf(errors[i]); - - if (ind == -1) { - fail("Expected message '"+errors[i]+"' did not occur"); - } else { - logged.remove(ind); - } - } - - if (completeList && logged.size() > 0) { - fail("Unexpected errors occurred: "+logged); - } - } - - public void info(String issue, Map props) { - } - - public void trace(String issue, Map props) { - } - - public void warning(String issue, Map props) { - } - - private java.util.List m_errors=new java.util.Vector(); -} diff --git a/bundles/org.scribble.protocol/src/test/resources/context/Main1.spr b/bundles/org.scribble.protocol/src/test/resources/context/Main1.spr deleted file mode 100644 index 66d6f0791..000000000 --- a/bundles/org.scribble.protocol/src/test/resources/context/Main1.spr +++ /dev/null @@ -1 +0,0 @@ -Main1 \ No newline at end of file diff --git a/bundles/org.scribble.protocol/src/test/resources/context/Ref1.spr b/bundles/org.scribble.protocol/src/test/resources/context/Ref1.spr deleted file mode 100644 index 034127e2b..000000000 --- a/bundles/org.scribble.protocol/src/test/resources/context/Ref1.spr +++ /dev/null @@ -1 +0,0 @@ -Ref1 \ No newline at end of file diff --git a/bundles/org.scribble.protocol/src/test/resources/context/submain/Main2.spr b/bundles/org.scribble.protocol/src/test/resources/context/submain/Main2.spr deleted file mode 100644 index e1a65dfa0..000000000 --- a/bundles/org.scribble.protocol/src/test/resources/context/submain/Main2.spr +++ /dev/null @@ -1 +0,0 @@ -Main2 \ No newline at end of file diff --git a/bundles/org.scribble.protocol/src/test/resources/context/subref/Ref2.spr b/bundles/org.scribble.protocol/src/test/resources/context/subref/Ref2.spr deleted file mode 100644 index 48424ff19..000000000 --- a/bundles/org.scribble.protocol/src/test/resources/context/subref/Ref2.spr +++ /dev/null @@ -1 +0,0 @@ -Ref2 \ No newline at end of file diff --git a/bundles/pom.xml b/bundles/pom.xml deleted file mode 100644 index ca747ff59..000000000 --- a/bundles/pom.xml +++ /dev/null @@ -1,61 +0,0 @@ - - 4.0.0 - org.scribble - bundles - pom - 2.1.0-SNAPSHOT - Scribble::Bundles - - - org.scribble - parent - 2.1.0-SNAPSHOT - - - - org.scribble.common - org.scribble.protocol - org.scribble.protocol.parser - org.scribble.protocol.projection - org.scribble.protocol.conformance - org.scribble.protocol.monitor - org.scribble.protocol.export.monitor - org.scribble.command - - - - - - - - - org.apache.maven.plugins - maven-jar-plugin - 2.2 - - - META-INF/MANIFEST.MF - - - - - org.apache.felix - maven-bundle-plugin - - - bundle-manifest - process-classes - - manifest - - - - - - - - - - diff --git a/header.txt b/header.txt new file mode 100644 index 000000000..794754c8a --- /dev/null +++ b/header.txt @@ -0,0 +1,11 @@ +Copyright ${project.inceptionYear} The Scribble 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 + +http://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. diff --git a/mvnw b/mvnw new file mode 100755 index 000000000..6ecc150ae --- /dev/null +++ b/mvnw @@ -0,0 +1,236 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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 +# +# http://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. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Maven2 Start Up Batch script +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# M2_HOME - location of maven2's installed home dir +# MAVEN_OPTS - parameters passed to the Java VM when running Maven +# e.g. to debug Maven itself, use +# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +# MAVEN_SKIP_RC - flag to disable loading of mavenrc files +# ---------------------------------------------------------------------------- + +if [ -z "$MAVEN_SKIP_RC" ] ; then + + if [ -f /etc/mavenrc ] ; then + . /etc/mavenrc + fi + + if [ -f "$HOME/.mavenrc" ] ; then + . "$HOME/.mavenrc" + fi + +fi + +# OS specific support. $var _must_ be set to either true or false. +cygwin=false; +darwin=false; +mingw=false +case "`uname`" in + CYGWIN*) cygwin=true ;; + MINGW*) mingw=true;; + Darwin*) darwin=true + # + # Look for the Apple JDKs first to preserve the existing behaviour, and then look + # for the new JDKs provided by Oracle. + # + if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK ] ; then + # + # Apple JDKs + # + export JAVA_HOME=/System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Home + fi + + if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Java/JavaVirtualMachines/CurrentJDK ] ; then + # + # Apple JDKs + # + export JAVA_HOME=/System/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home + fi + + if [ -z "$JAVA_HOME" ] && [ -L "/Library/Java/JavaVirtualMachines/CurrentJDK" ] ; then + # + # Oracle JDKs + # + export JAVA_HOME=/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home + fi + + if [ -z "$JAVA_HOME" ] && [ -x "/usr/libexec/java_home" ]; then + # + # Apple JDKs + # + export JAVA_HOME=`/usr/libexec/java_home` + fi + ;; +esac + +if [ -z "$JAVA_HOME" ] ; then + if [ -r /etc/gentoo-release ] ; then + JAVA_HOME=`java-config --jre-home` + fi +fi + +if [ -z "$M2_HOME" ] ; then + ## resolve links - $0 may be a link to maven's home + 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 + + saveddir=`pwd` + + M2_HOME=`dirname "$PRG"`/.. + + # make it fully qualified + M2_HOME=`cd "$M2_HOME" && pwd` + + cd "$saveddir" + # echo Using m2 at $M2_HOME +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin ; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --unix "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --unix "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --unix "$CLASSPATH"` +fi + +# For Migwn, ensure paths are in UNIX format before anything is touched +if $mingw ; then + [ -n "$M2_HOME" ] && + M2_HOME="`(cd "$M2_HOME"; pwd)`" + [ -n "$JAVA_HOME" ] && + JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" + # TODO classpath? +fi + +if [ -z "$JAVA_HOME" ]; then + javaExecutable="`which javac`" + if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then + # readlink(1) is not available as standard on Solaris 10. + readLink=`which readlink` + if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then + if $darwin ; then + javaHome="`dirname \"$javaExecutable\"`" + javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" + else + javaExecutable="`readlink -f \"$javaExecutable\"`" + fi + javaHome="`dirname \"$javaExecutable\"`" + javaHome=`expr "$javaHome" : '\(.*\)/bin'` + JAVA_HOME="$javaHome" + export JAVA_HOME + fi + fi +fi + +if [ -z "$JAVACMD" ] ; then + 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 + else + JAVACMD="`which java`" + fi +fi + +if [ ! -x "$JAVACMD" ] ; then + echo "Error: JAVA_HOME is not defined correctly." >&2 + echo " We cannot execute $JAVACMD" >&2 + exit 1 +fi + +if [ -z "$JAVA_HOME" ] ; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + local basedir=$(pwd) + local wdir=$(pwd) + while [ "$wdir" != '/' ] ; do + if [ -d "$wdir"/.mvn ] ; then + basedir=$wdir + break + fi + wdir=$(cd "$wdir/.."; pwd) + done + echo "${basedir}" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + echo "$(tr -s '\n' ' ' < "$1")" + fi +} + +export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-$(find_maven_basedir)} +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --path --windows "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --windows "$CLASSPATH"` + [ -n "$MAVEN_PROJECTBASEDIR" ] && + MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` +fi + +# Provide a "standardized" way to retrieve the CLI args that will +# work with both Windows and non-Windows executions. +MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" +export MAVEN_CMD_LINE_ARGS + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +# avoid using MAVEN_CMD_LINE_ARGS below since that would loose parameter escaping in $@ +exec "$JAVACMD" \ + $MAVEN_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/mvnw.cmd b/mvnw.cmd new file mode 100644 index 000000000..8e2b7459f --- /dev/null +++ b/mvnw.cmd @@ -0,0 +1,146 @@ +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Maven2 Start Up Batch script +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM M2_HOME - location of maven2's installed home dir +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" +if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +set MAVEN_CMD_LINE_ARGS=%MAVEN_CONFIG% %* + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" + +set WRAPPER_JAR=""%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +# avoid using MAVEN_CMD_LINE_ARGS below since that would loose parameter escaping in %* +%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" +if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%" == "on" pause + +if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% + +exit /B %ERROR_CODE% diff --git a/pom.xml b/pom.xml index 84611ed41..188655f30 100644 --- a/pom.xml +++ b/pom.xml @@ -1,237 +1,418 @@ - - 4.0.0 - org.scribble - parent - 2.1.0-SNAPSHOT - pom - Scribble - http://www.scribble.org - - Scribble - - - - https://github.com/scribble - https://github.com/scribble - - - - - Apache 2 - http://www.apache.org/licenses/LICENSE-2.0.txt - repo - Apache License V2 - - - - - - Gary Brown - objectiser - gary@pi4tech.com - Scribble.org - - Developer - - +0 - - - - - Scribble.org - 2008 - 2.1.0-SNAPSHOT - 2.1.0-SNAPSHOT - 3.0.1 - 1.6.0 - - 4.2.0 - 3.2 - 1.2.14 - 4.7 - 5.3.0 - - - - build - bundles - qa - apidocs - - - - - - org.apache.felix - org.apache.felix.framework - ${felix.version} - - - org.apache.felix - org.apache.felix.main - ${felix.version} - - - org.apache.felix - org.apache.felix.scr - ${felix.scr.version} - - - org.apache.felix - org.osgi.core - ${osgi.version} - - - org.osgi - org.osgi.compendium - 4.2.0 - - - log4j - log4j - ${log4j.version} - - - junit - junit - ${junit.version} - - - - - - - - - - - org.apache.maven.plugins - maven-jar-plugin - 2.2 - - - org.apache.maven.plugins - maven-javadoc-plugin - 2.2 - - true - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 2.3.2 - - 1.5 - 1.5 - false - false - true - -verbose - - - - - org.apache.maven.plugins - maven-source-plugin - - - attach-sources - verify - - jar - - - - - - maven-surefire-plugin - 2.5 - - - **/*TestCase.java - **/*Test.java - - - - - - org.apache.maven.plugins - maven-checkstyle-plugin - 2.6 - - checkstyle/checkstyle.xml - false - checkstyle/suppressions.xml - false - - - + + + + 4.0.0 + + + org.scribble + parent + 0.5.1-SNAPSHOT + pom + + + + + org.scribble + scribble-core + ${project.version} + + + org.scribble + scribble-parser + ${project.version} + + + org.scribble + scribble-ast + ${project.version} + + + org.scribble + scribble-cli + ${project.version} + + + org.scribble + scribble-runtime + ${project.version} + + + org.scribble + scribble-codegen + ${project.version} + + + org.scribble + scribble-main + ${project.version} + + + + org.scribble + scribble-test + ${project.version} + + + + org.antlr + antlr-runtime + ${antlr.version} + + + junit + junit + ${junit.version} + + - org.scribble - build - ${project.version} + commons-io + commons-io + ${version.commons-io} - - - - check-style - site - - checkstyle - - - - - - - - - - - org.apache.maven.plugins - maven-surefire-report-plugin - - - - - - - - jboss-public-repository-group - JBoss Public Maven Repository Group - https://repository.jboss.org/nexus/content/groups/public/ - - true - never - - - true - never - - - - - - - - jboss-releases-repository - JBoss Releases Repository - https://repository.jboss.org/nexus/service/local/staging/deploy/maven2/ - - - jboss-snapshots-repository - JBoss Snapshots Repository - https://repository.jboss.org/nexus/content/repositories/snapshots/ - false - - - - - + + + + + + scribble-core + scribble-runtime + scribble-ast + scribble-parser + scribble-codegen + scribble-main + scribble-cli + scribble-test + scribble-dist + scribble-demos + + + + 3.4 + 4.13.1 + + + 2.7 + + + 1.8 + 1.8 + true + + + 2.5.3 + 3.2.1 + + 2.9 + 0.3.4 + 0.1.0 + + + UTF-8 + + + + scribble-java + Scribble + http://www.scribble.org + 2008 + + + + Apache 2 + http://www.apache.org/licenses/LICENSE-2.0.txt + repo + Apache License V2 + + + + + Scribble + http://www.scribble.org + + + + + Gary Brown + objectiser + gary.pi4tech@gmail.com + Scribble.org + + Developer + + +0 + + + Raymond Hu + rhu1 + r.z.h.hu@herts.ac.uk + University of Hertfordshire + + Developer + + +0 + + + + + + + + + + + org.apache.maven.plugins + maven-jar-plugin + 2.2 + + + org.apache.maven.plugins + maven-javadoc-plugin + ${version.maven-javadoc-plugin} + + + org.apache.maven.plugins + maven-antrun-plugin + 1.7 + + + org.apache.maven.plugins + maven-assembly-plugin + 2.4 + + + org.jboss.maven.plugins + maven-jdocbook-plugin + 2.3.8 + + + com.mycila + license-maven-plugin + 3.0 + + + + + io.takari + maven + ${version.io.takari-maven} + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.2 + + + + org.apache.maven.plugins + maven-source-plugin + ${version.maven-source-plugin} + + + attach-sources + verify + + jar + + + + + + maven-surefire-plugin + 2.5 + + + **/*TestCase.java + **/*Test.java + + + **/ScribAllTest.java + + + + + + + com.mycila + license-maven-plugin + +

header.txt
+ true + true + + **/*.xml + **/*.g + **/*.scr + **/*.policy + **/*.txt + mvnw + mvnw.cmd + travis/publish.sh + .mvn/wrapper/maven-wrapper.properties + **/*.versionsBackup + **/Scribble-0.3.original + bin/*.sh + scribblec.sh + **/*.swp + scribble-test/**/*.* + + **/IGNORE + + scribble-f17/**/* + + + + + + check + + compile + + + + + maven-release-plugin + ${version.maven-release-plugin} + + false + release + true + @{project.version} + + + + io.zipkin.centralsync-maven-plugin + centralsync-maven-plugin + ${version.io.zikin.centralsync-maven-plugin} + + scribble + maven + scribble-java + + + + + + + + + org.apache.maven.plugins + maven-surefire-report-plugin + 3.0.0-M5 + + + + + + + https://github.com/scribble/scribble-java + scm:git:https://github.com/scribble/scribble-java.git + + + scm:git:https://github.com/scribble/scribble-java.git + + HEAD + + + + + + + release + + + + + maven-source-plugin + ${version.maven-source-plugin} + + + attach-sources + + jar + + + + + + + maven-javadoc-plugin + ${version.maven-javadoc-plugin} + + false + + + + attach-javadocs + + jar + + package + + + + + + + + + diff --git a/qa/org.scribble.protocol.ctk/LICENSE.txt b/qa/org.scribble.protocol.ctk/LICENSE.txt deleted file mode 100644 index 29f81d812..000000000 --- a/qa/org.scribble.protocol.ctk/LICENSE.txt +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - 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 - - http://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. diff --git a/qa/org.scribble.protocol.ctk/META-INF/MANIFEST.MF b/qa/org.scribble.protocol.ctk/META-INF/MANIFEST.MF deleted file mode 100644 index 25127699a..000000000 --- a/qa/org.scribble.protocol.ctk/META-INF/MANIFEST.MF +++ /dev/null @@ -1,12 +0,0 @@ -Manifest-Version: 1.0 -Bundle-ManifestVersion: 2 -Bundle-Name: Scribble Protocol CTK -Bundle-SymbolicName: org.scribble.protocol.ctk -Bundle-Version: 2.0.0.qualifier -Bundle-Vendor: www.scribble.org -Import-Package: org.scribble.command.simulate, - org.scribble.protocol.export.monitor, - org.scribble.protocol.monitor, - org.scribble.protocol.monitor.model -Require-Bundle: org.scribble.protocol, - org.scribble.common diff --git a/qa/org.scribble.protocol.ctk/build.properties b/qa/org.scribble.protocol.ctk/build.properties deleted file mode 100644 index ab34875cc..000000000 --- a/qa/org.scribble.protocol.ctk/build.properties +++ /dev/null @@ -1,13 +0,0 @@ -source.. = src/test/java/ -output.. = bin/ -bin.includes = META-INF/,\ - .,\ - LICENSE.txt -src.includes = META-INF/,\ - src/,\ - pom.xml,\ - build.properties,\ - .settings/,\ - .project,\ - .classpath,\ - LICENSE.txt diff --git a/qa/org.scribble.protocol.ctk/pom.xml b/qa/org.scribble.protocol.ctk/pom.xml deleted file mode 100644 index 2e8cfee0e..000000000 --- a/qa/org.scribble.protocol.ctk/pom.xml +++ /dev/null @@ -1,149 +0,0 @@ - - 4.0.0 - org.scribble.qa - org.scribble.protocol.ctk - jar - 2.1.0-SNAPSHOT - Scribble::QA::Protocol::CTK - - - org.scribble - qa - 2.1.0-SNAPSHOT - - - - - org.scribble.bundles - org.scribble.common - ${scribble.bundles.version} - - - org.scribble.bundles - org.scribble.protocol - ${scribble.bundles.version} - - - org.scribble.bundles - org.scribble.protocol.parser - ${scribble.bundles.version} - - - org.scribble.bundles - org.scribble.protocol.projection - ${scribble.bundles.version} - - - org.scribble.bundles - org.scribble.protocol.export.monitor - ${scribble.bundles.version} - - - org.scribble.bundles - org.scribble.command - ${scribble.version} - - - org.osgi - org.osgi.core - ${osgi.version} - - - org.antlr - antlr - ${antlr.version} - - - junit - junit - test - - - - - ${artifactId}_${scribble.version} - - - - - - - org.apache.maven.plugins - maven-jar-plugin - 2.2 - - - META-INF/MANIFEST.MF - - - - - org.apache.maven.plugins - maven-javadoc-plugin - 2.2 - - true - - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 2.0.2 - - - 1.5 - 1.5 - false - false - - - - - - org.apache.maven.plugins - maven-source-plugin - - - attach-sources - verify - - jar - - - - - - maven-surefire-plugin - - - **/*TestCase.java - **/*Test.java - - - - - org.apache.maven.plugins - maven-deploy-plugin - - true - - - - - - - - - org.apache.maven.plugins - maven-surefire-report-plugin - - - - - diff --git a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/CTKUtil.java b/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/CTKUtil.java deleted file mode 100644 index 535306f6a..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/CTKUtil.java +++ /dev/null @@ -1,403 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.ctk; - -import org.scribble.command.simulate.Event; -import org.scribble.command.simulate.EventProcessor; -import org.scribble.common.logging.Journal; -import org.scribble.common.resource.Content; -import org.scribble.common.resource.DefaultResourceLocator; -import org.scribble.common.resource.ResourceContent; -import org.scribble.protocol.DefaultProtocolContext; -import org.scribble.protocol.ProtocolContext; -import org.scribble.protocol.model.*; -import org.scribble.protocol.monitor.ProtocolMonitor; -import org.scribble.protocol.monitor.ProtocolMonitorFactory; -import org.scribble.protocol.parser.DefaultProtocolParserManager; -import org.scribble.protocol.parser.ProtocolParser; -import org.scribble.protocol.parser.ProtocolParserManager; - -import java.io.IOException; -import java.util.Comparator; - -import static org.junit.Assert.*; - -public class CTKUtil { - - public static ProtocolParser getParser() { - org.scribble.protocol.parser.ProtocolParser parser=null; - - try { - String clsName=System.getProperty("scribble.protocol.parser"); - - if (clsName == null) { - clsName = "org.scribble.protocol.parser.antlr.ANTLRProtocolParser"; - } - - Class cls=Class.forName(clsName); - - parser = (org.scribble.protocol.parser.ProtocolParser) - cls.newInstance(); - - } catch (Exception e) { - fail("Failed to get Protocol parser: "+e); - } - - return (parser); - } - - public static ProtocolModel getModel(String filename, TestJournal logger) { - ProtocolModel ret=null; - - java.net.URL url= - ClassLoader.getSystemResource(filename); - - if (url == null) { - fail("Failed to load protocol '"+filename+"'"); - } - - org.scribble.protocol.parser.ProtocolParser parser=getParser(); - - try { - Content content=new ResourceContent(url.toURI()); - - ret = parser.parse(null, content, logger); - } catch (Exception e) { - fail("Failed to parse protocol: "+e); - } - - assertNotNull(ret); - assertTrue(logger.getErrorCount() == 0); - - return (ret); - } - - public static String getModelText(String filename) { - String ret=null; - - java.io.InputStream is= - ClassLoader.getSystemResourceAsStream(filename); - - if (is == null) { - fail("Failed to load protocol '"+filename+"'"); - } - - try { - byte[] b=new byte[is.available()]; - is.read(b); - - is.close(); - - ret = new String(b); - - } catch (Exception e) { - fail("Failed to load protocol '"+filename+"': "+e); - } - - return (ret); - } - - /** - * This method returns an instance of a protocol monitor. - * - * @return The protocol monitor - */ - public static ProtocolMonitor getMonitor() { - return (ProtocolMonitorFactory.createProtocolMonitor()); - } - - /** - * This method returns the list of monitoring events from the supplied filename. - * - * @param filename The filename containing the list of monitoring events - * @return The list of monitoring events, or null if failed to load - */ - public static java.util.List getMonitorEvents(String filename) { - java.util.List ret=null; - - java.io.InputStream is= - ClassLoader.getSystemResourceAsStream(filename); - - if (is == null) { - fail("Failed to load protocol '"+filename+"'"); - } - - EventProcessor eventProcessor=new EventProcessor(); - - try { - eventProcessor.initialize(is); - - ret = eventProcessor.getEvents(); - - is.close(); - } catch (Exception e) { - fail("Failed to load monitoring events: "+e); - } - - return (ret); - } - - /** - * This method validates a model against the expected model. - * - * @param model The model constructed by the parser - * @param expected The expected model - */ - public static void verify(ProtocolModel model, ProtocolModel expected) { - java.util.List mlist=sequence(model); - java.util.List elist=sequence(expected); - - assertNotNull(mlist); - assertNotNull(elist); - - int len=mlist.size(); - - if (len > elist.size()) { - len = elist.size(); - } - - for (int i=0; i < len; i++) { - if (mlist.get(i).getClass() != elist.get(i).getClass()) { - fail("Element ("+i+") mismatch class model="+ - mlist.get(i).getClass()+" expected="+ - elist.get(i).getClass()); - } else { - Comparator comparator= - ComparatorUtil.getComparator(mlist.get(i).getClass()); - - if (comparator == null) { - fail("No comparator found for type: "+mlist.get(i).getClass()); - } else if (comparator.compare(mlist.get(i), elist.get(i)) != 0) { - fail("Element ("+i+") did not match: "+mlist.get(i)+ - " expected="+elist.get(i)); - } - } - } - - assertTrue(mlist.size() == elist.size()); - } - - /** - * This method converts the model tree into a flat list of model - * objects which can be compared. - * - * @param model The model - * @return The list of model objects - */ - protected static java.util.List sequence(ProtocolModel model) { - final java.util.List ret=new java.util.Vector(); - - model.visit(new DefaultVisitor() { - - @Override - public boolean start(Block elem) { - ret.add(elem); - return true; - } - - @Override - public boolean start(Choice elem) { - ret.add(elem); - return true; - } - - @Override - public boolean start(DirectedChoice elem) { - ret.add(elem); - return true; - } - - @Override - public boolean start(OnMessage elem) { - ret.add(elem); - return true; - } - - @Override - public boolean start(Parallel elem) { - ret.add(elem); - return true; - } - - @Override - public boolean start(Protocol elem) { - ret.add(elem); - return true; - } - - @Override - public boolean start(Repeat elem) { - ret.add(elem); - return true; - } - - @Override - public boolean start(RecBlock elem) { - ret.add(elem); - return true; - } - - @Override - public boolean start(Do elem) { - ret.add(elem); - return true; - } - - @Override - public boolean start(Interrupt elem) { - ret.add(elem); - return true; - } - - @Override - public void accept(Run elem) { - ret.add(elem); - } - - @Override - public void accept(TypeImportList elem) { - ret.add(elem); - } - - @Override - public void accept(ProtocolImportList elem) { - ret.add(elem); - } - - @Override - public void accept(Interaction elem) { - ret.add(elem); - } - - @Override - public void accept(Introduces elem) { - ret.add(elem); - } - - @Override - public void accept(Recursion elem) { - ret.add(elem); - } - - @Override - public void accept(Inline elem) { - ret.add(elem); - } - - @Override - public void accept(TypeImport elem) { - ret.add(elem); - } - - @Override - public void accept(ProtocolImport elem) { - ret.add(elem); - } - - @Override - public void accept(End elem) { - ret.add(elem); - } - - }); - - return (ret); - } - - public static org.scribble.protocol.ProtocolContext getProtocolContext(String baseDir) { - final org.scribble.protocol.parser.ProtocolParser parser=getParser(); - - ProtocolParserManager ppm=new DefaultProtocolParserManager() { - - @Override - public ProtocolModel parse(ProtocolContext context, Content content, Journal journal) - throws IOException { - return (parser.parse(context, content, journal)); - } - - }; - - DefaultResourceLocator locator=null; - - if (baseDir != null) { - java.net.URL url=ClassLoader.getSystemResource(baseDir); - - if (url == null) { - fail("Failed to find base directory '"+baseDir+"'"); - } - - locator=new DefaultResourceLocator(new java.io.File(url.getPath())); - } - - DefaultProtocolContext ret=new DefaultProtocolContext(ppm, locator); - - //ret.setProtocolValidationManager(new DefaultProtocolValidationManager()); - //ret.getProtocolValidationManager().getValidators().add(new DefaultProtocolComponentValidator()); - - return (ret); - } - - public static ProtocolModel project(ProtocolModel model, Role role, - Journal logger, ProtocolContext context) { - ProtocolModel ret=null; - - org.scribble.protocol.projection.ProtocolProjector projector=null; - - try { - String clsName=System.getProperty("scribble.protocol.projector"); - - if (clsName == null) { - clsName = "org.scribble.protocol.projection.impl.ProtocolProjectorImpl"; - } - - Class cls=Class.forName(clsName); - - projector = (org.scribble.protocol.projection.ProtocolProjector) - cls.newInstance(); - - } catch (Exception e) { - fail("Failed to get Protocol projector: "+e); - } - - ret = projector.project(context, model, role, logger); - - return (ret); - } - - public static void checkProjectsSuccessfully(String globalModelFile, String localModelFile, ProtocolContext context) { - String projectAsRole = getProjectAsRole(localModelFile); - - TestJournal logger=new TestJournal(); - - ProtocolModel model=getModel(globalModelFile, logger); - ProtocolModel expected=getModel(localModelFile, logger); - - Role role=new Role(projectAsRole); - ProtocolModel projected=project(model, role, logger, context); - - if (logger.getErrorCount() > 0) { - fail("Projection to role '"+role+"' failed: "+logger.getErrors()); - } - - verify(projected, expected); - } - - private static String getProjectAsRole(String localModelFile) { - String roleDotSpr = localModelFile.substring(localModelFile.indexOf('@') + 1); - return roleDotSpr.substring(0, roleDotSpr.indexOf('.')); - } -} diff --git a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/ComparatorUtil.java b/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/ComparatorUtil.java deleted file mode 100644 index 05e85c3e7..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/ComparatorUtil.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright 2009 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.ctk; - -import java.util.Comparator; - -import org.scribble.protocol.ctk.comparators.*; -import org.scribble.protocol.model.*; - -public class ComparatorUtil { - - private static java.util.Map,Comparator> m_comparators= - new java.util.HashMap,Comparator>(); - - static { - m_comparators.put(ProtocolModel.class, new ModelComparator()); - m_comparators.put(TypeImportList.class, new TypeImportListComparator()); - m_comparators.put(TypeImport.class, new TypeImportComparator()); - m_comparators.put(ProtocolImportList.class, new ProtocolImportListComparator()); - m_comparators.put(ProtocolImport.class, new ProtocolImportComparator()); - m_comparators.put(Protocol.class, new ProtocolComparator()); - m_comparators.put(Block.class, new BlockComparator()); - m_comparators.put(Introduces.class, new IntroducesComparator()); - m_comparators.put(Role.class, new RoleComparator()); - m_comparators.put(Interaction.class, new InteractionComparator()); - m_comparators.put(MessageSignature.class, new MessageSignatureComparator()); - m_comparators.put(TypeReference.class, new TypeReferenceComparator()); - m_comparators.put(ProtocolReference.class, new ProtocolReferenceComparator()); - m_comparators.put(Do.class, new DoComparator()); - m_comparators.put(Interrupt.class, new InterruptComparator()); - m_comparators.put(Choice.class, new ChoiceComparator()); - m_comparators.put(OnMessage.class, new OnMessageComparator()); - m_comparators.put(DirectedChoice.class, new DirectedChoiceComparator()); - m_comparators.put(Parallel.class, new ParallelComparator()); - m_comparators.put(Repeat.class, new RepeatComparator()); - m_comparators.put(RecBlock.class, new RecBlockComparator()); - m_comparators.put(Recursion.class, new RecursionComparator()); - m_comparators.put(Run.class, new RunComparator()); - m_comparators.put(Inline.class, new UseComparator()); - m_comparators.put(Parameter.class, new ParameterComparator()); - m_comparators.put(DataType.class, new DataTypeComparator()); - m_comparators.put(ParameterDefinition.class, new ParameterDefinitionComparator()); - m_comparators.put(Unordered.class, new UnorderedComparator()); - m_comparators.put(End.class, new EndComparator()); - } - - public static Comparator getComparator(Class cls) { - return (m_comparators.get(cls)); - } -} diff --git a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/ProtocolExportTest.java b/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/ProtocolExportTest.java deleted file mode 100644 index da0ddceef..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/ProtocolExportTest.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright 2009-11 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.ctk; - -import static org.junit.Assert.*; - -import org.scribble.protocol.model.*; - -public class ProtocolExportTest { - - @org.junit.Test - public void testRunSubProtocol() { - TestJournal logger=new TestJournal(); - - String filename="tests/protocol/global/RunSubProtocol.spr"; - - ProtocolModel model=CTKUtil.getModel(filename, logger); - - assertNotNull(model); - - assertTrue(logger.getErrorCount() == 0); - - String protocol=CTKUtil.getModelText(filename); - - org.scribble.protocol.export.text.TextProtocolExporter exporter= - new org.scribble.protocol.export.text.TextProtocolExporter(); - - java.io.ByteArrayOutputStream os=new java.io.ByteArrayOutputStream(); - - exporter.export(model, logger, os); - - try { - os.close(); - } catch(Exception e) { - fail("Failed to close stream"); - } - - String str=os.toString(); - - str = str.replaceAll("\r\n", "\n"); - - if (!str.equals(protocol)) { - System.out.println("ORIGINAL="+protocol); - System.out.println("GENERATED="+str); - fail("Exported text is not same as original protocol"); - } - } - -} diff --git a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/ProtocolMonitorTest.java b/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/ProtocolMonitorTest.java deleted file mode 100644 index 50dccb930..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/ProtocolMonitorTest.java +++ /dev/null @@ -1,358 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.ctk; - -import static org.junit.Assert.*; - -import org.scribble.command.simulate.Event; -import org.scribble.protocol.export.monitor.MonitorProtocolExporter; -import org.scribble.protocol.model.*; -import org.scribble.protocol.monitor.DefaultSession; -import org.scribble.protocol.monitor.DefaultMonitorContext; -import org.scribble.protocol.monitor.ProtocolMonitor; -import org.scribble.protocol.monitor.Session; -import org.scribble.protocol.monitor.model.Description; - -public class ProtocolMonitorTest { - - protected void testMonitor(String modelFile, String eventFile, boolean shouldFail) { - TestJournal journal=new TestJournal(); - - // Load the model - ProtocolModel model=CTKUtil.getModel(modelFile, journal); - - assertNotNull(model); - assertTrue(journal.getErrorCount() == 0); - - MonitorProtocolExporter exporter=new MonitorProtocolExporter(); - - // Generate the monitoring description from the model - Description desc=exporter.generateDescription(model, journal); - - assertNotNull(desc); - assertTrue(journal.getErrorCount() == 0); - - // Retrieve monitoring events - java.util.List events=CTKUtil.getMonitorEvents(eventFile); - - assertNotNull(events); - - ProtocolMonitor monitor=CTKUtil.getMonitor(); - - DefaultMonitorContext context=new DefaultMonitorContext(); - - Session conv=monitor.createSession(context, desc, DefaultSession.class); - - boolean failed=false; - - for (Event event : events) { - if (event.validate(monitor, context, desc, conv).isValid() == false) { - failed = true; - - if (!shouldFail) { - fail("Failed to monitor '"+event+"'"); - } - } - } - - if (shouldFail && !failed) { - fail("Monitor test was expected to fail but didn't"); - } - } - - @org.junit.Test - public void testMultiPartyInteractionsAndChoice_1AtBuyer() { - testMonitor("tests/protocol/local/MultiPartyInteractionsAndChoice@Buyer.spr", - "tests/monitor/MultiPartyInteractionsAndChoice-1@Buyer.events", false); - } - - @org.junit.Test - public void testMultiPartyInteractionsAndChoice_2AtBuyer() { - testMonitor("tests/protocol/local/MultiPartyInteractionsAndChoice@Buyer.spr", - "tests/monitor/MultiPartyInteractionsAndChoice-2@Buyer.events", false); - } - - @org.junit.Test - public void testMultiPartyInteractionsAndChoice_3AtBuyer() { - // FAIL - // Incorrect message type - testMonitor("tests/protocol/local/MultiPartyInteractionsAndChoice@Buyer.spr", - "tests/monitor/MultiPartyInteractionsAndChoice-3@Buyer.events", true); - } - - @org.junit.Test - public void testMultiPartyInteractionsAndChoice_4AtBuyer() { - // Don't explicitly define the choice decision, so use lookahead to determine the - // choice - - testMonitor("tests/protocol/local/MultiPartyInteractionsAndChoice@Buyer.spr", - "tests/monitor/MultiPartyInteractionsAndChoice-4@Buyer.events", false); - } - - @org.junit.Test - public void testMultiPartyInteractionsAndChoice2_1AtBuyer() { - // Test nested choice, where one choice path has just a operator, events - // explicitly define both choice decisions - testMonitor("tests/protocol/local/MultiPartyInteractionsAndChoice2@Buyer.spr", - "tests/monitor/MultiPartyInteractionsAndChoice2-1@Buyer.events", false); - } - - @org.junit.Test - public void testMultiPartyInteractionsAndChoice2_2AtBuyer() { - // Test nested choice, with only outer choice having explicit decision - testMonitor("tests/protocol/local/MultiPartyInteractionsAndChoice2@Buyer.spr", - "tests/monitor/MultiPartyInteractionsAndChoice2-2@Buyer.events", false); - } - - @org.junit.Test - public void testMultiPartyInteractionsAndChoice2_3AtBuyer() { - // FAIL - // Test nested choice, with only inner choice having explicit decision - // which will fail as the decision will be matched against the outer choice - testMonitor("tests/protocol/local/MultiPartyInteractionsAndChoice2@Buyer.spr", - "tests/monitor/MultiPartyInteractionsAndChoice2-3@Buyer.events", true); - } - - @org.junit.Test - public void testMultiPartyInteractionsAndChoice2_4AtBuyer() { - // Test nested choice, with no explicit choice decisions - testMonitor("tests/protocol/local/MultiPartyInteractionsAndChoice2@Buyer.spr", - "tests/monitor/MultiPartyInteractionsAndChoice2-4@Buyer.events", false); - } - - @org.junit.Test - public void testMultiPartyInteractionsAndChoice2_5AtBuyer() { - // Test invalid product path, with explicit decision - testMonitor("tests/protocol/local/MultiPartyInteractionsAndChoice2@Buyer.spr", - "tests/monitor/MultiPartyInteractionsAndChoice2-5@Buyer.events", false); - } - - @org.junit.Test - public void testMultiPartyInteractionsAndChoice2_1AtBroker() { - // Test Order to Confirmation using only lookahead, so no explicit choice decisions - testMonitor("tests/protocol/local/MultiPartyInteractionsAndChoice2@Broker.spr", - "tests/monitor/MultiPartyInteractionsAndChoice2-1@Broker.events", false); - } - - @org.junit.Test - public void testMultiPartyInteractionsAndChoice2_2AtBroker() { - // Test Order with InvalidProduct returned, and no explicit choice decisions - testMonitor("tests/protocol/local/MultiPartyInteractionsAndChoice2@Broker.spr", - "tests/monitor/MultiPartyInteractionsAndChoice2-2@Broker.events", false); - } - - @org.junit.Test - public void testMultiPartyInteractionsAndChoice2_3AtBroker() { - // Test Order to Confirmation using explicit choice decisions - testMonitor("tests/protocol/local/MultiPartyInteractionsAndChoice2@Broker.spr", - "tests/monitor/MultiPartyInteractionsAndChoice2-3@Broker.events", false); - } - - @org.junit.Test - public void testParallel_1AtBuyer() { - testMonitor("tests/protocol/local/Parallel@Buyer.spr", - "tests/monitor/Parallel-1@Buyer.events", false); - } - - @org.junit.Test - public void testParallel_2AtBuyer() { - testMonitor("tests/protocol/local/Parallel@Buyer.spr", - "tests/monitor/Parallel-2@Buyer.events", false); - } - - @org.junit.Test - public void testParallel_1AtSeller() { - testMonitor("tests/protocol/local/Parallel@Seller.spr", - "tests/monitor/Parallel-1@Seller.events", false); - } - - @org.junit.Test - public void testParallel_2AtSeller() { - testMonitor("tests/protocol/local/Parallel@Seller.spr", - "tests/monitor/Parallel-2@Seller.events", false); - } - - @org.junit.Test - public void testUnordered_1AtBuyer() { - testMonitor("tests/protocol/local/Unordered@Buyer.spr", - "tests/monitor/Unordered-1@Buyer.events", false); - } - - @org.junit.Test - public void testUnordered_2AtBuyer() { - testMonitor("tests/protocol/local/Unordered@Buyer.spr", - "tests/monitor/Unordered-2@Buyer.events", false); - } - - @org.junit.Test - public void testUnordered_1AtSeller() { - testMonitor("tests/protocol/local/Unordered@Seller.spr", - "tests/monitor/Unordered-1@Seller.events", false); - } - - @org.junit.Test - public void testUnordered_2AtSeller() { - testMonitor("tests/protocol/local/Unordered@Seller.spr", - "tests/monitor/Unordered-2@Seller.events", false); - } - - @org.junit.Test - public void testRepeat_1AtBuyer() { - testMonitor("tests/protocol/local/Repeat@Buyer.spr", - "tests/monitor/Repeat-1@Buyer.events", false); - } - - @org.junit.Test - public void testRepeat_2AtBuyer() { - testMonitor("tests/protocol/local/Repeat@Buyer.spr", - "tests/monitor/Repeat-2@Buyer.events", false); - } - - @org.junit.Test - public void testRepeat_1AtSeller() { - testMonitor("tests/protocol/local/Repeat@Seller.spr", - "tests/monitor/Repeat-1@Seller.events", false); - } - - @org.junit.Test - public void testRepeat_2AtSeller() { - testMonitor("tests/protocol/local/Repeat@Seller.spr", - "tests/monitor/Repeat-2@Seller.events", false); - } - - @org.junit.Test - public void testRecur_1AtBuyer() { - testMonitor("tests/protocol/local/Recur@Buyer.spr", - "tests/monitor/Recur-1@Buyer.events", false); - } - - @org.junit.Test - public void testRecur_1AtSeller() { - testMonitor("tests/protocol/local/Recur@Seller.spr", - "tests/monitor/Recur-1@Seller.events", false); - } - - @org.junit.Test - public void testRecur_2AtBuyer() { - testMonitor("tests/protocol/local/Recur@Buyer.spr", - "tests/monitor/Recur-2@Buyer.events", false); - } - - @org.junit.Test - public void testRecur_2AtSeller() { - testMonitor("tests/protocol/local/Recur@Seller.spr", - "tests/monitor/Recur-2@Seller.events", false); - } - - @org.junit.Test - @org.junit.Ignore - public void testRecur2_1AtBuyer() { - testMonitor("tests/protocol/local/Recur2@Buyer.spr", - "tests/monitor/Recur2-1@Buyer.events", false); - } - - @org.junit.Test - @org.junit.Ignore - public void testRecur2_1AtSeller() { - testMonitor("tests/protocol/local/Recur2@Seller.spr", - "tests/monitor/Recur2-1@Seller.events", false); - } - - @org.junit.Test - public void testRecur3_1AtBuyer() { - testMonitor("tests/protocol/local/Recur3@Buyer.spr", - "tests/monitor/Recur3-1@Buyer.events", false); - } - - @org.junit.Test - public void testRecur3_1AtSeller() { - testMonitor("tests/protocol/local/Recur3@Seller.spr", - "tests/monitor/Recur3-1@Seller.events", false); - } - - @org.junit.Test - public void testRunSubProtocolAtBuyer() { - testMonitor("tests/protocol/local/RunSubProtocol@Buyer.spr", - "tests/monitor/RunSubProtocol@Buyer.events", false); - } - - @org.junit.Test - public void testRunSubProtocolAtSeller() { - testMonitor("tests/protocol/local/RunSubProtocol@Seller.spr", - "tests/monitor/RunSubProtocol@Seller.events", false); - } - - @org.junit.Test - public void testDoInterrupt_1AtBuyer() { - testMonitor("tests/protocol/local/DoInterrupt@Buyer.spr", - "tests/monitor/DoInterrupt-1@Buyer.events", false); - } - - @org.junit.Test - public void testDoInterrupt_1AtSeller() { - testMonitor("tests/protocol/local/DoInterrupt@Seller.spr", - "tests/monitor/DoInterrupt-1@Seller.events", false); - } - - @org.junit.Test - public void testDoInterrupt_2AtBuyer() { - testMonitor("tests/protocol/local/DoInterrupt@Buyer.spr", - "tests/monitor/DoInterrupt-2@Buyer.events", false); - } - - @org.junit.Test - public void testDoInterrupt_2AtSeller() { - testMonitor("tests/protocol/local/DoInterrupt@Seller.spr", - "tests/monitor/DoInterrupt-2@Seller.events", false); - } - - @org.junit.Test - public void testSingleInteractionXSDImportAtBuyer() { - testMonitor("tests/protocol/local/SingleInteractionXSDImport@Buyer.spr", - "tests/monitor/SingleInteractionXSDImport@Buyer.events", false); - } - - @org.junit.Test - public void testSingleInteractionXSDImportAtSeller() { - testMonitor("tests/protocol/local/SingleInteractionXSDImport@Seller.spr", - "tests/monitor/SingleInteractionXSDImport@Seller.events", false); - } - - @org.junit.Test - public void testDirectedChoice_1AtBuyer() { - testMonitor("tests/protocol/local/DirectedChoice@Buyer.spr", - "tests/monitor/DirectedChoice-1@Buyer.events", false); - } - - @org.junit.Test - public void testDirectedChoice_1AtSeller() { - testMonitor("tests/protocol/local/DirectedChoice@Seller.spr", - "tests/monitor/DirectedChoice-1@Seller.events", false); - } - - @org.junit.Test - public void testDirectedChoice_2AtBuyer() { - testMonitor("tests/protocol/local/DirectedChoice@Buyer.spr", - "tests/monitor/DirectedChoice-2@Buyer.events", false); - } - - @org.junit.Test - public void testDirectedChoice_2AtSeller() { - testMonitor("tests/protocol/local/DirectedChoice@Seller.spr", - "tests/monitor/DirectedChoice-2@Seller.events", false); - } -} diff --git a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/ProtocolParserTest.java b/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/ProtocolParserTest.java deleted file mode 100644 index 9895dac95..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/ProtocolParserTest.java +++ /dev/null @@ -1,1526 +0,0 @@ -/* - * Copyright 2009 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.ctk; - -import static org.junit.Assert.*; - -import org.scribble.common.model.DefaultAnnotation; -import org.scribble.protocol.model.*; - -public class ProtocolParserTest { - - @org.junit.Test - public void testAnnotation() { - TestJournal logger=new TestJournal(); - - ProtocolModel model=CTKUtil.getModel("tests/protocol/global/Annotation.spr", logger); - - assertNotNull(model); - - assertTrue(logger.getErrorCount() == 0); - - // Build expected model - ProtocolModel expected=new ProtocolModel(); - - TypeImportList imp=new TypeImportList(); - imp.getAnnotations().add(new DefaultAnnotation(" Annotation before import ")); - - TypeImport t=new TypeImport(); - t.setName("Order"); - imp.getTypeImports().add(t); - expected.getImports().add(imp); - - Protocol protocol=new Protocol(); - expected.setProtocol(protocol); - - ParameterDefinition p=new ParameterDefinition(); - p.setName("Buyer"); - protocol.getParameterDefinitions().add(p); - - protocol.setName("SingleInteraction"); - protocol.getAnnotations().add(new DefaultAnnotation(" Annotation before top protocol ")); - - Introduces rl=new Introduces(); - rl.getAnnotations().add(new DefaultAnnotation(" Annotation before role list ")); - - Role buyer=new Role(); - buyer.setName("Buyer"); - rl.setIntroducer(buyer); - - Role seller=new Role(); - seller.setName("Seller"); - rl.getIntroducedRoles().add(seller); - - protocol.getBlock().add(rl); - - Interaction interaction=new Interaction(); - interaction.getAnnotations().add(new DefaultAnnotation(" Annotation before interaction ")); - - MessageSignature ms=new MessageSignature(); - TypeReference tref=new TypeReference(); - tref.setName("Order"); - ms.getTypeReferences().add(tref); - interaction.setMessageSignature(ms); - interaction.setFromRole(buyer); - interaction.getToRoles().add(seller); - - protocol.getBlock().add(interaction); - - CTKUtil.verify(model, expected); - } - - @org.junit.Test - public void testBlockComment() { - TestJournal logger=new TestJournal(); - - ProtocolModel model=CTKUtil.getModel("tests/protocol/global/BlockComment.spr", logger); - - assertNotNull(model); - - assertTrue(logger.getErrorCount() == 0); - - // Build expected model - ProtocolModel expected=new ProtocolModel(); - - TypeImportList imp=new TypeImportList(); - TypeImport t=new TypeImport(); - t.setName("Order"); - imp.getTypeImports().add(t); - expected.getImports().add(imp); - - Protocol protocol=new Protocol(); - expected.setProtocol(protocol); - - protocol.setName("SingleInteraction"); - - ParameterDefinition p=new ParameterDefinition(); - p.setName("Buyer"); - protocol.getParameterDefinitions().add(p); - - Introduces rl=new Introduces(); - Role buyer=new Role(); - buyer.setName("Buyer"); - rl.setIntroducer(buyer); - Role seller=new Role(); - seller.setName("Seller"); - rl.getIntroducedRoles().add(seller); - - protocol.getBlock().add(rl); - - Interaction interaction=new Interaction(); - - MessageSignature ms=new MessageSignature(); - TypeReference tref=new TypeReference(); - tref.setName("Order"); - ms.getTypeReferences().add(tref); - interaction.setMessageSignature(ms); - interaction.setFromRole(buyer); - interaction.getToRoles().add(seller); - - protocol.getBlock().add(interaction); - - CTKUtil.verify(model, expected); - } - - @org.junit.Test - public void testLineComment() { - TestJournal logger=new TestJournal(); - - ProtocolModel model=CTKUtil.getModel("tests/protocol/global/LineComment.spr", logger); - - assertNotNull(model); - - assertTrue(logger.getErrorCount() == 0); - - // Build expected model - ProtocolModel expected=new ProtocolModel(); - - TypeImportList imp=new TypeImportList(); - TypeImport t=new TypeImport(); - t.setName("Order"); - imp.getTypeImports().add(t); - expected.getImports().add(imp); - - Protocol protocol=new Protocol(); - expected.setProtocol(protocol); - - protocol.setName("SingleInteraction"); - - ParameterDefinition p=new ParameterDefinition(); - p.setName("Buyer"); - protocol.getParameterDefinitions().add(p); - - Introduces rl=new Introduces(); - Role buyer=new Role(); - buyer.setName("Buyer"); - rl.setIntroducer(buyer); - Role seller=new Role(); - seller.setName("Seller"); - rl.getIntroducedRoles().add(seller); - - protocol.getBlock().add(rl); - - Interaction interaction=new Interaction(); - - MessageSignature ms=new MessageSignature(); - TypeReference tref=new TypeReference(); - tref.setName("Order"); - ms.getTypeReferences().add(tref); - interaction.setMessageSignature(ms); - interaction.setFromRole(buyer); - interaction.getToRoles().add(seller); - - protocol.getBlock().add(interaction); - - CTKUtil.verify(model, expected); - } - - @org.junit.Test - public void testSingleInteraction() { - TestJournal logger=new TestJournal(); - - ProtocolModel model=CTKUtil.getModel("tests/protocol/global/SingleInteraction.spr", logger); - - assertNotNull(model); - - assertTrue(logger.getErrorCount() == 0); - - // Build expected model - ProtocolModel expected=new ProtocolModel(); - - TypeImportList imp=new TypeImportList(); - TypeImport t=new TypeImport(); - t.setName("Order"); - imp.getTypeImports().add(t); - expected.getImports().add(imp); - - Protocol protocol=new Protocol(); - expected.setProtocol(protocol); - - protocol.setName("SingleInteraction"); - - ParameterDefinition p=new ParameterDefinition(); - p.setName("Buyer"); - protocol.getParameterDefinitions().add(p); - - Introduces rl=new Introduces(); - Role buyer=new Role(); - buyer.setName("Buyer"); - rl.setIntroducer(buyer); - Role seller=new Role(); - seller.setName("Seller"); - rl.getIntroducedRoles().add(seller); - - protocol.getBlock().add(rl); - - Interaction interaction=new Interaction(); - - MessageSignature ms=new MessageSignature(); - TypeReference tref=new TypeReference(); - tref.setName("Order"); - ms.getTypeReferences().add(tref); - interaction.setMessageSignature(ms); - interaction.setFromRole(buyer); - interaction.getToRoles().add(seller); - - protocol.getBlock().add(interaction); - - CTKUtil.verify(model, expected); - } - - @org.junit.Test - public void testSingleInteractionWithXSDImport() { - TestJournal logger=new TestJournal(); - - ProtocolModel model=CTKUtil.getModel("tests/protocol/global/SingleInteractionXSDImport.spr", logger); - - assertNotNull(model); - - assertTrue(logger.getErrorCount() == 0); - - // Build expected model - ProtocolModel expected=new ProtocolModel(); - - TypeImportList imp1=new TypeImportList(); - imp1.setFormat("xml"); - imp1.setLocation("../schema/MySchema.xsd"); - - TypeImport t1=new TypeImport(); - t1.setName("Order"); - DataType dt1=new DataType(); - dt1.setDetails("{http://www.acme.org/Purchasing}Order"); - t1.setDataType(dt1); - imp1.getTypeImports().add(t1); - - TypeImport t2=new TypeImport(); - t2.setName("Quote"); - DataType dt2=new DataType(); - dt2.setDetails("{http://www.acme.org/Purchasing}Quote"); - t2.setDataType(dt2); - imp1.getTypeImports().add(t2); - - expected.getImports().add(imp1); - - TypeImportList imp2=new TypeImportList(); - imp2.setFormat("java"); - imp2.setLocation("org.scribble"); - - TypeImport t3=new TypeImport(); - t3.setName("Order"); - DataType dt3=new DataType(); - dt3.setDetails("Order"); - t3.setDataType(dt3); - imp2.getTypeImports().add(t3); - - TypeImport t4=new TypeImport(); - t4.setName("Quote"); - DataType dt4=new DataType(); - dt4.setDetails("Quote"); - t4.setDataType(dt4); - imp2.getTypeImports().add(t4); - - expected.getImports().add(imp2); - - Protocol protocol=new Protocol(); - expected.setProtocol(protocol); - - protocol.setName("SingleInteraction"); - - ParameterDefinition p=new ParameterDefinition(); - p.setName("Buyer"); - protocol.getParameterDefinitions().add(p); - - Introduces rl=new Introduces(); - Role buyer=new Role(); - buyer.setName("Buyer"); - rl.setIntroducer(buyer); - Role seller=new Role(); - seller.setName("Seller"); - rl.getIntroducedRoles().add(seller); - - protocol.getBlock().add(rl); - - Interaction interaction=new Interaction(); - - MessageSignature ms=new MessageSignature(); - TypeReference tref=new TypeReference(); - tref.setName("Order"); - ms.getTypeReferences().add(tref); - interaction.setMessageSignature(ms); - interaction.setFromRole(buyer); - interaction.getToRoles().add(seller); - - protocol.getBlock().add(interaction); - - CTKUtil.verify(model, expected); - } - - @org.junit.Test - public void testSingleInteractionRPC() { - TestJournal logger=new TestJournal(); - - ProtocolModel model=CTKUtil.getModel("tests/protocol/global/SingleInteractionRPC.spr", logger); - - assertNotNull(model); - - assertTrue(logger.getErrorCount() == 0); - - // Build expected model - ProtocolModel expected=new ProtocolModel(); - - TypeImportList imp=new TypeImportList(); - TypeImport t=new TypeImport(); - t.setName("Order"); - imp.getTypeImports().add(t); - expected.getImports().add(imp); - - imp=new TypeImportList(); - t=new TypeImport(); - t.setName("Customer"); - imp.getTypeImports().add(t); - expected.getImports().add(imp); - - Protocol protocol=new Protocol(); - expected.setProtocol(protocol); - - protocol.setName("SingleInteractionRPC"); - - ParameterDefinition p=new ParameterDefinition(); - p.setName("Buyer"); - protocol.getParameterDefinitions().add(p); - - Introduces rl=new Introduces(); - Role buyer=new Role(); - buyer.setName("Buyer"); - rl.setIntroducer(buyer); - Role seller=new Role(); - seller.setName("Seller"); - rl.getIntroducedRoles().add(seller); - - protocol.getBlock().add(rl); - - Interaction interaction=new Interaction(); - - MessageSignature ms=new MessageSignature(); - - ms.setOperation("submit"); - - TypeReference tref1=new TypeReference(); - tref1.setName("Order"); - ms.getTypeReferences().add(tref1); - - TypeReference tref2=new TypeReference(); - tref2.setName("Customer"); - ms.getTypeReferences().add(tref2); - - interaction.setMessageSignature(ms); - interaction.setFromRole(buyer); - interaction.getToRoles().add(seller); - - protocol.getBlock().add(interaction); - - CTKUtil.verify(model, expected); - } - - @org.junit.Test - public void testMulticastInteraction() { - TestJournal logger=new TestJournal(); - - ProtocolModel model=CTKUtil.getModel("tests/protocol/global/MulticastInteraction.spr", logger); - - assertNotNull(model); - - assertTrue(logger.getErrorCount() == 0); - - // Build expected model - ProtocolModel expected=new ProtocolModel(); - - TypeImportList imp=new TypeImportList(); - TypeImport t=new TypeImport(); - t.setName("Order"); - imp.getTypeImports().add(t); - expected.getImports().add(imp); - - Protocol protocol=new Protocol(); - expected.setProtocol(protocol); - - protocol.setName("MulticastInteraction"); - - ParameterDefinition p=new ParameterDefinition(); - p.setName("Buyer"); - protocol.getParameterDefinitions().add(p); - - Introduces rl=new Introduces(); - Role buyer=new Role(); - buyer.setName("Buyer"); - rl.setIntroducer(buyer); - - Role sellerA=new Role(); - sellerA.setName("SellerA"); - rl.getIntroducedRoles().add(sellerA); - - Role sellerB=new Role(); - sellerB.setName("SellerB"); - rl.getIntroducedRoles().add(sellerB); - - protocol.getBlock().add(rl); - - Interaction interaction=new Interaction(); - - MessageSignature ms=new MessageSignature(); - TypeReference tref=new TypeReference(); - tref.setName("Order"); - ms.getTypeReferences().add(tref); - interaction.setMessageSignature(ms); - interaction.setFromRole(buyer); - interaction.getToRoles().add(sellerA); - interaction.getToRoles().add(sellerB); - - protocol.getBlock().add(interaction); - - CTKUtil.verify(model, expected); - } - - @org.junit.Test - public void testDoInterrupt() { - TestJournal logger=new TestJournal(); - - ProtocolModel model=CTKUtil.getModel("tests/protocol/global/DoInterrupt.spr", logger); - - assertNotNull(model); - - assertTrue(logger.getErrorCount() == 0); - - // Build expected model - ProtocolModel expected=new ProtocolModel(); - - TypeImportList imp=new TypeImportList(); - TypeImport t=new TypeImport(); - t.setName("Order"); - imp.getTypeImports().add(t); - expected.getImports().add(imp); - - imp=new TypeImportList(); - t=new TypeImport(); - t.setName("OutOfStock"); - imp.getTypeImports().add(t); - expected.getImports().add(imp); - - imp=new TypeImportList(); - t=new TypeImport(); - t.setName("OrderExpired"); - imp.getTypeImports().add(t); - t=new TypeImport(); - t.setName("OrderCancelled"); - imp.getTypeImports().add(t); - expected.getImports().add(imp); - - imp=new TypeImportList(); - t=new TypeImport(); - t.setName("Confirm"); - imp.getTypeImports().add(t); - expected.getImports().add(imp); - - imp=new TypeImportList(); - t=new TypeImport(); - t.setName("Ack"); - imp.getTypeImports().add(t); - expected.getImports().add(imp); - - imp=new TypeImportList(); - t=new TypeImport(); - t.setName("Finish"); - imp.getTypeImports().add(t); - expected.getImports().add(imp); - - Protocol protocol=new Protocol(); - expected.setProtocol(protocol); - - protocol.setName("DoInterrupt"); - - ParameterDefinition p=new ParameterDefinition(); - p.setName("Buyer"); - protocol.getParameterDefinitions().add(p); - - Introduces rl=new Introduces(); - Role buyer=new Role(); - buyer.setName("Buyer"); - rl.setIntroducer(buyer); - Role seller=new Role(); - seller.setName("Seller"); - rl.getIntroducedRoles().add(seller); - - protocol.getBlock().add(rl); - - Do tryEscape=new Do(); - - Block b=new Block(); - - Interaction interaction=new Interaction(); - - MessageSignature ms=new MessageSignature(); - TypeReference tref=new TypeReference(); - tref.setName("Order"); - ms.getTypeReferences().add(tref); - interaction.setMessageSignature(ms); - interaction.setFromRole(buyer); - interaction.getToRoles().add(seller); - - b.add(interaction); - - interaction = new Interaction(); - - ms = new MessageSignature(); - tref = new TypeReference(); - tref.setName("Confirm"); - ms.getTypeReferences().add(tref); - interaction.setMessageSignature(ms); - interaction.setFromRole(seller); - interaction.getToRoles().add(buyer); - - b.add(interaction); - - tryEscape.setBlock(b); - - Interrupt catchBlock=new Interrupt(); - - interaction=new Interaction(); - - ms=new MessageSignature(); - tref=new TypeReference(); - tref.setName("OutOfStock"); - ms.getTypeReferences().add(tref); - interaction.setMessageSignature(ms); - interaction.setFromRole(seller); - interaction.getToRoles().add(buyer); - - catchBlock.getBlock().add(interaction); - - tryEscape.getInterrupts().add(catchBlock); - - catchBlock = new Interrupt(); - - interaction=new Interaction(); - - ms=new MessageSignature(); - ms.setOperation("expire"); - tref=new TypeReference(); - tref.setName("OrderExpired"); - ms.getTypeReferences().add(tref); - interaction.setMessageSignature(ms); - interaction.setFromRole(buyer); - interaction.getToRoles().add(seller); - - catchBlock.getBlock().add(interaction); - - interaction=new Interaction(); - - ms=new MessageSignature(); - tref=new TypeReference(); - tref.setName("OrderCancelled"); - ms.getTypeReferences().add(tref); - interaction.setMessageSignature(ms); - interaction.setFromRole(buyer); - interaction.getToRoles().add(seller); - - catchBlock.getBlock().add(interaction); - - interaction = new Interaction(); - - ms = new MessageSignature(); - tref = new TypeReference(); - tref.setName("Ack"); - ms.getTypeReferences().add(tref); - interaction.setMessageSignature(ms); - interaction.setFromRole(seller); - interaction.getToRoles().add(buyer); - - catchBlock.getBlock().add(interaction); - - tryEscape.getInterrupts().add(catchBlock); - - protocol.getBlock().add(tryEscape); - - interaction = new Interaction(); - - ms = new MessageSignature(); - tref = new TypeReference(); - tref.setName("Finish"); - ms.getTypeReferences().add(tref); - interaction.setMessageSignature(ms); - interaction.setFromRole(buyer); - interaction.getToRoles().add(seller); - - protocol.getBlock().add(interaction); - - CTKUtil.verify(model, expected); - } - - @org.junit.Test - public void testEnd() { - TestJournal logger=new TestJournal(); - - ProtocolModel model=CTKUtil.getModel("tests/protocol/global/End.spr", logger); - - assertNotNull(model); - - assertTrue(logger.getErrorCount() == 0); - - // Build expected model - ProtocolModel expected=new ProtocolModel(); - - TypeImportList imp=new TypeImportList(); - TypeImport t=new TypeImport(); - t.setName("Order"); - imp.getTypeImports().add(t); - expected.getImports().add(imp); - - imp=new TypeImportList(); - t=new TypeImport(); - t.setName("Cancel"); - imp.getTypeImports().add(t); - expected.getImports().add(imp); - - imp=new TypeImportList(); - t=new TypeImport(); - t.setName("Invoice"); - imp.getTypeImports().add(t); - expected.getImports().add(imp); - - Protocol protocol=new Protocol(); - expected.setProtocol(protocol); - - protocol.setName("EndExample"); - - ParameterDefinition p=new ParameterDefinition(); - p.setName("Buyer"); - protocol.getParameterDefinitions().add(p); - - Introduces rl=new Introduces(); - Role buyer=new Role(); - buyer.setName("Buyer"); - rl.setIntroducer(buyer); - Role seller=new Role(); - seller.setName("Seller"); - rl.getIntroducedRoles().add(seller); - - protocol.getBlock().add(rl); - - Choice choice=new Choice(); - - choice.setRole(buyer); - - Block b1=new Block(); - choice.getPaths().add(b1); - - Interaction ib1=new Interaction(); - - MessageSignature ms=new MessageSignature(); - TypeReference tref=new TypeReference(); - tref.setName("Order"); - ms.getTypeReferences().add(tref); - ib1.setMessageSignature(ms); - - ib1.setFromRole(buyer); - ib1.getToRoles().add(seller); - b1.add(ib1); - - Block b2=new Block(); - choice.getPaths().add(b2); - - Interaction ib2=new Interaction(); - - ms=new MessageSignature(); - tref=new TypeReference(); - tref.setName("Cancel"); - ms.getTypeReferences().add(tref); - ib2.setMessageSignature(ms); - - ib2.setFromRole(buyer); - ib2.getToRoles().add(seller); - b2.add(ib2); - - b2.add(new End()); - - protocol.getBlock().add(choice); - - Interaction i1=new Interaction(); - i1.setFromRole(seller); - i1.getToRoles().add(buyer); - - MessageSignature ms2=new MessageSignature(); - TypeReference tref2=new TypeReference(); - tref2.setName("Invoice"); - ms2.getTypeReferences().add(tref2); - i1.setMessageSignature(ms2); - - protocol.getBlock().add(i1); - - CTKUtil.verify(model, expected); - } - - @org.junit.Test - public void testChoice() { - TestJournal logger=new TestJournal(); - - ProtocolModel model=CTKUtil.getModel("tests/protocol/global/Choice.spr", logger); - - assertNotNull(model); - - assertTrue(logger.getErrorCount() == 0); - - // Build expected model - ProtocolModel expected=new ProtocolModel(); - - TypeImportList imp=new TypeImportList(); - TypeImport t=new TypeImport(); - t.setName("Order"); - imp.getTypeImports().add(t); - expected.getImports().add(imp); - - imp=new TypeImportList(); - t=new TypeImport(); - t.setName("Cancel"); - imp.getTypeImports().add(t); - expected.getImports().add(imp); - - imp=new TypeImportList(); - t=new TypeImport(); - t.setName("Invoice"); - imp.getTypeImports().add(t); - expected.getImports().add(imp); - - Protocol protocol=new Protocol(); - expected.setProtocol(protocol); - - protocol.setName("SingleInteraction"); - - ParameterDefinition p=new ParameterDefinition(); - p.setName("Buyer"); - protocol.getParameterDefinitions().add(p); - - Introduces rl=new Introduces(); - Role buyer=new Role(); - buyer.setName("Buyer"); - rl.setIntroducer(buyer); - Role seller=new Role(); - seller.setName("Seller"); - rl.getIntroducedRoles().add(seller); - - protocol.getBlock().add(rl); - - Choice choice=new Choice(); - - choice.setRole(buyer); - - Block b1=new Block(); - choice.getPaths().add(b1); - - Interaction ib1=new Interaction(); - - MessageSignature ms=new MessageSignature(); - TypeReference tref=new TypeReference(); - tref.setName("Order"); - ms.getTypeReferences().add(tref); - ib1.setMessageSignature(ms); - - ib1.setFromRole(buyer); - ib1.getToRoles().add(seller); - b1.add(ib1); - - Interaction i1=new Interaction(); - i1.setFromRole(seller); - i1.getToRoles().add(buyer); - - MessageSignature ms2=new MessageSignature(); - TypeReference tref2=new TypeReference(); - tref2.setName("Invoice"); - ms2.getTypeReferences().add(tref2); - i1.setMessageSignature(ms2); - - b1.add(i1); - - Block b2=new Block(); - choice.getPaths().add(b2); - - Interaction ib2=new Interaction(); - - ms=new MessageSignature(); - tref=new TypeReference(); - tref.setName("Cancel"); - ms.getTypeReferences().add(tref); - ib2.setMessageSignature(ms); - - ib2.setFromRole(buyer); - ib2.getToRoles().add(seller); - b2.add(ib2); - - protocol.getBlock().add(choice); - - CTKUtil.verify(model, expected); - } - - @org.junit.Test - public void testDirectedChoice() { - TestJournal logger=new TestJournal(); - - ProtocolModel model=CTKUtil.getModel("tests/protocol/global/DirectedChoice.spr", logger); - - assertNotNull(model); - - assertTrue(logger.getErrorCount() == 0); - - // Build expected model - ProtocolModel expected=new ProtocolModel(); - - TypeImportList imp=new TypeImportList(); - TypeImport t=new TypeImport(); - t.setName("Order"); - imp.getTypeImports().add(t); - expected.getImports().add(imp); - - imp=new TypeImportList(); - t=new TypeImport(); - t.setName("Cancel"); - imp.getTypeImports().add(t); - expected.getImports().add(imp); - - imp=new TypeImportList(); - t=new TypeImport(); - t.setName("Invoice"); - imp.getTypeImports().add(t); - expected.getImports().add(imp); - - Protocol protocol=new Protocol(); - expected.setProtocol(protocol); - - protocol.setName("SingleInteraction"); - - ParameterDefinition p=new ParameterDefinition(); - p.setName("Buyer"); - protocol.getParameterDefinitions().add(p); - - Introduces rl=new Introduces(); - Role buyer=new Role(); - buyer.setName("Buyer"); - rl.setIntroducer(buyer); - Role seller=new Role(); - seller.setName("Seller"); - rl.getIntroducedRoles().add(seller); - - protocol.getBlock().add(rl); - - DirectedChoice choice=new DirectedChoice(); - - choice.setFromRole(buyer); - choice.getToRoles().add(seller); - - OnMessage om1=new OnMessage(); - - choice.getOnMessages().add(om1); - - MessageSignature ms=new MessageSignature(); - TypeReference tref=new TypeReference(); - tref.setName("Order"); - ms.getTypeReferences().add(tref); - - om1.setMessageSignature(ms); - - Interaction i1=new Interaction(); - i1.setFromRole(seller); - i1.getToRoles().add(buyer); - - MessageSignature ms2=new MessageSignature(); - TypeReference tref2=new TypeReference(); - tref2.setName("Invoice"); - ms2.getTypeReferences().add(tref2); - i1.setMessageSignature(ms2); - - om1.getBlock().add(i1); - - OnMessage om2=new OnMessage(); - choice.getOnMessages().add(om2); - - ms=new MessageSignature(); - tref=new TypeReference(); - tref.setName("Cancel"); - ms.getTypeReferences().add(tref); - - om2.setMessageSignature(ms); - - protocol.getBlock().add(choice); - - CTKUtil.verify(model, expected); - } - - @org.junit.Test - public void testParallel() { - TestJournal logger=new TestJournal(); - - ProtocolModel model=CTKUtil.getModel("tests/protocol/global/Parallel.spr", logger); - - assertNotNull(model); - - assertTrue(logger.getErrorCount() == 0); - - // Build expected model - ProtocolModel expected=new ProtocolModel(); - - TypeImportList imp=new TypeImportList(); - TypeImport t=new TypeImport(); - t.setName("M1"); - imp.getTypeImports().add(t); - expected.getImports().add(imp); - - imp=new TypeImportList(); - t=new TypeImport(); - t.setName("M2"); - imp.getTypeImports().add(t); - expected.getImports().add(imp); - - imp=new TypeImportList(); - t=new TypeImport(); - t.setName("M3"); - imp.getTypeImports().add(t); - expected.getImports().add(imp); - - Protocol protocol=new Protocol(); - expected.setProtocol(protocol); - - protocol.setName("Parallel"); - - ParameterDefinition p=new ParameterDefinition(); - p.setName("Buyer"); - protocol.getParameterDefinitions().add(p); - - Introduces rl=new Introduces(); - Role buyer=new Role(); - buyer.setName("Buyer"); - rl.setIntroducer(buyer); - Role seller=new Role(); - seller.setName("Seller"); - rl.getIntroducedRoles().add(seller); - - protocol.getBlock().add(rl); - - Parallel parallel=new Parallel(); - - Block b1=new Block(); - parallel.getPaths().add(b1); - - Interaction interaction=new Interaction(); - - MessageSignature ms=new MessageSignature(); - TypeReference tref=new TypeReference(); - tref.setName("M1"); - ms.getTypeReferences().add(tref); - interaction.setMessageSignature(ms); - interaction.setFromRole(buyer); - interaction.getToRoles().add(seller); - - b1.add(interaction); - - Block b2=new Block(); - parallel.getPaths().add(b2); - - interaction=new Interaction(); - - ms=new MessageSignature(); - tref=new TypeReference(); - tref.setName("M2"); - ms.getTypeReferences().add(tref); - interaction.setMessageSignature(ms); - interaction.setFromRole(buyer); - interaction.getToRoles().add(seller); - - b2.add(interaction); - - protocol.getBlock().add(parallel); - - interaction=new Interaction(); - - ms=new MessageSignature(); - tref=new TypeReference(); - tref.setName("M3"); - ms.getTypeReferences().add(tref); - interaction.setMessageSignature(ms); - interaction.setFromRole(buyer); - interaction.getToRoles().add(seller); - - protocol.getBlock().add(interaction); - - CTKUtil.verify(model, expected); - } - - @org.junit.Test - public void testRepeat() { - TestJournal logger=new TestJournal(); - - ProtocolModel model=CTKUtil.getModel("tests/protocol/global/Repeat.spr", logger); - - assertNotNull(model); - - assertTrue(logger.getErrorCount() == 0); - - // Build expected model - ProtocolModel expected=new ProtocolModel(); - - TypeImportList imp=new TypeImportList(); - TypeImport t=new TypeImport(); - t.setName("Order"); - imp.getTypeImports().add(t); - expected.getImports().add(imp); - - imp=new TypeImportList(); - t=new TypeImport(); - t.setName("Finish"); - imp.getTypeImports().add(t); - expected.getImports().add(imp); - - Protocol protocol=new Protocol(); - expected.setProtocol(protocol); - - protocol.setName("Repeat"); - - ParameterDefinition p=new ParameterDefinition(); - p.setName("Buyer"); - protocol.getParameterDefinitions().add(p); - - Introduces rl=new Introduces(); - Role buyer=new Role(); - buyer.setName("Buyer"); - rl.setIntroducer(buyer); - Role seller=new Role(); - seller.setName("Seller"); - rl.getIntroducedRoles().add(seller); - - protocol.getBlock().add(rl); - - Repeat repeat=new Repeat(); - - repeat.getRoles().add(buyer); - - Interaction interaction=new Interaction(); - - MessageSignature ms=new MessageSignature(); - TypeReference tref=new TypeReference(); - tref.setName("Order"); - ms.getTypeReferences().add(tref); - interaction.setMessageSignature(ms); - interaction.setFromRole(buyer); - interaction.getToRoles().add(seller); - - repeat.getBlock().add(interaction); - - protocol.getBlock().add(repeat); - - interaction=new Interaction(); - - ms=new MessageSignature(); - tref=new TypeReference(); - tref.setName("Finish"); - ms.getTypeReferences().add(tref); - interaction.setMessageSignature(ms); - interaction.setFromRole(buyer); - interaction.getToRoles().add(seller); - - protocol.getBlock().add(interaction); - - CTKUtil.verify(model, expected); - } - - @org.junit.Test - public void testUnordered() { - TestJournal logger=new TestJournal(); - - ProtocolModel model=CTKUtil.getModel("tests/protocol/global/Unordered.spr", logger); - - assertNotNull(model); - - assertTrue(logger.getErrorCount() == 0); - - // Build expected model - ProtocolModel expected=new ProtocolModel(); - - TypeImportList imp=new TypeImportList(); - TypeImport t=new TypeImport(); - t.setName("Order"); - imp.getTypeImports().add(t); - expected.getImports().add(imp); - - imp=new TypeImportList(); - t=new TypeImport(); - t.setName("Cancel"); - imp.getTypeImports().add(t); - expected.getImports().add(imp); - - imp=new TypeImportList(); - t=new TypeImport(); - t.setName("Finish"); - imp.getTypeImports().add(t); - expected.getImports().add(imp); - - Protocol protocol=new Protocol(); - expected.setProtocol(protocol); - - protocol.setName("Unordered"); - - ParameterDefinition p=new ParameterDefinition(); - p.setName("Buyer"); - protocol.getParameterDefinitions().add(p); - - Introduces rl=new Introduces(); - Role buyer=new Role(); - buyer.setName("Buyer"); - rl.setIntroducer(buyer); - Role seller=new Role(); - seller.setName("Seller"); - rl.getIntroducedRoles().add(seller); - - protocol.getBlock().add(rl); - - Unordered unordered=new Unordered(); - - Interaction interaction=new Interaction(); - - MessageSignature ms=new MessageSignature(); - TypeReference tref=new TypeReference(); - tref.setName("Order"); - ms.getTypeReferences().add(tref); - interaction.setMessageSignature(ms); - interaction.setFromRole(buyer); - interaction.getToRoles().add(seller); - - unordered.getBlock().add(interaction); - - interaction=new Interaction(); - - ms=new MessageSignature(); - tref=new TypeReference(); - tref.setName("Cancel"); - ms.getTypeReferences().add(tref); - interaction.setMessageSignature(ms); - interaction.setFromRole(buyer); - interaction.getToRoles().add(seller); - - unordered.getBlock().add(interaction); - - protocol.getBlock().add(unordered); - - interaction=new Interaction(); - - ms=new MessageSignature(); - tref=new TypeReference(); - tref.setName("Finish"); - ms.getTypeReferences().add(tref); - interaction.setMessageSignature(ms); - interaction.setFromRole(buyer); - interaction.getToRoles().add(seller); - - protocol.getBlock().add(interaction); - - CTKUtil.verify(model, expected); - } - - @org.junit.Test - public void testRecur() { - TestJournal logger=new TestJournal(); - - ProtocolModel model=CTKUtil.getModel("tests/protocol/global/Recur.spr", logger); - - assertNotNull(model); - - assertTrue(logger.getErrorCount() == 0); - - // Build expected model - ProtocolModel expected=new ProtocolModel(); - - TypeImportList imp=new TypeImportList(); - TypeImport t=new TypeImport(); - t.setName("Order"); - imp.getTypeImports().add(t); - expected.getImports().add(imp); - - imp=new TypeImportList(); - t=new TypeImport(); - t.setName("Finish"); - imp.getTypeImports().add(t); - expected.getImports().add(imp); - - imp=new TypeImportList(); - t=new TypeImport(); - t.setName("Rejected"); - imp.getTypeImports().add(t); - expected.getImports().add(imp); - - imp=new TypeImportList(); - t=new TypeImport(); - t.setName("Accepted"); - imp.getTypeImports().add(t); - expected.getImports().add(imp); - - imp=new TypeImportList(); - t=new TypeImport(); - t.setName("Another"); - imp.getTypeImports().add(t); - expected.getImports().add(imp); - - Protocol protocol=new Protocol(); - expected.setProtocol(protocol); - - protocol.setName("Recur"); - - ParameterDefinition p=new ParameterDefinition(); - p.setName("Buyer"); - protocol.getParameterDefinitions().add(p); - - Introduces rl=new Introduces(); - Role buyer=new Role(); - buyer.setName("Buyer"); - rl.setIntroducer(buyer); - Role seller=new Role(); - seller.setName("Seller"); - rl.getIntroducedRoles().add(seller); - - protocol.getBlock().add(rl); - - RecBlock lb=new RecBlock(); - - lb.setLabel("Transaction"); - - Interaction interaction=new Interaction(); - - MessageSignature ms=new MessageSignature(); - TypeReference tref=new TypeReference(); - tref.setName("Order"); - ms.getTypeReferences().add(tref); - interaction.setMessageSignature(ms); - interaction.setFromRole(buyer); - interaction.getToRoles().add(seller); - - lb.getBlock().add(interaction); - - Choice choice=new Choice(); - - choice.setRole(seller); - - Block b1=new Block(); - choice.getPaths().add(b1); - - Interaction ib1=new Interaction(); - - ms=new MessageSignature(); - tref=new TypeReference(); - tref.setName("Rejected"); - ms.getTypeReferences().add(tref); - ms.setOperation("tryAgain"); - ib1.setMessageSignature(ms); - - ib1.setFromRole(seller); - ib1.getToRoles().add(buyer); - b1.add(ib1); - - Recursion recursion=new Recursion(); - recursion.setLabel("Transaction"); - - b1.add(recursion); - - Block b2=new Block(); - choice.getPaths().add(b2); - - Interaction ib2=new Interaction(); - - ms=new MessageSignature(); - tref=new TypeReference(); - tref.setName("Accepted"); - ms.getTypeReferences().add(tref); - ms.setOperation("exit"); - ib2.setMessageSignature(ms); - - ib2.setFromRole(seller); - ib2.getToRoles().add(buyer); - b2.add(ib2); - - lb.getBlock().add(choice); - - Interaction interaction2=new Interaction(); - - ms=new MessageSignature(); - tref=new TypeReference(); - tref.setName("Another"); - ms.getTypeReferences().add(tref); - interaction2.setMessageSignature(ms); - interaction2.setFromRole(buyer); - interaction2.getToRoles().add(seller); - - lb.getBlock().add(interaction2); - - protocol.getBlock().add(lb); - - Interaction interaction3=new Interaction(); - - ms=new MessageSignature(); - tref=new TypeReference(); - tref.setName("Finish"); - ms.getTypeReferences().add(tref); - interaction3.setMessageSignature(ms); - interaction3.setFromRole(buyer); - interaction3.getToRoles().add(seller); - - protocol.getBlock().add(interaction3); - - CTKUtil.verify(model, expected); - } - - @org.junit.Test - public void testRunSubProtocol() { - TestJournal logger=new TestJournal(); - - ProtocolModel model=CTKUtil.getModel("tests/protocol/global/RunSubProtocol.spr", logger); - - assertNotNull(model); - - assertTrue(logger.getErrorCount() == 0); - - // Build expected model - ProtocolModel expected=new ProtocolModel(); - - TypeImportList imp=new TypeImportList(); - TypeImport t=new TypeImport(); - t.setName("Order"); - imp.getTypeImports().add(t); - expected.getImports().add(imp); - - imp=new TypeImportList(); - t=new TypeImport(); - t.setName("Confirm"); - imp.getTypeImports().add(t); - expected.getImports().add(imp); - - Protocol protocol=new Protocol(); - expected.setProtocol(protocol); - - protocol.setName("RunSubProtocol"); - - ParameterDefinition p=new ParameterDefinition(); - p.setName("Buyer"); - protocol.getParameterDefinitions().add(p); - - Introduces rl=new Introduces(); - Role buyer=new Role(); - buyer.setName("Buyer"); - rl.setIntroducer(buyer); - Role seller=new Role(); - seller.setName("Seller"); - rl.getIntroducedRoles().add(seller); - - protocol.getBlock().add(rl); - - - Run run=new Run(); - - run.setFromRole(buyer); - - ProtocolReference ref=new ProtocolReference(); - ref.setName("Sub"); - - run.setProtocolReference(ref); - - Parameter db1=new Parameter("Buyer"); - run.getParameters().add(db1); - - Parameter db2=new Parameter("Seller"); - run.getParameters().add(db2); - - protocol.getBlock().add(run); - - Interaction interaction=new Interaction(); - - MessageSignature ms=new MessageSignature(); - TypeReference tref=new TypeReference(); - tref.setName("Confirm"); - ms.getTypeReferences().add(tref); - interaction.setMessageSignature(ms); - interaction.setFromRole(seller); - interaction.getToRoles().add(buyer); - - protocol.getBlock().add(interaction); - - - Protocol subprotocol=new Protocol(); - subprotocol.setName("Sub"); - - Role subbuyer=new Role(); - subbuyer.setName("SubBuyer"); - Role subseller=new Role(); - subseller.setName("SubSeller"); - - subprotocol.getParameterDefinitions().add(new ParameterDefinition("SubBuyer")); - subprotocol.getParameterDefinitions().add(new ParameterDefinition("SubSeller")); - - interaction=new Interaction(); - - ms=new MessageSignature(); - tref=new TypeReference(); - tref.setName("Order"); - ms.getTypeReferences().add(tref); - interaction.setMessageSignature(ms); - interaction.setFromRole(subbuyer); - interaction.getToRoles().add(subseller); - - subprotocol.getBlock().add(interaction); - - protocol.getNestedProtocols().add(subprotocol); - - CTKUtil.verify(model, expected); - } - @org.junit.Test - public void testInlineProtocol() { - TestJournal logger=new TestJournal(); - - ProtocolModel model=CTKUtil.getModel("tests/protocol/global/InlineProtocol.spr", logger); - - assertNotNull(model); - - assertTrue(logger.getErrorCount() == 0); - - // Build expected model - ProtocolModel expected=new ProtocolModel(); - - TypeImportList imp=new TypeImportList(); - TypeImport t=new TypeImport(); - t.setName("Order"); - imp.getTypeImports().add(t); - expected.getImports().add(imp); - - ProtocolImportList pimp=new ProtocolImportList(); - ProtocolImport pi=new ProtocolImport(); - pi.setName("Sub"); - pi.setLocation("ReferencedExternalProtocol.spr"); - pimp.getProtocolImports().add(pi); - expected.getImports().add(pimp); - - Protocol protocol=new Protocol(); - expected.setProtocol(protocol); - - protocol.setName("InlineProtocol"); - - ParameterDefinition p=new ParameterDefinition(); - p.setName("Buyer"); - protocol.getParameterDefinitions().add(p); - - Introduces rl=new Introduces(); - Role buyer=new Role(); - buyer.setName("Buyer"); - rl.setIntroducer(buyer); - Role seller=new Role(); - seller.setName("Seller"); - rl.getIntroducedRoles().add(seller); - - protocol.getBlock().add(rl); - - Inline inc=new Inline(); - - ProtocolReference ref=new ProtocolReference(); - ref.setName("Sub"); - - inc.setProtocolReference(ref); - - Parameter db1=new Parameter("Buyer"); - inc.getParameters().add(db1); - - Parameter db2=new Parameter("Seller"); - inc.getParameters().add(db2); - - protocol.getBlock().add(inc); - - CTKUtil.verify(model, expected); - } - - @org.junit.Test - public void testESBBroker() { - TestJournal logger=new TestJournal(); - - CTKUtil.getModel("tests/protocol/global/ESBBroker.spr", logger); - } - - @org.junit.Test - public void testESBBrokerWithAnnotations() { - TestJournal logger=new TestJournal(); - - CTKUtil.getModel("tests/protocol/global/ESBBrokerWithAnnotations.spr", logger); - } -} diff --git a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/ProtocolProjectorAllowOptionalTest.java b/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/ProtocolProjectorAllowOptionalTest.java deleted file mode 100644 index 223801da5..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/ProtocolProjectorAllowOptionalTest.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.ctk; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.scribble.protocol.ProtocolContext; -import org.scribble.protocol.projection.impl.ChoiceProjectorRule; - -import java.util.LinkedList; -import java.util.List; - -@RunWith(Parameterized.class) -public class ProtocolProjectorAllowOptionalTest { - - private String globalModelFile; - private String expectedLocalModelFile; - private ProtocolContext context; - - public ProtocolProjectorAllowOptionalTest(String globalModelFile, String expectedLocalModelFile, ProtocolContext context) { - this.globalModelFile = globalModelFile; - this.expectedLocalModelFile = expectedLocalModelFile; - this.context = context; - } - - @Parameterized.Parameters - public static List testcases() { - Object[][] array = new Object[][]{ - {"Recur2.spr", "Recur2@Buyer.spr"}, - {"Recur2.spr", "Recur2@Seller.spr"}, - {"ChoiceMergeableSimpleAllowOptional.spr", "ChoiceMergeableSimpleAllowOptional@C.spr"} - }; - List result = new LinkedList(); - for (Object[] sub: array) { - result.add(new Object[] { - "tests/protocol/global/" + sub[0], - "tests/protocol/local/" + sub[1], - (sub.length == 3 ? sub[2] : null) - }); - } - return result; - } - - @Test - public void doTest() { - System.setProperty(ChoiceProjectorRule.ALLOW_OPTIONAL, "true"); - - CTKUtil.checkProjectsSuccessfully(globalModelFile, expectedLocalModelFile, context); - - System.setProperty(ChoiceProjectorRule.ALLOW_OPTIONAL, "false"); - } - } diff --git a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/ProtocolProjectorRejectsTest.java b/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/ProtocolProjectorRejectsTest.java deleted file mode 100644 index d9630776e..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/ProtocolProjectorRejectsTest.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.ctk; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.scribble.protocol.ProtocolContext; -import org.scribble.protocol.export.text.TextProtocolExporter; -import org.scribble.protocol.model.ProtocolModel; -import org.scribble.protocol.model.Role; - -import java.io.ByteArrayOutputStream; -import java.util.LinkedList; -import java.util.List; - -import static org.junit.Assert.fail; - -@RunWith(Parameterized.class) -public class ProtocolProjectorRejectsTest { - - private String globalModelFile; - private ProtocolContext context; - private String projectedRole; - - public ProtocolProjectorRejectsTest(String globalModelFile, ProtocolContext context, String projectedRole) { - this.globalModelFile = globalModelFile; - this.context = context; - this.projectedRole = projectedRole; - } - - @Parameterized.Parameters - public static List testcases() { - Object[][] array = new Object[][]{ - {"ChoiceNotMergeableSimple.spr", null, "C"}, - {"ChoiceNotMergeableSimple2.spr", null, "C"}, - {"ChoiceNotMergeableRecursion.spr", null, "C"} - }; - List result = new LinkedList(); - for (Object[] sub: array) { - result.add(new Object[] { - "tests/protocol/global/witherrors/" + sub[0], - (sub.length >= 2 ? sub[1] : null), - (sub.length >= 3 ? sub[2] : null) - }); - } - return result; - } - - @Test - public void doTest() { - TestJournal logger=new TestJournal(); - - ProtocolModel model= CTKUtil.getModel(globalModelFile, logger); - - for (Role role: model.getRoles()) { - if (projectedRole == null || role.getName().equals(projectedRole)) { - ProtocolModel projected= CTKUtil.project(model, role, logger, context); - - if (logger.getErrorCount() == 0) { - ByteArrayOutputStream arrayOs = new ByteArrayOutputStream(); - new TextProtocolExporter().export(projected, logger, arrayOs); - fail("The protocol in file: " + globalModelFile + " should not be projectable. " + - "Projection was successful for role: " + role + ", result:\n" + arrayOs.toString()); - } - } - } - } -} diff --git a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/ProtocolProjectorTest.java b/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/ProtocolProjectorTest.java deleted file mode 100644 index 20b5c046c..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/ProtocolProjectorTest.java +++ /dev/null @@ -1,140 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.ctk; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.scribble.protocol.ProtocolContext; - -import java.util.LinkedList; -import java.util.List; - -@RunWith(Parameterized.class) -public class ProtocolProjectorTest { - - private String globalModelFile; - private String expectedLocalModelFile; - private ProtocolContext context; - - public ProtocolProjectorTest(String globalModelFile, String expectedLocalModelFile, ProtocolContext context) { - this.globalModelFile = globalModelFile; - this.expectedLocalModelFile = expectedLocalModelFile; - this.context = context; - } - - @Parameterized.Parameters - public static List testcases() { - Object[][] array = new Object[][]{ -/* - {"ChoiceMergeableSimple.spr", "ChoiceMergeableSimple@C.spr"}, - - {"Annotation.spr", "Annotation@Buyer.spr"}, // 0 - {"Annotation.spr", "Annotation@Seller.spr"}, // 1 - - {"ChoiceProjection.spr", "ChoiceProjection@C.spr"}, // 2 - - {"Choice.spr", "Choice@Buyer.spr"}, // 2 - {"Choice.spr", "Choice@Seller.spr"}, // 3 - {"ChoiceMerge.spr", "ChoiceMerge@Broker.spr"}, // 4 - {"ChoiceMerge.spr", "ChoiceMerge@Seller.spr"}, // 5 - - {"ChoiceMergeCommonPrefix.spr", "ChoiceMergeCommonPrefix@A.spr"}, // 6 - {"ChoiceMergeCommonPrefix.spr", "ChoiceMergeCommonPrefix@B.spr"}, // 7 - {"ChoiceMergeCommonPrefix.spr", "ChoiceMergeCommonPrefix@C.spr"}, - - {"ChoiceMergeIdenticalBranches.spr", "ChoiceMergeIdenticalBranches@A.spr"}, // 8 - {"ChoiceMergeIdenticalBranches.spr", "ChoiceMergeIdenticalBranches@B.spr"}, // 9 - {"ChoiceMergeIdenticalBranches.spr", "ChoiceMergeIdenticalBranches@C.spr"}, // 10 - - // TODO: POSSIBLE INVALID EXAMPLE, DUE TO CHAIN OF INTRODUCTION - //{"ChoiceMergeNested.spr", "ChoiceMergeNested@A.spr"}, // 11 - //{"ChoiceMergeNested.spr", "ChoiceMergeNested@B.spr"}, // 12 - //{"ChoiceMergeNested.spr", "ChoiceMergeNested@C.spr"}, // 13 - //{"ChoiceMergeNested.spr", "ChoiceMergeNested@D.spr"}, // 14 - - {"InlineProtocol.spr", "InlineProtocol@Buyer.spr", CTKUtil.getProtocolContext("tests/protocol/global")}, // 14 - {"InlineProtocol.spr", "InlineProtocol@Seller.spr", CTKUtil.getProtocolContext("tests/protocol/global")}, // 15 - - {"MultiPartyInteractionsAndChoice.spr", "MultiPartyInteractionsAndChoice@Broker.spr"}, // 16 - {"MultiPartyInteractionsAndChoice.spr", "MultiPartyInteractionsAndChoice@Buyer.spr"}, // 17 - {"MultiPartyInteractionsAndChoice.spr", "MultiPartyInteractionsAndChoice@CreditAgency.spr"}, // 18 - {"MultiPartyInteractionsAndChoice.spr", "MultiPartyInteractionsAndChoice@Seller.spr"}, // 19 - {"MultiPartyInteractionsAndChoice2.spr", "MultiPartyInteractionsAndChoice2@Broker.spr"}, // 20 - {"MultiPartyInteractionsAndChoice2.spr", "MultiPartyInteractionsAndChoice2@Buyer.spr"}, // 21 - {"MultiPartyInteractionsAndChoice2.spr", "MultiPartyInteractionsAndChoice2@Seller.spr"}, // 22 - - {"MulticastInteraction.spr", "MulticastInteraction@Buyer.spr"}, // 23 - {"MulticastInteraction.spr", "MulticastInteraction@SellerA.spr"}, // 24 - {"Parallel.spr", "Parallel@Buyer.spr"}, // 27 - {"Parallel.spr", "Parallel@Seller.spr"}, // 28 - - {"Recur.spr", "Recur@Buyer.spr"}, - {"Recur.spr", "Recur@Seller.spr"}, - {"Repeat.spr", "Repeat@Buyer.spr"}, - {"Repeat.spr", "Repeat@Seller.spr"}, - {"Repeat2.spr", "Repeat2@CreditAgency.spr"}, - {"Repeat2.spr", "Repeat2@Buyer.spr"}, - {"RunExternalProtocol.spr", "RunExternalProtocol@Buyer.spr", CTKUtil.getProtocolContext("tests/protocol/global")}, - {"RunExternalProtocol.spr", "RunExternalProtocol@Seller.spr", CTKUtil.getProtocolContext("tests/protocol/global")}, - {"RunSubProtocol.spr", "RunSubProtocol@Buyer.spr"}, - {"RunSubProtocol.spr", "RunSubProtocol@Seller.spr"}, - - {"SingleInteraction.spr", "SingleInteraction@Buyer.spr"}, - {"SingleInteraction.spr", "SingleInteraction@Seller.spr"}, - {"SingleInteractionXSDImport.spr", "SingleInteractionXSDImport@Buyer.spr"}, - {"SingleInteractionXSDImport.spr", "SingleInteractionXSDImport@Seller.spr"}, - - {"DoInterrupt.spr", "DoInterrupt@Buyer.spr"}, - {"DoInterrupt.spr", "DoInterrupt@Seller.spr"}, - {"Unordered.spr", "Unordered@Buyer.spr"}, - {"Unordered.spr", "Unordered@Seller.spr"}, - {"PurchaseGoods3.spr", "PurchaseGoods3@Buyer.spr"}, - {"PurchaseGoods3.spr", "PurchaseGoods3@Store.spr"}, - {"PurchaseGoods3.spr", "PurchaseGoods3@Logistics.spr"}, -*/ - {"DirectedChoice.spr", "DirectedChoice@Buyer.spr"}, -/* - {"DirectedChoice.spr", "DirectedChoice@Seller.spr"}, - - {"End.spr", "End@Buyer.spr"}, - {"End.spr", "End@Seller.spr"}, - - {"ESBBroker.spr", "ESBBroker@Broker.spr"}, - {"ESBBroker.spr", "ESBBroker@CreditAgency.spr"}, - - /* - {"ESBBroker.spr", "ESBBroker@SupplierTxnProcessor.spr"} - /* - */ - }; - List result = new LinkedList(); - for (Object[] sub: array) { - result.add(new Object[] { - "tests/protocol/global/" + sub[0], - "tests/protocol/local/" + sub[1], - (sub.length == 3 ? sub[2] : CTKUtil.getProtocolContext(null)) - }); - } - return result; - } - - @Test - public void doTest() { - CTKUtil.checkProjectsSuccessfully(globalModelFile, expectedLocalModelFile, context); - } -} diff --git a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/ProtocolProjectorTestCasesRejectsTest.java b/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/ProtocolProjectorTestCasesRejectsTest.java deleted file mode 100644 index 11c71006b..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/ProtocolProjectorTestCasesRejectsTest.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.ctk; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.scribble.protocol.ProtocolContext; -import org.scribble.protocol.export.text.TextProtocolExporter; -import org.scribble.protocol.model.ProtocolModel; -import org.scribble.protocol.model.Role; - -import java.io.ByteArrayOutputStream; -import java.util.LinkedList; -import java.util.List; - -import static org.junit.Assert.fail; - -@RunWith(Parameterized.class) -public class ProtocolProjectorTestCasesRejectsTest { - - private String globalModelFile; - private ProtocolContext context; - private String projectedRole; - - public ProtocolProjectorTestCasesRejectsTest(String globalModelFile, ProtocolContext context, String projectedRole) { - this.globalModelFile = globalModelFile; - this.context = context; - this.projectedRole = projectedRole; - } - - @Parameterized.Parameters - public static List testcases() { - Object[][] array = new Object[][]{ - {"SCRIBBLE-126.spr", null, "C"}, - }; - List result = new LinkedList(); - for (Object[] sub: array) { - result.add(new Object[] { - "tests/protocol/global/testcase/" + sub[0], - (sub.length >= 2 ? sub[1] : null), - (sub.length >= 3 ? sub[2] : null) - }); - } - return result; - } - - @Test - public void doTest() { - TestJournal logger=new TestJournal(); - - ProtocolModel model= CTKUtil.getModel(globalModelFile, logger); - - for (Role role: model.getRoles()) { - if (projectedRole == null || role.getName().equals(projectedRole)) { - ProtocolModel projected= CTKUtil.project(model, role, logger, context); - - if (logger.getErrorCount() == 0) { - ByteArrayOutputStream arrayOs = new ByteArrayOutputStream(); - new TextProtocolExporter().export(projected, logger, arrayOs); - fail("The protocol in file: " + globalModelFile + " should not be projectable. " + - "Projection was successful for role: " + role + ", result:\n" + arrayOs.toString()); - } - } - } - } -} diff --git a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/ProtocolProjectorTestCasesTest.java b/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/ProtocolProjectorTestCasesTest.java deleted file mode 100644 index 7831d5f04..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/ProtocolProjectorTestCasesTest.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.ctk; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.scribble.protocol.ProtocolContext; - -import java.util.LinkedList; -import java.util.List; - -@RunWith(Parameterized.class) -public class ProtocolProjectorTestCasesTest { - - private String globalModelFile; - private String expectedLocalModelFile; - private ProtocolContext context; - - public ProtocolProjectorTestCasesTest(String globalModelFile, String expectedLocalModelFile, ProtocolContext context) { - this.globalModelFile = globalModelFile; - this.expectedLocalModelFile = expectedLocalModelFile; - this.context = context; - } - - @Parameterized.Parameters - public static List testcases() { - Object[][] array = new Object[][]{ - - {"SCRIBBLE-125.spr", "SCRIBBLE-125@C.spr"}, - - }; - List result = new LinkedList(); - for (Object[] sub: array) { - result.add(new Object[] { - "tests/protocol/global/testcase/" + sub[0], - "tests/protocol/local/testcase/" + sub[1], - (sub.length == 3 ? sub[2] : CTKUtil.getProtocolContext(null)) - }); - } - return result; - } - - @Test - public void doTest() { - CTKUtil.checkProjectsSuccessfully(globalModelFile, expectedLocalModelFile, context); - } -} diff --git a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/TestJournal.java b/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/TestJournal.java deleted file mode 100644 index 25787fc20..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/TestJournal.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright 2009 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.ctk; - -import java.util.Map; - -import org.scribble.common.logging.Journal; - -import static org.junit.Assert.*; - -public class TestJournal implements Journal { - - public void debug(String issue, Map props) { - } - - public void error(String issue, Map props) { - m_errors.add(issue); - } - - public int getErrorCount() { - return (m_errors.size()); - } - - public void verifyErrors(String[] errors) { - java.util.List logged=new java.util.Vector(m_errors); - - for (int i=0; i < errors.length; i++) { - int ind=logged.indexOf(errors[i]); - - if (ind == -1) { - fail("Expected message '"+errors[i]+"' did not occur"); - } else { - logged.remove(ind); - } - } - - if (logged.size() > 0) { - fail("Unexpected errors occurred: "+logged); - } - } - - public void info(String issue, Map props) { - } - - public void trace(String issue, Map props) { - } - - public void warning(String issue, Map props) { - } - - public java.util.List getErrors() { - return(m_errors); - } - - private java.util.List m_errors=new java.util.Vector(); -} diff --git a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/AnnotationsComparator.java b/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/AnnotationsComparator.java deleted file mode 100644 index da05ab42b..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/AnnotationsComparator.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright 2009 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.ctk.comparators; - -import java.util.Comparator; -import org.scribble.common.model.Annotation; - -public class AnnotationsComparator implements Comparator> { - - public int compare(java.util.List arg0, java.util.List arg1) { - java.util.List m=(java.util.List)arg0; - java.util.List e=(java.util.List)arg1; - - if (m == null && e == null) { - return (0); - } - - if (m == null || e == null){ - return (1); - } - - if (m.size() != e.size()) { - return (2); - } - - for (int i=0; i < m.size(); i++) { - if (m.get(i).toString().equals(e.get(i).toString()) == false) { - return (1); - } - } - - return (0); - } -} diff --git a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/BlockComparator.java b/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/BlockComparator.java deleted file mode 100644 index 4c4c84468..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/BlockComparator.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright 2009 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.ctk.comparators; - -import java.util.Comparator; -import org.scribble.protocol.model.*; - -public class BlockComparator implements Comparator { - - public int compare(ModelObject arg0, ModelObject arg1) { - Block m=(Block)arg0; - Block e=(Block)arg1; - - if (m.size() != e.size()) { - return (1); - } - - return (0); - } -} diff --git a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/ChoiceComparator.java b/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/ChoiceComparator.java deleted file mode 100644 index ddd2ce21a..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/ChoiceComparator.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.ctk.comparators; - -import java.util.Comparator; - -import org.scribble.protocol.ctk.ComparatorUtil; -import org.scribble.protocol.model.*; - -public class ChoiceComparator implements Comparator { - - public int compare(ModelObject arg0, ModelObject arg1) { - Choice m=(Choice)arg0; - Choice e=(Choice)arg1; - - RoleComparator pcomp=(RoleComparator) - ComparatorUtil.getComparator(Role.class); - - if (pcomp.compare(m.getRole(), e.getRole()) != 0) { - return (1); - } - - if (m.getPaths().size() != e.getPaths().size()) { - return (1); - } - - return (0); - } -} diff --git a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/DataTypeComparator.java b/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/DataTypeComparator.java deleted file mode 100644 index 297d8c52e..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/DataTypeComparator.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright 2009 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.ctk.comparators; - -import java.util.Comparator; -import org.scribble.protocol.model.*; - -public class DataTypeComparator implements Comparator { - - public int compare(ModelObject arg0, ModelObject arg1) { - DataType m=(DataType)arg0; - DataType e=(DataType)arg1; - - if (m == null && e == null) { - return (0); - } - - if (m == null || e == null){ - return (1); - } - - if (m.getDetails() != null && e.getDetails() != null) { - if (m.getDetails().equals(e.getDetails()) == false) { - return (1); - } - } else if (m.getDetails() != null || e.getDetails() != null) { - return (1); - } - - return (0); - } -} diff --git a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/DirectedChoiceComparator.java b/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/DirectedChoiceComparator.java deleted file mode 100644 index abea6c658..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/DirectedChoiceComparator.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.ctk.comparators; - -import java.util.Comparator; - -import org.scribble.protocol.ctk.ComparatorUtil; -import org.scribble.protocol.model.*; - -public class DirectedChoiceComparator implements Comparator { - - public int compare(ModelObject arg0, ModelObject arg1) { - DirectedChoice m=(DirectedChoice)arg0; - DirectedChoice e=(DirectedChoice)arg1; - - RoleComparator pcomp=(RoleComparator) - ComparatorUtil.getComparator(Role.class); - - if (m.getFromRole() == null) { - if (e.getFromRole() != null) { - return (1); - } - } else if (pcomp.compare(m.getFromRole(), - e.getFromRole()) != 0) { - return (1); - } - - if (m.getToRoles().size() != e.getToRoles().size()) { - return (1); - } else { - for (int i=0; i < m.getToRoles().size(); i++) { - if (pcomp.compare(m.getToRoles().get(i), - e.getToRoles().get(i)) != 0) { - return (1); - } - } - } - - if (m.getOnMessages().size() != e.getOnMessages().size()) { - return (1); - } - - return (0); - } -} diff --git a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/DoComparator.java b/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/DoComparator.java deleted file mode 100644 index 29688ae76..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/DoComparator.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.ctk.comparators; - -import java.util.Comparator; -import org.scribble.protocol.model.*; - -public class DoComparator implements Comparator { - - public int compare(ModelObject arg0, ModelObject arg1) { - Do m=(Do)arg0; - Do e=(Do)arg1; - - Comparator> ancomp=new AnnotationsComparator(); - - if (ancomp.compare(m.getAnnotations(), e.getAnnotations()) != 0) { - return (1); - } - - return (0); - } -} diff --git a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/EndComparator.java b/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/EndComparator.java deleted file mode 100644 index f41c67683..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/EndComparator.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.ctk.comparators; - -import java.util.Comparator; - -import org.scribble.protocol.model.*; - -public class EndComparator implements Comparator { - - public int compare(ModelObject arg0, ModelObject arg1) { - if (arg0.getClass() != End.class || arg1.getClass() != End.class) { - return (1); - } - return (0); - } -} diff --git a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/InteractionComparator.java b/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/InteractionComparator.java deleted file mode 100644 index 21d91dd96..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/InteractionComparator.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright 2009 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.ctk.comparators; - -import java.util.Comparator; - -import org.scribble.protocol.ctk.ComparatorUtil; -import org.scribble.protocol.model.*; - -public class InteractionComparator implements Comparator { - - public int compare(ModelObject arg0, ModelObject arg1) { - Interaction m=(Interaction)arg0; - Interaction e=(Interaction)arg1; - - Comparator mscomp= - ComparatorUtil.getComparator(MessageSignature.class); - - Comparator pcomp= - ComparatorUtil.getComparator(Role.class); - - if (mscomp.compare(m.getMessageSignature(), - e.getMessageSignature()) != 0) { - return (1); - } - - if (m.getFromRole() == null) { - if (e.getFromRole() != null) { - return (1); - } - } else if (pcomp.compare(m.getFromRole(), - e.getFromRole()) != 0) { - return (1); - } - - if (m.getToRoles().size() != e.getToRoles().size()) { - return (1); - } else { - for (int i=0; i < m.getToRoles().size(); i++) { - if (pcomp.compare(m.getToRoles().get(i), - e.getToRoles().get(i)) != 0) { - return (1); - } - } - } - - Comparator> ancomp=new AnnotationsComparator(); - - if (ancomp.compare(m.getAnnotations(), e.getAnnotations()) != 0) { - return (1); - } - - return (0); - } -} diff --git a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/InterruptComparator.java b/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/InterruptComparator.java deleted file mode 100644 index f7f1c5aa4..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/InterruptComparator.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.ctk.comparators; - -import java.util.Comparator; - -import org.scribble.protocol.model.*; - -public class InterruptComparator implements Comparator { - - public int compare(ModelObject arg0, ModelObject arg1) { - Interrupt m=(Interrupt)arg0; - Interrupt e=(Interrupt)arg1; - - if (m.getBlock().size() != e.getBlock().size()) { - return (1); - } - - return (0); - } -} diff --git a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/IntroducesComparator.java b/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/IntroducesComparator.java deleted file mode 100644 index 02fca0ce4..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/IntroducesComparator.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright 2009 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.ctk.comparators; - -import java.util.Comparator; - -import org.scribble.protocol.ctk.ComparatorUtil; -import org.scribble.protocol.model.*; - -public class IntroducesComparator implements Comparator { - - public int compare(ModelObject arg0, ModelObject arg1) { - Introduces m=(Introduces)arg0; - Introduces e=(Introduces)arg1; - - if (m.getIntroducedRoles().size() == e.getIntroducedRoles().size()) { - RoleComparator pcomp=(RoleComparator) - ComparatorUtil.getComparator(Role.class); - - for (int i=0; i < m.getIntroducedRoles().size(); i++) { - if (pcomp.compare(m.getIntroducedRoles().get(i), e.getIntroducedRoles().get(i)) != 0) { - return (1); - } - } - } else { - return (1); - } - - Comparator> ancomp=new AnnotationsComparator(); - - if (ancomp.compare(m.getAnnotations(), e.getAnnotations()) != 0) { - return (1); - } - - return (0); - } -} diff --git a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/MessageSignatureComparator.java b/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/MessageSignatureComparator.java deleted file mode 100644 index d9db673e1..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/MessageSignatureComparator.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright 2009 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.ctk.comparators; - -import java.util.Comparator; - -import org.scribble.protocol.ctk.ComparatorUtil; -import org.scribble.protocol.model.*; - -public class MessageSignatureComparator implements Comparator { - - public int compare(ModelObject arg0, ModelObject arg1) { - MessageSignature m=(MessageSignature)arg0; - MessageSignature e=(MessageSignature)arg1; - - if (m.getOperation() == null && - e.getOperation() == null) { - // Matches - } else if (m.getOperation() != null && - e.getOperation() != null && - m.getOperation().equals(e.getOperation())) { - // Matches - } else { - return (1); - } - - if (m.getTypeReferences().size() != e.getTypeReferences().size()) { - return (1); - } - - Comparator trcomp= - ComparatorUtil.getComparator(TypeReference.class); - - for (int i=0; i < m.getTypeReferences().size(); i++) { - if (trcomp.compare(m.getTypeReferences().get(i), e.getTypeReferences().get(i)) != 0) { - return (1); - } - } - - return (0); - } -} diff --git a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/ModelComparator.java b/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/ModelComparator.java deleted file mode 100644 index 1c34686f7..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/ModelComparator.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright 2009 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.ctk.comparators; - -import java.util.Comparator; -import org.scribble.protocol.model.*; - -public class ModelComparator implements Comparator { - - public int compare(ModelObject arg0, ModelObject arg1) { - return (0); - } -} diff --git a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/OnMessageComparator.java b/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/OnMessageComparator.java deleted file mode 100644 index 378134f85..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/OnMessageComparator.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.ctk.comparators; - -import java.util.Comparator; - -import org.scribble.protocol.ctk.ComparatorUtil; -import org.scribble.protocol.model.*; - -public class OnMessageComparator implements Comparator { - - public int compare(ModelObject arg0, ModelObject arg1) { - OnMessage m=(OnMessage)arg0; - OnMessage e=(OnMessage)arg1; - - Comparator mscomp= - ComparatorUtil.getComparator(MessageSignature.class); - - if (mscomp.compare(m.getMessageSignature(), - e.getMessageSignature()) != 0) { - return (1); - } - - if (m.getBlock().size() != e.getBlock().size()) { - return (1); - } - - return (0); - } -} diff --git a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/ParallelComparator.java b/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/ParallelComparator.java deleted file mode 100644 index 43e0a68d3..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/ParallelComparator.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.ctk.comparators; - -import java.util.Comparator; -import org.scribble.protocol.model.*; - -public class ParallelComparator implements Comparator { - - public int compare(ModelObject arg0, ModelObject arg1) { - Parallel m=(Parallel)arg0; - Parallel e=(Parallel)arg1; - - if (m.getPaths().size() != e.getPaths().size()) { - return (1); - } - - Comparator> ancomp=new AnnotationsComparator(); - - if (ancomp.compare(m.getAnnotations(), e.getAnnotations()) != 0) { - return (1); - } - - return (0); - } -} diff --git a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/ParameterComparator.java b/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/ParameterComparator.java deleted file mode 100644 index 977a6ec8e..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/ParameterComparator.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.ctk.comparators; - -import java.util.Comparator; -import org.scribble.protocol.model.*; - -public class ParameterComparator implements Comparator { - - public int compare(ModelObject arg0, ModelObject arg1) { - Parameter m=(Parameter)arg0; - Parameter e=(Parameter)arg1; - - if (m.getName().equals(e.getName())) { - return (0); - } - - return (1); - } -} diff --git a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/ParameterDefinitionComparator.java b/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/ParameterDefinitionComparator.java deleted file mode 100644 index d09064f2f..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/ParameterDefinitionComparator.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright 2009 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.ctk.comparators; - -import java.util.Comparator; -import org.scribble.protocol.model.*; - -public class ParameterDefinitionComparator implements Comparator { - - public int compare(ModelObject arg0, ModelObject arg1) { - ParameterDefinition m=(ParameterDefinition)arg0; - ParameterDefinition e=(ParameterDefinition)arg1; - - if (m == null && e == null) { - return (0); - } - - if (m == null || e == null){ - return (1); - } - - if (m.getName().equals(e.getName()) && - (m.getType().equals(e.getType()))) { - return (0); - } - - return (1); - } -} diff --git a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/ProtocolComparator.java b/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/ProtocolComparator.java deleted file mode 100644 index 4591ca7cb..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/ProtocolComparator.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright 2009 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.ctk.comparators; - -import java.util.Comparator; -import org.scribble.protocol.model.*; - -public class ProtocolComparator implements Comparator { - - public int compare(ModelObject arg0, ModelObject arg1) { - Protocol m=(Protocol)arg0; - Protocol e=(Protocol)arg1; - - if (m.getName() == null || e.getName() == null) { - return (1); - } - - if (m.getName().equals(e.getName()) == false) { - return (1); - } - - if (m.getParameterDefinitions().size() != e.getParameterDefinitions().size()) { - return (1); - } - - for (int i=0; i < m.getParameterDefinitions().size(); i++) { - if (m.getParameterDefinitions().get(i).equals(e.getParameterDefinitions().get(i)) == false) { - return (1); - } - } - - Comparator> ancomp=new AnnotationsComparator(); - - if (ancomp.compare(m.getAnnotations(), e.getAnnotations()) != 0) { - return (1); - } - - return (0); - } -} diff --git a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/ProtocolImportComparator.java b/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/ProtocolImportComparator.java deleted file mode 100644 index 6a8ee1b65..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/ProtocolImportComparator.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.ctk.comparators; - -import java.util.Comparator; - -import org.scribble.protocol.model.*; - -public class ProtocolImportComparator implements Comparator { - - public int compare(ModelObject arg0, ModelObject arg1) { - ProtocolImport m=(ProtocolImport)arg0; - ProtocolImport e=(ProtocolImport)arg1; - - if (m.getName().equals(e.getName())) { - return (0); - } - - if (m.getLocation().equals(e.getLocation())) { - return (0); - } - - return (1); - } -} diff --git a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/ProtocolImportListComparator.java b/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/ProtocolImportListComparator.java deleted file mode 100644 index d0f2808f1..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/ProtocolImportListComparator.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.ctk.comparators; - -import java.util.Comparator; - -import org.scribble.protocol.ctk.ComparatorUtil; -import org.scribble.protocol.model.*; - -public class ProtocolImportListComparator implements Comparator { - - public int compare(ModelObject arg0, ModelObject arg1) { - ProtocolImportList m=(ProtocolImportList)arg0; - ProtocolImportList e=(ProtocolImportList)arg1; - - if (m.getProtocolImports().size() == e.getProtocolImports().size()) { - Comparator pcomp=(Comparator ) - ComparatorUtil.getComparator(ProtocolImport.class); - - for (int i=0; i < m.getProtocolImports().size(); i++) { - if (pcomp.compare(m.getProtocolImports().get(i), e.getProtocolImports().get(i)) != 0) { - return (1); - } - } - } else { - return (1); - } - - Comparator> ancomp=new AnnotationsComparator(); - - if (ancomp.compare(m.getAnnotations(), e.getAnnotations()) != 0) { - return (1); - } - - return (0); - } -} diff --git a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/ProtocolReferenceComparator.java b/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/ProtocolReferenceComparator.java deleted file mode 100644 index 62a19fa3f..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/ProtocolReferenceComparator.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright 2009 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.ctk.comparators; - -import java.util.Comparator; - -import org.scribble.protocol.ctk.ComparatorUtil; -import org.scribble.protocol.model.*; - -public class ProtocolReferenceComparator implements Comparator { - - public int compare(ModelObject arg0, ModelObject arg1) { - ProtocolReference m=(ProtocolReference)arg0; - ProtocolReference e=(ProtocolReference)arg1; - - if (m.getName() != null && - e.getName() != null && - m.getName().equals(e.getName())) { - - if (m.getRole() == null && - e.getRole() == null) { - return (0); - } else if (m.getRole() != null && - e.getRole() != null) { - RoleComparator pcomp=(RoleComparator) - ComparatorUtil.getComparator(Role.class); - - return (pcomp.compare(m.getRole(), e.getRole())); - } - } - - return (1); - } -} diff --git a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/RecBlockComparator.java b/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/RecBlockComparator.java deleted file mode 100644 index 30b90fe67..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/RecBlockComparator.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.ctk.comparators; - -import java.util.Comparator; - -import org.scribble.protocol.model.*; - -public class RecBlockComparator implements Comparator { - - public int compare(ModelObject arg0, ModelObject arg1) { - RecBlock m=(RecBlock)arg0; - RecBlock e=(RecBlock)arg1; - - if (m.getLabel().equals(e.getLabel()) == false) { - return (1); - } - - if (m.getBlock().size() != e.getBlock().size()) { - return (1); - } - - Comparator> ancomp=new AnnotationsComparator(); - - if (ancomp.compare(m.getAnnotations(), e.getAnnotations()) != 0) { - return (1); - } - - return (0); - } -} diff --git a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/RecursionComparator.java b/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/RecursionComparator.java deleted file mode 100644 index 2b3709770..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/RecursionComparator.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.ctk.comparators; - -import java.util.Comparator; - -import org.scribble.protocol.model.*; - -public class RecursionComparator implements Comparator { - - public int compare(ModelObject arg0, ModelObject arg1) { - Recursion m=(Recursion)arg0; - Recursion e=(Recursion)arg1; - - if (m.getLabel().equals(e.getLabel()) == false) { - return (1); - } - - Comparator> ancomp=new AnnotationsComparator(); - - if (ancomp.compare(m.getAnnotations(), e.getAnnotations()) != 0) { - return (1); - } - - return (0); - } -} diff --git a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/RepeatComparator.java b/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/RepeatComparator.java deleted file mode 100644 index f46e91e20..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/RepeatComparator.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.ctk.comparators; - -import java.util.Comparator; - -import org.scribble.protocol.ctk.ComparatorUtil; -import org.scribble.protocol.model.*; - -public class RepeatComparator implements Comparator { - - public int compare(ModelObject arg0, ModelObject arg1) { - Repeat m=(Repeat)arg0; - Repeat e=(Repeat)arg1; - - if (m.getRoles().size() != e.getRoles().size()) { - return (1); - } - - RoleComparator pcomp=(RoleComparator) - ComparatorUtil.getComparator(Role.class); - - for (int i=0; i < m.getRoles().size(); i++) { - if (pcomp.compare(m.getRoles().get(i), e.getRoles().get(i)) != 0) { - return (1); - } - } - - if (m.getBlock().size() != e.getBlock().size()) { - return (1); - } - - Comparator> ancomp=new AnnotationsComparator(); - - if (ancomp.compare(m.getAnnotations(), e.getAnnotations()) != 0) { - return (1); - } - - return (0); - } -} diff --git a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/RoleComparator.java b/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/RoleComparator.java deleted file mode 100644 index 98958cce3..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/RoleComparator.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright 2009 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.ctk.comparators; - -import java.util.Comparator; -import org.scribble.protocol.model.*; - -public class RoleComparator implements Comparator { - - public int compare(ModelObject arg0, ModelObject arg1) { - Role m=(Role)arg0; - Role e=(Role)arg1; - - if (m == null && e == null) { - return (0); - } - - if (m == null || e == null){ - return (1); - } - - if (m.getName().equals(e.getName())) { - return (0); - } - - return (1); - } -} diff --git a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/RunComparator.java b/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/RunComparator.java deleted file mode 100644 index 009b94643..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/RunComparator.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.ctk.comparators; - -import java.util.Comparator; - -import org.scribble.protocol.ctk.ComparatorUtil; -import org.scribble.protocol.model.*; - -public class RunComparator implements Comparator { - - public int compare(ModelObject arg0, ModelObject arg1) { - Run m=(Run)arg0; - Run e=(Run)arg1; - - RoleComparator rc=(RoleComparator) - ComparatorUtil.getComparator(Role.class); - if (rc.compare(m.getFromRole(), e.getFromRole()) != 0) { - return (1); - } - - if (m.getProtocolReference() != null && e.getProtocolReference() != null) { - ProtocolReferenceComparator prcomp=(ProtocolReferenceComparator) - ComparatorUtil.getComparator(ProtocolReference.class); - - if (prcomp.compare(m.getProtocolReference(), e.getProtocolReference()) != 0) { - return (1); - } - } else if (m.getProtocolReference() != null || e.getProtocolReference() != null) { - return (1); - } - - if (m.getParameters().size() != e.getParameters().size()) { - return (1); - } - - ParameterComparator dbc=(ParameterComparator) - ComparatorUtil.getComparator(Parameter.class); - - for (int i=0; i < m.getParameters().size(); i++) { - if (dbc.compare(m.getParameters().get(i), e.getParameters().get(i)) != 0) { - return (1); - } - } - - Comparator> ancomp=new AnnotationsComparator(); - - if (ancomp.compare(m.getAnnotations(), e.getAnnotations()) != 0) { - return (1); - } - - return (0); - } -} diff --git a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/TypeImportComparator.java b/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/TypeImportComparator.java deleted file mode 100644 index c6ab5ec88..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/TypeImportComparator.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.ctk.comparators; - -import java.util.Comparator; - -import org.scribble.protocol.ctk.ComparatorUtil; -import org.scribble.protocol.model.*; - -public class TypeImportComparator implements Comparator { - - public int compare(ModelObject arg0, ModelObject arg1) { - TypeImport m=(TypeImport)arg0; - TypeImport e=(TypeImport)arg1; - - if (m.getName().equals(e.getName())) { - - if (m.getDataType() == null && e.getDataType() == null) { - return (0); - } - - Comparator dtc=ComparatorUtil.getComparator(DataType.class); - - if (m.getDataType() != null && e.getDataType() != null && - dtc.compare(m.getDataType(), e.getDataType()) == 0) { - return (0); - } - } - - return (1); - } -} diff --git a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/TypeImportListComparator.java b/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/TypeImportListComparator.java deleted file mode 100644 index b95842f76..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/TypeImportListComparator.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.ctk.comparators; - -import java.util.Comparator; - -import org.scribble.protocol.ctk.ComparatorUtil; -import org.scribble.protocol.model.*; - -public class TypeImportListComparator implements Comparator { - - public int compare(ModelObject arg0, ModelObject arg1) { - TypeImportList m=(TypeImportList)arg0; - TypeImportList e=(TypeImportList)arg1; - - if (m.getFormat() != null && e.getFormat() != null) { - if (m.getFormat().equals(e.getFormat()) == false) { - return (1); - } - } else if (m.getFormat() != null || e.getFormat() != null) { - return (1); - } - - if (m.getLocation() != null && e.getLocation() != null) { - if (m.getLocation().equals(e.getLocation()) == false) { - return (1); - } - } else if (m.getLocation() != null || e.getLocation() != null) { - return (1); - } - - if (m.getTypeImports().size() == e.getTypeImports().size()) { - Comparator pcomp=(Comparator ) - ComparatorUtil.getComparator(TypeImport.class); - - for (int i=0; i < m.getTypeImports().size(); i++) { - if (pcomp.compare(m.getTypeImports().get(i), e.getTypeImports().get(i)) != 0) { - return (1); - } - } - } else { - return (1); - } - - Comparator> ancomp=new AnnotationsComparator(); - - if (ancomp.compare(m.getAnnotations(), e.getAnnotations()) != 0) { - return (1); - } - - return (0); - } -} diff --git a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/TypeReferenceComparator.java b/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/TypeReferenceComparator.java deleted file mode 100644 index b8c20e896..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/TypeReferenceComparator.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright 2009 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.ctk.comparators; - -import java.util.Comparator; - -import org.scribble.protocol.model.ModelObject; -import org.scribble.protocol.model.TypeReference; - -public class TypeReferenceComparator implements Comparator { - - public int compare(ModelObject arg0, ModelObject arg1) { - TypeReference m=(TypeReference)arg0; - TypeReference e=(TypeReference)arg1; - - if (m.getName() != null && - e.getName() != null && - m.getName().equals(e.getName())) { - return (0); - } - - return (1); - } -} diff --git a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/UnorderedComparator.java b/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/UnorderedComparator.java deleted file mode 100644 index 80ab6bcc3..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/UnorderedComparator.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.ctk.comparators; - -import java.util.Comparator; - -import org.scribble.protocol.model.*; - -public class UnorderedComparator implements Comparator { - - public int compare(ModelObject arg0, ModelObject arg1) { - Unordered m=(Unordered)arg0; - Unordered e=(Unordered)arg1; - - if (m.getBlock().size() != e.getBlock().size()) { - return (1); - } - - Comparator> ancomp=new AnnotationsComparator(); - - if (ancomp.compare(m.getAnnotations(), e.getAnnotations()) != 0) { - return (1); - } - - return (0); - } -} diff --git a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/UseComparator.java b/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/UseComparator.java deleted file mode 100644 index 769335ade..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/java/org/scribble/protocol/ctk/comparators/UseComparator.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright 2009-10 www.scribble.org - * 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 - * - * http://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. - * - */ -package org.scribble.protocol.ctk.comparators; - -import java.util.Comparator; - -import org.scribble.protocol.ctk.ComparatorUtil; -import org.scribble.protocol.model.*; - -public class UseComparator implements Comparator { - - public int compare(ModelObject arg0, ModelObject arg1) { - Inline m=(Inline)arg0; - Inline e=(Inline)arg1; - - if (m.getProtocolReference() != null && e.getProtocolReference() != null) { - ProtocolReferenceComparator prcomp=(ProtocolReferenceComparator) - ComparatorUtil.getComparator(ProtocolReference.class); - - if (prcomp.compare(m.getProtocolReference(), e.getProtocolReference()) != 0) { - return (1); - } - } else if (m.getProtocolReference() != null || e.getProtocolReference() != null) { - return (1); - } - - if (m.getParameters().size() != e.getParameters().size()) { - return (1); - } - - ParameterComparator dbc=(ParameterComparator) - ComparatorUtil.getComparator(Parameter.class); - - for (int i=0; i < m.getParameters().size(); i++) { - if (dbc.compare(m.getParameters().get(i), e.getParameters().get(i)) != 0) { - return (1); - } - } - - return (0); - } -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/DirectedChoice-1@Buyer.events b/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/DirectedChoice-1@Buyer.events deleted file mode 100644 index 510c5c0d6..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/DirectedChoice-1@Buyer.events +++ /dev/null @@ -1 +0,0 @@ -send,Cancel diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/DirectedChoice-1@Seller.events b/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/DirectedChoice-1@Seller.events deleted file mode 100644 index d8099f299..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/DirectedChoice-1@Seller.events +++ /dev/null @@ -1 +0,0 @@ -receive,Cancel diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/DirectedChoice-2@Buyer.events b/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/DirectedChoice-2@Buyer.events deleted file mode 100644 index 4240a6940..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/DirectedChoice-2@Buyer.events +++ /dev/null @@ -1,2 +0,0 @@ -send,Order -receive,Invoice diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/DirectedChoice-2@Seller.events b/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/DirectedChoice-2@Seller.events deleted file mode 100644 index 8306aee16..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/DirectedChoice-2@Seller.events +++ /dev/null @@ -1,2 +0,0 @@ -receive,Order -send,Invoice diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/DoInterrupt-1@Buyer.events b/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/DoInterrupt-1@Buyer.events deleted file mode 100644 index face16d38..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/DoInterrupt-1@Buyer.events +++ /dev/null @@ -1,3 +0,0 @@ -send,Order -receive,Confirm -send,Finish diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/DoInterrupt-1@Seller.events b/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/DoInterrupt-1@Seller.events deleted file mode 100644 index 148355ad4..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/DoInterrupt-1@Seller.events +++ /dev/null @@ -1,3 +0,0 @@ -receive,Order -send,Confirm -receive,Finish diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/DoInterrupt-2@Buyer.events b/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/DoInterrupt-2@Buyer.events deleted file mode 100644 index a6b39644f..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/DoInterrupt-2@Buyer.events +++ /dev/null @@ -1,5 +0,0 @@ -send,Order -send,expire(OrderExpired) -send,OrderCancelled -receive,Ack -send,Finish diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/DoInterrupt-2@Seller.events b/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/DoInterrupt-2@Seller.events deleted file mode 100644 index 709b3dd5f..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/DoInterrupt-2@Seller.events +++ /dev/null @@ -1,5 +0,0 @@ -receive,Order -receive,expire(OrderExpired) -receive,OrderCancelled -send,Ack -receive,Finish diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/MultiPartyInteractionsAndChoice-1@Buyer.events b/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/MultiPartyInteractionsAndChoice-1@Buyer.events deleted file mode 100644 index 3ff5d4099..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/MultiPartyInteractionsAndChoice-1@Buyer.events +++ /dev/null @@ -1,3 +0,0 @@ -send,Order -receive,Confirmation - diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/MultiPartyInteractionsAndChoice-2@Buyer.events b/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/MultiPartyInteractionsAndChoice-2@Buyer.events deleted file mode 100644 index 343e507b0..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/MultiPartyInteractionsAndChoice-2@Buyer.events +++ /dev/null @@ -1,3 +0,0 @@ -send,Order -receive,OutOfStock - diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/MultiPartyInteractionsAndChoice-3@Buyer.events b/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/MultiPartyInteractionsAndChoice-3@Buyer.events deleted file mode 100644 index 9a4fe19a7..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/MultiPartyInteractionsAndChoice-3@Buyer.events +++ /dev/null @@ -1,3 +0,0 @@ -send,Order -receive,INVALID - diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/MultiPartyInteractionsAndChoice-4@Buyer.events b/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/MultiPartyInteractionsAndChoice-4@Buyer.events deleted file mode 100644 index 3ff5d4099..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/MultiPartyInteractionsAndChoice-4@Buyer.events +++ /dev/null @@ -1,3 +0,0 @@ -send,Order -receive,Confirmation - diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/MultiPartyInteractionsAndChoice2-1@Broker.events b/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/MultiPartyInteractionsAndChoice2-1@Broker.events deleted file mode 100644 index 17ad07e7b..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/MultiPartyInteractionsAndChoice2-1@Broker.events +++ /dev/null @@ -1,5 +0,0 @@ -receive,Order -send,Order -receive,Confirmation -send,Confirmation - diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/MultiPartyInteractionsAndChoice2-1@Buyer.events b/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/MultiPartyInteractionsAndChoice2-1@Buyer.events deleted file mode 100644 index 3ff5d4099..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/MultiPartyInteractionsAndChoice2-1@Buyer.events +++ /dev/null @@ -1,3 +0,0 @@ -send,Order -receive,Confirmation - diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/MultiPartyInteractionsAndChoice2-2@Broker.events b/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/MultiPartyInteractionsAndChoice2-2@Broker.events deleted file mode 100644 index 621d6ca7d..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/MultiPartyInteractionsAndChoice2-2@Broker.events +++ /dev/null @@ -1,3 +0,0 @@ -receive,Order -send,invalidProduct(InvalidProduct) - diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/MultiPartyInteractionsAndChoice2-2@Buyer.events b/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/MultiPartyInteractionsAndChoice2-2@Buyer.events deleted file mode 100644 index 3ff5d4099..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/MultiPartyInteractionsAndChoice2-2@Buyer.events +++ /dev/null @@ -1,3 +0,0 @@ -send,Order -receive,Confirmation - diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/MultiPartyInteractionsAndChoice2-3@Broker.events b/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/MultiPartyInteractionsAndChoice2-3@Broker.events deleted file mode 100644 index 17ad07e7b..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/MultiPartyInteractionsAndChoice2-3@Broker.events +++ /dev/null @@ -1,5 +0,0 @@ -receive,Order -send,Order -receive,Confirmation -send,Confirmation - diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/MultiPartyInteractionsAndChoice2-3@Buyer.events b/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/MultiPartyInteractionsAndChoice2-3@Buyer.events deleted file mode 100644 index 87adbc5e9..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/MultiPartyInteractionsAndChoice2-3@Buyer.events +++ /dev/null @@ -1,3 +0,0 @@ -send,Order -receive,ConfirmationX - diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/MultiPartyInteractionsAndChoice2-4@Buyer.events b/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/MultiPartyInteractionsAndChoice2-4@Buyer.events deleted file mode 100644 index 3ff5d4099..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/MultiPartyInteractionsAndChoice2-4@Buyer.events +++ /dev/null @@ -1,3 +0,0 @@ -send,Order -receive,Confirmation - diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/MultiPartyInteractionsAndChoice2-5@Buyer.events b/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/MultiPartyInteractionsAndChoice2-5@Buyer.events deleted file mode 100644 index f88aaa6eb..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/MultiPartyInteractionsAndChoice2-5@Buyer.events +++ /dev/null @@ -1,3 +0,0 @@ -send,Order -receive,InvalidProduct - diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/Parallel-1@Buyer.events b/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/Parallel-1@Buyer.events deleted file mode 100644 index e20d5adfd..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/Parallel-1@Buyer.events +++ /dev/null @@ -1,3 +0,0 @@ -send,M1 -send,M2 -send,M3 diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/Parallel-1@Seller.events b/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/Parallel-1@Seller.events deleted file mode 100644 index b34ac9028..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/Parallel-1@Seller.events +++ /dev/null @@ -1,3 +0,0 @@ -receive,M1 -receive,M2 -receive,M3 diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/Parallel-2@Buyer.events b/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/Parallel-2@Buyer.events deleted file mode 100644 index 7f2b44c3f..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/Parallel-2@Buyer.events +++ /dev/null @@ -1,3 +0,0 @@ -send,M2 -send,M1 -send,M3 diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/Parallel-2@Seller.events b/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/Parallel-2@Seller.events deleted file mode 100644 index 6155944fd..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/Parallel-2@Seller.events +++ /dev/null @@ -1,3 +0,0 @@ -receive,M2 -receive,M1 -receive,M3 diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/Recur-1@Buyer.events b/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/Recur-1@Buyer.events deleted file mode 100644 index 89dba2e93..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/Recur-1@Buyer.events +++ /dev/null @@ -1,7 +0,0 @@ -send,Order -receive,Rejected -send,Order -receive,Accepted -send,Another -send,Another -send,Finish diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/Recur-1@Seller.events b/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/Recur-1@Seller.events deleted file mode 100644 index d613b8a1d..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/Recur-1@Seller.events +++ /dev/null @@ -1,7 +0,0 @@ -receive,Order -send,Rejected -receive,Order -send,Accepted -receive,Another -receive,Another -receive,Finish diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/Recur-2@Buyer.events b/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/Recur-2@Buyer.events deleted file mode 100644 index f17084211..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/Recur-2@Buyer.events +++ /dev/null @@ -1,4 +0,0 @@ -send,Order -receive,Accepted -send,Another -send,Finish diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/Recur-2@Seller.events b/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/Recur-2@Seller.events deleted file mode 100644 index ad11b2ca3..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/Recur-2@Seller.events +++ /dev/null @@ -1,4 +0,0 @@ -receive,Order -send,Accepted -receive,Another -receive,Finish diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/Recur2-1@Buyer.events b/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/Recur2-1@Buyer.events deleted file mode 100644 index f27f5fd15..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/Recur2-1@Buyer.events +++ /dev/null @@ -1,5 +0,0 @@ -send,Order -send,Order -send,Another -send,Another -send,Finish diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/Recur2-1@Seller.events b/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/Recur2-1@Seller.events deleted file mode 100644 index dd55de332..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/Recur2-1@Seller.events +++ /dev/null @@ -1,5 +0,0 @@ -receive,Order -receive,Order -receive,Another -receive,Another -receive,Finish diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/Recur3-1@Buyer.events b/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/Recur3-1@Buyer.events deleted file mode 100644 index 0b4bf21e6..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/Recur3-1@Buyer.events +++ /dev/null @@ -1,7 +0,0 @@ -send,Order -receive,tryAgain() -send,Order -receive,exit() -send,Another -send,Another -send,Finish \ No newline at end of file diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/Recur3-1@Seller.events b/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/Recur3-1@Seller.events deleted file mode 100644 index a81ec1c2b..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/Recur3-1@Seller.events +++ /dev/null @@ -1,7 +0,0 @@ -receive,Order -send,tryAgain() -receive,Order -send,exit() -receive,Another -receive,Another -receive,Finish diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/Repeat-1@Buyer.events b/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/Repeat-1@Buyer.events deleted file mode 100644 index 81e6b626d..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/Repeat-1@Buyer.events +++ /dev/null @@ -1,3 +0,0 @@ -send,Order -send,Order -send,Finish diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/Repeat-1@Seller.events b/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/Repeat-1@Seller.events deleted file mode 100644 index 9a88161a5..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/Repeat-1@Seller.events +++ /dev/null @@ -1,3 +0,0 @@ -receive,Order -receive,Order -receive,Finish diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/Repeat-2@Buyer.events b/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/Repeat-2@Buyer.events deleted file mode 100644 index 72520e6b6..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/Repeat-2@Buyer.events +++ /dev/null @@ -1 +0,0 @@ -send,Finish diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/Repeat-2@Seller.events b/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/Repeat-2@Seller.events deleted file mode 100644 index 910750ffc..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/Repeat-2@Seller.events +++ /dev/null @@ -1 +0,0 @@ -receive,Finish diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/RunInlineProtocol@Buyer.events b/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/RunInlineProtocol@Buyer.events deleted file mode 100644 index 3a2c4f1dd..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/RunInlineProtocol@Buyer.events +++ /dev/null @@ -1,2 +0,0 @@ -send,Order -receive,Confirm diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/RunInlineProtocol@Seller.events b/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/RunInlineProtocol@Seller.events deleted file mode 100644 index 413d9774f..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/RunInlineProtocol@Seller.events +++ /dev/null @@ -1,2 +0,0 @@ -receive,Order -send,Confirm diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/RunSubProtocol@Buyer.events b/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/RunSubProtocol@Buyer.events deleted file mode 100644 index 3a2c4f1dd..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/RunSubProtocol@Buyer.events +++ /dev/null @@ -1,2 +0,0 @@ -send,Order -receive,Confirm diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/RunSubProtocol@Seller.events b/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/RunSubProtocol@Seller.events deleted file mode 100644 index 413d9774f..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/RunSubProtocol@Seller.events +++ /dev/null @@ -1,2 +0,0 @@ -receive,Order -send,Confirm diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/SingleInteractionXSDImport@Buyer.events b/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/SingleInteractionXSDImport@Buyer.events deleted file mode 100644 index 0dc6f5cf8..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/SingleInteractionXSDImport@Buyer.events +++ /dev/null @@ -1 +0,0 @@ -send,{http://www.acme.org/Purchasing}Order diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/SingleInteractionXSDImport@Seller.events b/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/SingleInteractionXSDImport@Seller.events deleted file mode 100644 index 9bcbc7ff5..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/SingleInteractionXSDImport@Seller.events +++ /dev/null @@ -1 +0,0 @@ -receive,{http://www.acme.org/Purchasing}Order diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/Unordered-1@Buyer.events b/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/Unordered-1@Buyer.events deleted file mode 100644 index c988c710e..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/Unordered-1@Buyer.events +++ /dev/null @@ -1,3 +0,0 @@ -send,Order -send,Cancel -send,Finish diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/Unordered-1@Seller.events b/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/Unordered-1@Seller.events deleted file mode 100644 index 0c1147073..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/Unordered-1@Seller.events +++ /dev/null @@ -1,3 +0,0 @@ -receive,Order -receive,Cancel -receive,Finish diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/Unordered-2@Buyer.events b/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/Unordered-2@Buyer.events deleted file mode 100644 index 7cafdbdb1..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/Unordered-2@Buyer.events +++ /dev/null @@ -1,3 +0,0 @@ -send,Cancel -send,Order -send,Finish diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/Unordered-2@Seller.events b/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/Unordered-2@Seller.events deleted file mode 100644 index c005dea90..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/monitor/Unordered-2@Seller.events +++ /dev/null @@ -1,3 +0,0 @@ -receive,Cancel -receive,Order -receive,Finish diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/Annotation.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/Annotation.spr deleted file mode 100644 index fc8ef0df0..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/Annotation.spr +++ /dev/null @@ -1,12 +0,0 @@ -[[ Annotation before import ]] -import Order; - -[[ Annotation before top protocol ]] -protocol SingleInteraction (role Buyer) { - - [[ Annotation before role list ]] - Buyer introduces Seller; - - [[ Annotation before interaction ]] - Order from Buyer to Seller; -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/BlockComment.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/BlockComment.spr deleted file mode 100644 index b75b2b2a8..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/BlockComment.spr +++ /dev/null @@ -1,15 +0,0 @@ -import Order; - -/* -This is the block comment. -*/ - -protocol SingleInteraction(role Buyer) { - Buyer introduces Seller; - - /* - Inner block comment. - */ - - Order from Buyer to Seller; -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/Choice.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/Choice.spr deleted file mode 100644 index 2b3def5d2..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/Choice.spr +++ /dev/null @@ -1,14 +0,0 @@ -import Order; -import Cancel; -import Invoice; - -protocol SingleInteraction(role Buyer) { - Buyer introduces Seller; - - choice at Buyer { - Order from Buyer to Seller; - Invoice from Seller to Buyer; - } or { - Cancel from Buyer to Seller; - } -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/ChoiceMerge.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/ChoiceMerge.spr deleted file mode 100644 index ee1191477..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/ChoiceMerge.spr +++ /dev/null @@ -1,21 +0,0 @@ -import Order; -import Cancel; -import Invoice; -import Cancelled; - -protocol ChoiceMerge(role Buyer) { - Buyer introduces Broker; - Broker introduces Seller; - - choice at Buyer { - Order from Buyer to Broker; - Order from Broker to Seller; - Invoice from Seller to Broker; - Invoice from Broker to Buyer; - } or { - Cancel from Buyer to Broker; - Cancel from Broker to Seller; - Cancelled from Seller to Broker; - Cancelled from Broker to Buyer; - } -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/ChoiceMergeCommonPrefix.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/ChoiceMergeCommonPrefix.spr deleted file mode 100644 index 88040b674..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/ChoiceMergeCommonPrefix.spr +++ /dev/null @@ -1,17 +0,0 @@ -import Int; -import Boolean; - -protocol ChoiceMergeCommonPrefix(role A) { - A introduces B; - B introduces C; - - choice at A { - ok() from A to B; - Int from B to C; - ok() from B to C; - } or { - quit() from A to B; - Int from B to C; - quit() from B to C; - } -} \ No newline at end of file diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/ChoiceMergeIdenticalBranches.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/ChoiceMergeIdenticalBranches.spr deleted file mode 100644 index c2536dbd7..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/ChoiceMergeIdenticalBranches.spr +++ /dev/null @@ -1,12 +0,0 @@ -protocol ChoiceMergeIdenticalBranches(role A) { - A introduces B; - B introduces C; - - choice at A { - l1() from A to B; - Int from B to C; - } or { - l2() from A to B; - Int from B to C; - } -} \ No newline at end of file diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/ChoiceMergeNested.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/ChoiceMergeNested.spr deleted file mode 100644 index c49f3271a..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/ChoiceMergeNested.spr +++ /dev/null @@ -1,27 +0,0 @@ -import M1; -import M2; -import M3; -import M4; - -protocol ChoiceMergeNested(role A) { - A introduces B, C, D; - - choice at A { - M1 from A to B; - M4 from B to C; - choice at C { - M1 from C to D; - M1 from D to A; - M3 from A to B; - } or { - M2 from C to D; - M2 from D to A; - M4 from A to B; - } - } or { - M2 from A to B; - M3 from B to A; - M3 from B to C; - M3 from B to D; - } -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/ChoiceMergeableSimple.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/ChoiceMergeableSimple.spr deleted file mode 100644 index 2e518acdc..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/ChoiceMergeableSimple.spr +++ /dev/null @@ -1,15 +0,0 @@ -protocol ChoiceNotMergeable (role A) { - A introduces B; - B introduces C; - - choice at A { - M1 from A to B; - M4 from B to C; - } or { - M2 from A to B; - M4 from B to C; - } or { - M3 from A to B; - M5 from B to C; - } -} \ No newline at end of file diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/ChoiceMergeableSimpleAllowOptional.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/ChoiceMergeableSimpleAllowOptional.spr deleted file mode 100644 index 511bddcaa..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/ChoiceMergeableSimpleAllowOptional.spr +++ /dev/null @@ -1,16 +0,0 @@ -protocol ChoiceNotMergeable (role A) { - A introduces B; - B introduces C; - - choice at A { - M1 from A to B; - M4 from B to C; - M5 from C to B; - } or { - M2 from A to B; - M4 from B to C; - } or { - M3 from A to B; - M5 from B to C; - } -} \ No newline at end of file diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/ChoiceProjection.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/ChoiceProjection.spr deleted file mode 100644 index 6ae0c2673..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/ChoiceProjection.spr +++ /dev/null @@ -1,18 +0,0 @@ -protocol ChoiceProjection(role A) { - A introduces B; - B introduces C; - - choice at A { - M1 from A to B; - M1 from B to C; - M12 from C to B; - } or { - M2 from A to B; - M2 from B to C; - choice at C { - M21 from C to B; - } or { - M22 from C to B; - } - } -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/DirectedChoice.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/DirectedChoice.spr deleted file mode 100644 index af65888b2..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/DirectedChoice.spr +++ /dev/null @@ -1,14 +0,0 @@ -import Order; -import Cancel; -import Invoice; - -protocol SingleInteraction(role Buyer) { - Buyer introduces Seller; - - from Buyer to Seller { - Order: - Invoice from Seller to Buyer; - - Cancel: - } -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/DoInterrupt.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/DoInterrupt.spr deleted file mode 100644 index abf676b33..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/DoInterrupt.spr +++ /dev/null @@ -1,23 +0,0 @@ -import Order; -import OutOfStock; -import OrderExpired, OrderCancelled; -import Confirm; -import Ack; -import Finish; - -protocol DoInterrupt(role Buyer) { - Buyer introduces Seller; - - do { - Order from Buyer to Seller; - Confirm from Seller to Buyer; - } interrupt { - OutOfStock from Seller to Buyer; - } interrupt { - expire(OrderExpired) from Buyer to Seller; - OrderCancelled from Buyer to Seller; - Ack from Seller to Buyer; - } - - Finish from Buyer to Seller; -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/ESBBroker.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/ESBBroker.spr deleted file mode 100644 index 0a3961990..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/ESBBroker.spr +++ /dev/null @@ -1,45 +0,0 @@ -import xsd "bookingReference" as BookingReference, "buy" as Buy, "cancel" as Cancel, "CreditCheckRequest" as CreditInformation, "CreditCheckInvalid" as CreditInvalid, "CreditCheckOk" as CreditValid, "enquiry" as Enquiry, "orderConfirmed" as OrderConfirmed, "orderRejected" as OrderRejected, "quote" as Quote, "quoteList" as QuoteList, "requestForQuote" as RequestForQuote; -protocol ESBBrokerProcess(role Buyer) { - Buyer introduces Broker; - - makeEnquiry(Enquiry) from Buyer to Broker; - - repeat { - run RequestForQuote(Broker) from Broker; - } - - makeEnquiry(QuoteList) from Broker to Buyer; - - choice at Buyer { - run CompleteTransaction(Buyer, Broker) from Buyer; - } or { - cancel(Cancel) from Buyer to Broker; - } - - protocol CompleteTransaction(role Buyer, role Broker) { - buy(Buy) from Buyer to Broker; - - Broker introduces CreditAgency; - - checkCredit(CreditInformation) from Broker to CreditAgency; - - choice at CreditAgency { - Broker introduces SupplierTxnProcessor; - - checkCredit(CreditValid) from CreditAgency to Broker; - confirm(OrderConfirmed) from Broker to SupplierTxnProcessor; - confirm(BookingReference) from SupplierTxnProcessor to Broker; - buy(BookingReference) from Broker to Buyer; - } or { - checkCredit(CreditInvalid) from CreditAgency to Broker; - buy(OrderRejected) from Broker to Buyer; - } - } - - protocol RequestForQuote(role Broker) { - Broker introduces SupplierQuoteEngine; - - getQuote(RequestForQuote) from Broker to SupplierQuoteEngine; - getQuote(Quote) from SupplierQuoteEngine to Broker; - } -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/ESBBrokerWithAnnotations.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/ESBBrokerWithAnnotations.spr deleted file mode 100644 index abae89895..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/ESBBrokerWithAnnotations.spr +++ /dev/null @@ -1,96 +0,0 @@ -[[ XSDElement ]] -import xsd "bookingReference" as BookingReference, "buy" as Buy, "cancel" as Cancel, "CreditCheckRequest" as CreditInformation, "CreditCheckInvalid" as CreditInvalid, "CreditCheckOk" as CreditValid, "enquiry" as Enquiry, "orderConfirmed" as OrderConfirmed, "orderRejected" as OrderRejected, "quote" as Quote, "quoteList" as QuoteList, "requestForQuote" as RequestForQuote; -[[ SourceComponent(id=//@choreographies.0) ]] -[[ Namespace(name=http://www.pi4soa.org/ESBBroker/Broker,role=Broker) ]] -[[ Namespace(name=http://www.pi4soa.org/ESBBroker/Buyer,role=Buyer) ]] -[[ Namespace(name=http://www.pi4soa.org/ESBBroker/CreditAgency,role=CreditAgency) ]] -[[ Namespace(name=http://www.pi4soa.org/ESBBroker/Supplier,role=Supplier) ]] -[[ Type(prefix=tns,namespace=http://www.pi4soa.org/ESBBroker) ]] -[[ Type(prefix=xsd,namespace=http://www.w3.org/2001/XMLSchema) ]] -[[ Type(prefix=brk,namespace=http://www.pi4soa.org/ESBBroker/Broker) ]] -[[ Type(prefix=byr,namespace=http://www.pi4soa.org/ESBBroker/Buyer) ]] -[[ Type(prefix=cay,namespace=http://www.pi4soa.org/ESBBroker/CreditAgency) ]] -[[ Type(prefix=spr,namespace=http://www.pi4soa.org/ESBBroker/Supplier) ]] -[[ Namespace(name=http://www.pi4soa.org/ESBBroker/Supplier,role=SupplierTxnProcessor) ]] -[[ Namespace(name=http://www.pi4soa.org/ESBBroker/Supplier,role=SupplierQuoteEngine) ]] -protocol ESBBrokerProcess(role Buyer) { - Buyer introduces Broker, CreditAgency, Supplier; - [[ SourceComponent(id=//@choreographies.0/@activities.0/@exchangeDetails.0) ]] - [[ Interface(name={http://www.pi4soa.org/ESBBroker/Broker}BrokerBehavior) ]] - [[ Correlation(request=makeEnquiry) ]] - makeEnquiry(Enquiry) from Buyer to Broker; - [[ SourceComponent(id=//@choreographies.0/@activities.1) ]] - repeat { - [[ SourceComponent(id=//@choreographies.0/@activities.1/@activities.0) ]] - run RequestForQuote(Broker) from Broker; - } - [[ SourceComponent(id=//@choreographies.0/@activities.2/@activities.0/@exchangeDetails.0) ]] - [[ Interface(name={http://www.pi4soa.org/ESBBroker/Broker}BrokerBehavior) ]] - [[ Correlation(replyTo=makeEnquiry) ]] - makeEnquiry(QuoteList) from Broker to Buyer; - [[ SourceComponent(id=//@choreographies.0/@activities.3) ]] - choice at Buyer { - [[ SourceComponent(id=//@choreographies.0/@activities.3/@activities.0/@activities.0) ]] - run CompleteTransaction(Buyer, Broker, CreditAgency) from Buyer; - } or { - [[ SourceComponent(id=//@choreographies.0/@activities.3/@activities.1/@activities.0/@exchangeDetails.0) ]] - [[ Interface(name={http://www.pi4soa.org/ESBBroker/Broker}BrokerBehavior) ]] - cancel(Cancel) from Buyer to Broker; - } - [[ SourceComponent(id=//@choreographies.0/@enclosedChoreographies.0) ]] - [[ Namespace(name=http://www.pi4soa.org/ESBBroker/Supplier,role=SupplierTxnProcessor) ]] - protocol CompleteTransaction(role Buyer, role Broker, role CreditAgency) { - [[ SourceComponent(id=//@choreographies.0/@enclosedChoreographies.0/@activities.0/@exchangeDetails.0) ]] - [[ Interface(name={http://www.pi4soa.org/ESBBroker/Broker}BrokerBehavior) ]] - [[ Correlation(request=buy) ]] - buy(Buy) from Buyer to Broker; - [[ SourceComponent(id=//@choreographies.0/@enclosedChoreographies.0/@activities.1/@exchangeDetails.0) ]] - [[ Interface(name={http://www.pi4soa.org/ESBBroker/CreditAgency}CreditAgencyBehavior) ]] - [[ Correlation(request=checkCredit) ]] - checkCredit(CreditInformation) from Broker to CreditAgency; - [[ SourceComponent(id=//@choreographies.0/@enclosedChoreographies.0/@activities.2) ]] - choice at CreditAgency { - Broker introduces SupplierTxnProcessor; - [[ SourceComponent(id=//@choreographies.0/@enclosedChoreographies.0/@activities.2/@activities.0/@activities.0/@exchangeDetails.0) ]] - [[ Interface(name={http://www.pi4soa.org/ESBBroker/CreditAgency}CreditAgencyBehavior) ]] - [[ Correlation(replyTo=checkCredit) ]] - checkCredit(CreditValid) from CreditAgency to Broker; - [[ SourceComponent(id=//@choreographies.0/@enclosedChoreographies.0/@activities.2/@activities.0/@activities.1/@exchangeDetails.0) ]] - [[ Interface(name={http://www.pi4soa.org/ESBBroker/Supplier}SupplierBehavior) ]] - [[ Correlation(request=confirm) ]] - confirm(OrderConfirmed) from Broker to SupplierTxnProcessor; - [[ SourceComponent(id=//@choreographies.0/@enclosedChoreographies.0/@activities.2/@activities.0/@activities.1/@exchangeDetails.1) ]] - [[ Interface(name={http://www.pi4soa.org/ESBBroker/Supplier}SupplierBehavior) ]] - [[ Correlation(replyTo=confirm) ]] - confirm(BookingReference) from SupplierTxnProcessor to Broker; - [[ SourceComponent(id=//@choreographies.0/@enclosedChoreographies.0/@activities.2/@activities.0/@activities.2/@exchangeDetails.0) ]] - [[ Interface(name={http://www.pi4soa.org/ESBBroker/Broker}BrokerBehavior) ]] - [[ Correlation(replyTo=buy) ]] - buy(BookingReference) from Broker to Buyer; - } or { - [[ SourceComponent(id=//@choreographies.0/@enclosedChoreographies.0/@activities.2/@activities.1/@activities.0/@exchangeDetails.0) ]] - [[ Fault(name=invalidCredit) ]] - [[ Interface(name={http://www.pi4soa.org/ESBBroker/CreditAgency}CreditAgencyBehavior) ]] - [[ Correlation(replyTo=checkCredit) ]] - checkCredit(CreditInvalid) from CreditAgency to Broker; - [[ SourceComponent(id=//@choreographies.0/@enclosedChoreographies.0/@activities.2/@activities.1/@activities.1/@exchangeDetails.0) ]] - [[ Fault(name=rejected) ]] - [[ Interface(name={http://www.pi4soa.org/ESBBroker/Broker}BrokerBehavior) ]] - [[ Correlation(replyTo=buy) ]] - buy(OrderRejected) from Broker to Buyer; - } - } - [[ SourceComponent(id=//@choreographies.0/@enclosedChoreographies.1) ]] - [[ Namespace(name=http://www.pi4soa.org/ESBBroker/Supplier,role=SupplierQuoteEngine) ]] - protocol RequestForQuote(role Broker) { - Broker introduces SupplierQuoteEngine; - [[ SourceComponent(id=//@choreographies.0/@enclosedChoreographies.1/@activities.0/@exchangeDetails.0) ]] - [[ Interface(name={http://www.pi4soa.org/ESBBroker/Supplier}SupplierBehavior) ]] - [[ Correlation(request=getQuote) ]] - getQuote(RequestForQuote) from Broker to SupplierQuoteEngine; - [[ SourceComponent(id=//@choreographies.0/@enclosedChoreographies.1/@activities.0/@exchangeDetails.1) ]] - [[ Interface(name={http://www.pi4soa.org/ESBBroker/Supplier}SupplierBehavior) ]] - [[ Correlation(replyTo=getQuote) ]] - getQuote(Quote) from SupplierQuoteEngine to Broker; - } -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/End.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/End.spr deleted file mode 100644 index 7e2879a48..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/End.spr +++ /dev/null @@ -1,16 +0,0 @@ -import Order; -import Cancel; -import Invoice; - -protocol EndExample(role Buyer) { - Buyer introduces Seller; - - choice at Buyer { - Order from Buyer to Seller; - } or { - Cancel from Buyer to Seller; - end; - } - - Invoice from Seller to Buyer; -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/InlineProtocol.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/InlineProtocol.spr deleted file mode 100644 index ccaf70027..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/InlineProtocol.spr +++ /dev/null @@ -1,8 +0,0 @@ -import Order; -import protocol Sub from "ReferencedExternalProtocol.spr"; - -protocol InlineProtocol(role Buyer) { - Buyer introduces Seller; - - inline Sub(Buyer, Seller); -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/LineComment.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/LineComment.spr deleted file mode 100644 index 455fb5611..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/LineComment.spr +++ /dev/null @@ -1,9 +0,0 @@ -import Order; - -// The protocol definition -protocol SingleInteraction(role Buyer) { - Buyer introduces Seller; - - // Send the order from the buyer to the seller - Order from Buyer to Seller; -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/MultiPartyInteractionsAndChoice.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/MultiPartyInteractionsAndChoice.spr deleted file mode 100644 index ca856b956..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/MultiPartyInteractionsAndChoice.spr +++ /dev/null @@ -1,34 +0,0 @@ -import Order; -import CreditCheck; -import CreditOk; -import Confirmation; -import OutOfStock; -import InsufficientCredit; - -protocol MultiPartyInteractionsAndChoice(role Buyer) { - Buyer introduces Broker; - Broker introduces CreditAgency; - - Order from Buyer to Broker; - - CreditCheck from Broker to CreditAgency; - - choice at CreditAgency { - CreditOk from CreditAgency to Broker; - - Broker introduces Seller; - - Order from Broker to Seller; - - choice at Seller { - Confirmation from Seller to Broker; - Confirmation from Broker to Buyer; - } or { - OutOfStock from Seller to Broker; - OutOfStock from Broker to Buyer; - } - } or { - InsufficientCredit from CreditAgency to Broker; - InsufficientCredit from Broker to Buyer; - } -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/MultiPartyInteractionsAndChoice2.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/MultiPartyInteractionsAndChoice2.spr deleted file mode 100644 index 53ed9693e..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/MultiPartyInteractionsAndChoice2.spr +++ /dev/null @@ -1,26 +0,0 @@ -import Order; -import Confirmation; -import OutOfStock; -import InvalidProduct; - -protocol MultiPartyInteractionsAndChoice2(role Buyer) { - Buyer introduces Broker; - - Order from Buyer to Broker; - - choice at Broker { - Broker introduces Seller; - - Order from Broker to Seller; - - choice at Seller { - Confirmation from Seller to Broker; - Confirmation from Broker to Buyer; - } or { - OutOfStock from Seller to Broker; - OutOfStock from Broker to Buyer; - } - } or { - invalidProduct(InvalidProduct) from Broker to Buyer; - } -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/MulticastInteraction.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/MulticastInteraction.spr deleted file mode 100644 index b247c703a..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/MulticastInteraction.spr +++ /dev/null @@ -1,7 +0,0 @@ -import Order; - -protocol MulticastInteraction(role Buyer) { - Buyer introduces SellerA, SellerB; - - Order from Buyer to SellerA,SellerB; -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/Parallel.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/Parallel.spr deleted file mode 100644 index 492508359..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/Parallel.spr +++ /dev/null @@ -1,15 +0,0 @@ -import M1; -import M2; -import M3; - -protocol Parallel(role Buyer) { - Buyer introduces Seller; - - parallel { - M1 from Buyer to Seller; - } and { - M2 from Buyer to Seller; - } - - M3 from Buyer to Seller; -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/PurchaseGoods3.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/PurchaseGoods3.spr deleted file mode 100644 index af930ea1e..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/PurchaseGoods3.spr +++ /dev/null @@ -1,25 +0,0 @@ -import xsd "{http://www.jboss.org/examples/store}AccountNotFound" as AccountNotFound, "{http://www.jboss.org/examples/store}BuyConfirmed" as BuyConfirmed, "{http://www.jboss.org/examples/store}BuyFailed" as BuyFailed, "{http://www.jboss.org/examples/store}BuyRequest" as BuyRequest from "http://www.jboss.org/examples/store"; -import xsd "{http://www.jboss.org/examples/creditAgency}CreditCheckRequest" as CreditCheckRequest, "{http://www.jboss.org/examples/creditAgency}CreditRating" as CreditRating, "{http://www.jboss.org/examples/creditAgency}CustomerUnknown" as CustomerUnknown from "http://www.jboss.org/examples/creditAgency"; -import xsd "{http://www.jboss.org/examples/logistics}DeliveryConfirmed" as DeliveryConfirmed, "{http://www.jboss.org/examples/logistics}DeliveryRequest" as DeliveryRequest from "http://www.jboss.org/examples/logistics"; -import xsd "{http://www.w3.org/2001/XMLSchema}string" as IDType, "{http://www.w3.org/2001/XMLSchema}anyURI" as URITokenType from "http://www.w3.org/2001/XMLSchema"; -protocol PurchaseGoodsProcess (role Buyer) { - Buyer introduces Store; - Store introduces CreditAgency; - - buy(BuyRequest) from Buyer to Store; - checkCredit(CreditCheckRequest) from Store to CreditAgency; - choice at CreditAgency { - checkCredit(CreditRating) from CreditAgency to Store; - choice at Store { - Store introduces Logistics; - deliver(DeliveryRequest) from Store to Logistics; - deliver(DeliveryConfirmed) from Logistics to Store; - buy(BuyConfirmed) from Store to Buyer; - } or { - buy(BuyFailed) from Store to Buyer; - } - } or { - checkCredit(CustomerUnknown) from CreditAgency to Store; - buy(AccountNotFound) from Store to Buyer; - } -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/Recur.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/Recur.spr deleted file mode 100644 index 54519108d..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/Recur.spr +++ /dev/null @@ -1,24 +0,0 @@ -import Order; -import Finish; -import Rejected; -import Accepted; -import Another; - -protocol Recur (role Buyer) { - Buyer introduces Seller; - - rec Transaction { - Order from Buyer to Seller; - - choice at Seller { - tryAgain(Rejected) from Seller to Buyer; - Transaction; - } or { - exit(Accepted) from Seller to Buyer; - } - - Another from Buyer to Seller; - } - - Finish from Buyer to Seller; -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/Recur2.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/Recur2.spr deleted file mode 100644 index 9e81219f0..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/Recur2.spr +++ /dev/null @@ -1,22 +0,0 @@ -import Order; -import Finish; -import Rejected; -import Accepted; -import Another; - -protocol Recur (role Buyer) { - Buyer introduces Seller; - - rec Transaction { - Order from Buyer to Seller; - - choice at Seller { - Transaction; - } or { - } - - Another from Buyer to Seller; - } - - Finish from Buyer to Seller; -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/Recur3.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/Recur3.spr deleted file mode 100644 index 2e58be0ef..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/Recur3.spr +++ /dev/null @@ -1,24 +0,0 @@ -import Order; -import Finish; -import Rejected; -import Accepted; -import Another; - -protocol Recur (role Buyer) { - Buyer introduces Seller; - - rec Transaction { - Order from Buyer to Seller; - - choice at Seller { - tryAgain() from Seller to Buyer; - Transaction; - } or { - exit() from Seller to Buyer; - } - - Another from Buyer to Seller; - } - - Finish from Buyer to Seller; -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/ReferencedExternalProtocol.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/ReferencedExternalProtocol.spr deleted file mode 100644 index 44bac0972..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/ReferencedExternalProtocol.spr +++ /dev/null @@ -1,6 +0,0 @@ -import Order; -import Confirm; - -protocol Sub(role SubBuyer, role SubSeller) { - Order from SubBuyer to SubSeller; -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/Repeat.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/Repeat.spr deleted file mode 100644 index 133ef1301..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/Repeat.spr +++ /dev/null @@ -1,12 +0,0 @@ -import Order; -import Finish; - -protocol Repeat (role Buyer) { - Buyer introduces Seller; - - repeat at Buyer { - Order from Buyer to Seller; - } - - Finish from Buyer to Seller; -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/Repeat2.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/Repeat2.spr deleted file mode 100644 index 1afd5b103..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/Repeat2.spr +++ /dev/null @@ -1,14 +0,0 @@ -protocol Repeat2 (role Buyer) { - Buyer introduces Store; - - buy(BuyRequest) from Buyer to Store; - - repeat { - Store introduces CreditAgency; - - checkCredit(CreditCheckRequest) from Store to CreditAgency; - checkCredit(CreditRating) from CreditAgency to Store; - } - - buy(BuyConfirmed) from Store to Buyer; -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/RunExternalProtocol.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/RunExternalProtocol.spr deleted file mode 100644 index 99e8a5549..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/RunExternalProtocol.spr +++ /dev/null @@ -1,11 +0,0 @@ -import Order; -import Confirm; -import protocol Sub from "ReferencedExternalProtocol.spr"; - -protocol RunSubProtocol (role Buyer) { - Buyer introduces Seller; - - run Sub(Buyer, Seller) from Buyer; - - Confirm from Seller to Buyer; -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/RunSubProtocol.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/RunSubProtocol.spr deleted file mode 100644 index 0fae2d6c1..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/RunSubProtocol.spr +++ /dev/null @@ -1,10 +0,0 @@ -import Order; -import Confirm; -protocol RunSubProtocol(role Buyer) { - Buyer introduces Seller; - run Sub(Buyer, Seller) from Buyer; - Confirm from Seller to Buyer; - protocol Sub(role SubBuyer, role SubSeller) { - Order from SubBuyer to SubSeller; - } -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/SingleInteraction.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/SingleInteraction.spr deleted file mode 100644 index 3679bf7dc..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/SingleInteraction.spr +++ /dev/null @@ -1,7 +0,0 @@ -import Order; - -protocol SingleInteraction (role Buyer) { - Buyer introduces Seller; - - Order from Buyer to Seller; -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/SingleInteractionRPC.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/SingleInteractionRPC.spr deleted file mode 100644 index 164753200..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/SingleInteractionRPC.spr +++ /dev/null @@ -1,8 +0,0 @@ -import Order; -import Customer; - -protocol SingleInteractionRPC(role Buyer) { - Buyer introduces Seller; - - submit(Order,Customer) from Buyer to Seller; -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/SingleInteractionXSDImport.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/SingleInteractionXSDImport.spr deleted file mode 100644 index 67f1a2387..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/SingleInteractionXSDImport.spr +++ /dev/null @@ -1,13 +0,0 @@ -import xml "{http://www.acme.org/Purchasing}Order" as Order, - "{http://www.acme.org/Purchasing}Quote" as Quote - from "../schema/MySchema.xsd"; - -import java "Order" as Order, - "Quote" as Quote - from "org.scribble"; - -protocol SingleInteraction(role Buyer) { - Buyer introduces Seller; - - Order from Buyer to Seller; -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/Unordered.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/Unordered.spr deleted file mode 100644 index a4aa70e9a..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/Unordered.spr +++ /dev/null @@ -1,14 +0,0 @@ -import Order; -import Cancel; -import Finish; - -protocol Unordered(role Buyer) { - Buyer introduces Seller; - - unordered { - Order from Buyer to Seller; - Cancel from Buyer to Seller; - } - - Finish from Buyer to Seller; -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/testcase/SCRIBBLE-125.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/testcase/SCRIBBLE-125.spr deleted file mode 100644 index 243146ebe..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/testcase/SCRIBBLE-125.spr +++ /dev/null @@ -1,11 +0,0 @@ -protocol Example(role A, role B, role C) { - rec X { - from A to B { - Label1: - M2 from B to A; - Label2: - M3 from B to A; - X; - } - } -} \ No newline at end of file diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/testcase/SCRIBBLE-126.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/testcase/SCRIBBLE-126.spr deleted file mode 100644 index bc5df6401..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/testcase/SCRIBBLE-126.spr +++ /dev/null @@ -1,9 +0,0 @@ -protocol Example(role A, role B, role C) { - from A to B { - Label1: - M1 from B to C; - M2 from B to A; - Label2: - M3 from B to A; - } -} \ No newline at end of file diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/witherrors/ChoiceNotMergeableRecursion.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/witherrors/ChoiceNotMergeableRecursion.spr deleted file mode 100644 index fc89e18eb..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/witherrors/ChoiceNotMergeableRecursion.spr +++ /dev/null @@ -1,18 +0,0 @@ -protocol ChoiceNotMergeableRecursion (role A) { - A introduces B; - B introduces C; - - // Not mergable, as the projection at C would result in ambiguity, as - // to whether the received l0() message should trigger the recursion or not. - - rec X { - choice at A { - l1() from A to B; - l0() from B to C; - X; - } or { - l2() from A to B; - l0() from B to C; - } - } -} \ No newline at end of file diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/witherrors/ChoiceNotMergeableSimple.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/witherrors/ChoiceNotMergeableSimple.spr deleted file mode 100644 index 511bddcaa..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/witherrors/ChoiceNotMergeableSimple.spr +++ /dev/null @@ -1,16 +0,0 @@ -protocol ChoiceNotMergeable (role A) { - A introduces B; - B introduces C; - - choice at A { - M1 from A to B; - M4 from B to C; - M5 from C to B; - } or { - M2 from A to B; - M4 from B to C; - } or { - M3 from A to B; - M5 from B to C; - } -} \ No newline at end of file diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/witherrors/ChoiceNotMergeableSimple2.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/witherrors/ChoiceNotMergeableSimple2.spr deleted file mode 100644 index 4ab840a68..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/witherrors/ChoiceNotMergeableSimple2.spr +++ /dev/null @@ -1,13 +0,0 @@ -protocol ChoiceNotMergeable (role A) { - A introduces B; - B introduces C; - - choice at A { - M1 from A to B; - M1 from B to C; - M2 from B to C; - } or { - M2 from A to B; - M1 from B to C; - } -} \ No newline at end of file diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/witherrors/DirectedChoiceNotMergeableRecursion.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/witherrors/DirectedChoiceNotMergeableRecursion.spr deleted file mode 100644 index da61c6a58..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/witherrors/DirectedChoiceNotMergeableRecursion.spr +++ /dev/null @@ -1,18 +0,0 @@ -protocol ChoiceNotMergeableRecursion (role A) { - A introduces B; - B introduces C; - - // Not mergable, as the projection at C would result in ambiguity, as - // to whether the received l0() message should trigger the recursion or not. - - rec X { - choice from A to B { - l1(): - l0() from B to C; - X; - - l2(): - l0() from B to C; - } - } -} \ No newline at end of file diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/witherrors/DirectedChoiceNotMergeableSimple.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/witherrors/DirectedChoiceNotMergeableSimple.spr deleted file mode 100644 index 1af624117..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/global/witherrors/DirectedChoiceNotMergeableSimple.spr +++ /dev/null @@ -1,13 +0,0 @@ -protocol ChoiceNotMergeable (role A) { - A introduces B; - B introduces C; - - choice from A to B { - l1(): - l1() from B to C; - l1() from B to C; - - l2(): - l2() from B to C; - } -} \ No newline at end of file diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/Annotation@Buyer.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/Annotation@Buyer.spr deleted file mode 100644 index 1c7d1761f..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/Annotation@Buyer.spr +++ /dev/null @@ -1,12 +0,0 @@ -[[ Annotation before import ]] -import Order; - -[[ Annotation before top protocol ]] -protocol SingleInteraction at Buyer { - - [[ Annotation before role list ]] - Buyer introduces Seller; - - [[ Annotation before interaction ]] - Order to Seller; -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/Annotation@Seller.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/Annotation@Seller.spr deleted file mode 100644 index 45e93c68e..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/Annotation@Seller.spr +++ /dev/null @@ -1,9 +0,0 @@ -[[ Annotation before import ]] -import Order; - -[[ Annotation before top protocol ]] -protocol SingleInteraction at Seller(role Buyer) { - - [[ Annotation before interaction ]] - Order from Buyer; -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/Choice@Buyer.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/Choice@Buyer.spr deleted file mode 100644 index f9eee362b..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/Choice@Buyer.spr +++ /dev/null @@ -1,14 +0,0 @@ -import Order; -import Cancel; -import Invoice; - -protocol SingleInteraction at Buyer { - Buyer introduces Seller; - - choice at Buyer { - Order to Seller; - Invoice from Seller; - } or { - Cancel to Seller; - } -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/Choice@Seller.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/Choice@Seller.spr deleted file mode 100644 index 73d23d1d4..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/Choice@Seller.spr +++ /dev/null @@ -1,13 +0,0 @@ -import Order; -import Cancel; -import Invoice; - -protocol SingleInteraction at Seller (role Buyer) { - - choice { - Order from Buyer; - Invoice to Buyer; - } or { - Cancel from Buyer; - } -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/ChoiceMerge@Broker.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/ChoiceMerge@Broker.spr deleted file mode 100644 index e1126a4d8..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/ChoiceMerge@Broker.spr +++ /dev/null @@ -1,20 +0,0 @@ -import Order; -import Cancel; -import Invoice; -import Cancelled; - -protocol ChoiceMerge at Broker (role Buyer) { - Broker introduces Seller; - - choice { - Order from Buyer; - Order to Seller; - Invoice from Seller; - Invoice to Buyer; - } or { - Cancel from Buyer; - Cancel to Seller; - Cancelled from Seller; - Cancelled to Buyer; - } -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/ChoiceMerge@Seller.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/ChoiceMerge@Seller.spr deleted file mode 100644 index 635cd0b80..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/ChoiceMerge@Seller.spr +++ /dev/null @@ -1,15 +0,0 @@ -import Order; -import Cancel; -import Invoice; -import Cancelled; - -protocol ChoiceMerge at Seller (role Broker) { - - choice { - Order from Broker; - Invoice to Broker; - } or { - Cancel from Broker; - Cancelled to Broker; - } -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/ChoiceMergeCommonPrefix@A.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/ChoiceMergeCommonPrefix@A.spr deleted file mode 100644 index 4922d10a3..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/ChoiceMergeCommonPrefix@A.spr +++ /dev/null @@ -1,12 +0,0 @@ -import Int; -import Boolean; - -protocol ChoiceMergeCommonPrefix at A { - A introduces B; - - choice at A { - ok() to B; - } or { - quit() to B; - } -} \ No newline at end of file diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/ChoiceMergeCommonPrefix@B.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/ChoiceMergeCommonPrefix@B.spr deleted file mode 100644 index dcde1d1d4..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/ChoiceMergeCommonPrefix@B.spr +++ /dev/null @@ -1,16 +0,0 @@ -import Int; -import Boolean; - -protocol ChoiceMergeCommonPrefix at B(role A) { - B introduces C; - - choice { - ok() from A; - Int to C; - ok() to C; - } or { - quit() from A; - Int to C; - quit() to C; - } -} \ No newline at end of file diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/ChoiceMergeCommonPrefix@C.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/ChoiceMergeCommonPrefix@C.spr deleted file mode 100644 index 5c8d07d13..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/ChoiceMergeCommonPrefix@C.spr +++ /dev/null @@ -1,11 +0,0 @@ -import Int; -import Boolean; - -protocol ChoiceMergeCommonPrefix at C (role B) { - Int from B; - choice { - ok() from B; - } or { - quit() from B; - } -} \ No newline at end of file diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/ChoiceMergeIdenticalBranches@A.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/ChoiceMergeIdenticalBranches@A.spr deleted file mode 100644 index 238f805bf..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/ChoiceMergeIdenticalBranches@A.spr +++ /dev/null @@ -1,9 +0,0 @@ -protocol ChoiceMergeIdenticalBranches at A { - A introduces B; - - choice at A { - l1() to B; - } or { - l2() to B; - } -} \ No newline at end of file diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/ChoiceMergeIdenticalBranches@B.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/ChoiceMergeIdenticalBranches@B.spr deleted file mode 100644 index ee944f18b..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/ChoiceMergeIdenticalBranches@B.spr +++ /dev/null @@ -1,11 +0,0 @@ -protocol ChoiceMergeIdenticalBranches at B(role A) { - B introduces C; - - choice { - l1() from A; - Int to C; - } or { - l2() from A; - Int to C; - } -} \ No newline at end of file diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/ChoiceMergeIdenticalBranches@C.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/ChoiceMergeIdenticalBranches@C.spr deleted file mode 100644 index d079a78ae..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/ChoiceMergeIdenticalBranches@C.spr +++ /dev/null @@ -1,3 +0,0 @@ -protocol ChoiceMergeIdenticalBranches at C(role B) { - Int from B; -} \ No newline at end of file diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/ChoiceMergeNested@A.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/ChoiceMergeNested@A.spr deleted file mode 100644 index 20a13fbc6..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/ChoiceMergeNested@A.spr +++ /dev/null @@ -1,22 +0,0 @@ -import M1; -import M2; -import M3; -import M4; - -protocol ChoiceMergeNested at A { - A introduces B, D; - - choice at A { - M1 to B; - choice { - M1 from D; - M3 to B; - } or { - M2 from D; - M4 to B; - } - } or { - M2 to B; - M3 from B; - } -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/ChoiceMergeNested@B.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/ChoiceMergeNested@B.spr deleted file mode 100644 index 6a8998968..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/ChoiceMergeNested@B.spr +++ /dev/null @@ -1,22 +0,0 @@ -import M1; -import M2; -import M3; -import M4; - -protocol ChoiceMergeNested at B (role A, role C){ - - choice { - M1 from A; - M4 to C; - choice { - M3 from A; - } or { - M4 from A; - } - } or { - M2 from A; - M3 to A; - M3 to C; - M3 to D; - } -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/ChoiceMergeNested@C.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/ChoiceMergeNested@C.spr deleted file mode 100644 index 229c98820..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/ChoiceMergeNested@C.spr +++ /dev/null @@ -1,18 +0,0 @@ -import M1; -import M2; -import M3; -import M4; - -protocol ChoiceMergeNested at C(role A) { - - choice { - M4 from B; - choice at C { - M1 to D; - } or { - M2 to D; - } - } or { - M3 from B; - } -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/ChoiceMergeNested@D.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/ChoiceMergeNested@D.spr deleted file mode 100644 index ead148fa5..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/ChoiceMergeNested@D.spr +++ /dev/null @@ -1,16 +0,0 @@ -import M1; -import M2; -import M3; -import M4; - -protocol ChoiceMergeNested at D (role A) { - role A, C; - - choice from C { - M1: - M1 to A; - M2: - M2 to A; - M3: - } -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/ChoiceMergeableSimple@C.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/ChoiceMergeableSimple@C.spr deleted file mode 100644 index e149bfdb4..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/ChoiceMergeableSimple@C.spr +++ /dev/null @@ -1,8 +0,0 @@ -protocol ChoiceNotMergeable at C (role B) { - - choice { - M4 from B; - } or { - M5 from B; - } -} \ No newline at end of file diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/ChoiceMergeableSimpleAllowOptional@C.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/ChoiceMergeableSimpleAllowOptional@C.spr deleted file mode 100644 index d78a1e228..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/ChoiceMergeableSimpleAllowOptional@C.spr +++ /dev/null @@ -1,12 +0,0 @@ -protocol ChoiceNotMergeable at C (role B) { - - choice { - M4 from B; - choice { - M5 to B; - } or { - } - } or { - M5 from B; - } -} \ No newline at end of file diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/ChoiceProjection@C.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/ChoiceProjection@C.spr deleted file mode 100644 index 5126378e0..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/ChoiceProjection@C.spr +++ /dev/null @@ -1,13 +0,0 @@ -protocol ChoiceProjection at C (role B) { - choice { - M1 from B; - M12 to B; - } or { - M2 from B; - choice at C { - M21 to B; - } or { - M22 to B; - } - } -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/DirectedChoice@Buyer.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/DirectedChoice@Buyer.spr deleted file mode 100644 index d5a57c157..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/DirectedChoice@Buyer.spr +++ /dev/null @@ -1,14 +0,0 @@ -import Order; -import Cancel; -import Invoice; - -protocol SingleInteraction at Buyer { - Buyer introduces Seller; - - to Seller { - Order: - Invoice from Seller; - - Cancel: - } -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/DirectedChoice@Seller.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/DirectedChoice@Seller.spr deleted file mode 100644 index e07274d54..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/DirectedChoice@Seller.spr +++ /dev/null @@ -1,13 +0,0 @@ -import Order; -import Cancel; -import Invoice; - -protocol SingleInteraction at Seller (role Buyer) { - - from Buyer { - Order: - Invoice to Buyer; - - Cancel: - } -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/DoInterrupt@Buyer.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/DoInterrupt@Buyer.spr deleted file mode 100644 index 22ded664b..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/DoInterrupt@Buyer.spr +++ /dev/null @@ -1,23 +0,0 @@ -import Order; -import OutOfStock; -import OrderExpired, OrderCancelled; -import Confirm; -import Ack; -import Finish; - -protocol DoInterrupt at Buyer { - Buyer introduces Seller; - - do { - Order to Seller; - Confirm from Seller; - } interrupt { - OutOfStock from Seller; - } interrupt { - expire(OrderExpired) to Seller; - OrderCancelled to Seller; - Ack from Seller; - } - - Finish to Seller; -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/DoInterrupt@Seller.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/DoInterrupt@Seller.spr deleted file mode 100644 index 7b1aa3b98..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/DoInterrupt@Seller.spr +++ /dev/null @@ -1,22 +0,0 @@ -import Order; -import OutOfStock; -import OrderExpired, OrderCancelled; -import Confirm; -import Ack; -import Finish; - -protocol DoInterrupt at Seller (role Buyer) { - - do { - Order from Buyer; - Confirm to Buyer; - } interrupt { - OutOfStock to Buyer; - } interrupt { - expire(OrderExpired) from Buyer; - OrderCancelled from Buyer; - Ack to Buyer; - } - - Finish from Buyer; -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/ESBBroker@Broker.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/ESBBroker@Broker.spr deleted file mode 100644 index 9bdb533f9..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/ESBBroker@Broker.spr +++ /dev/null @@ -1,44 +0,0 @@ -import xsd "bookingReference" as BookingReference, "buy" as Buy, "cancel" as Cancel, "CreditCheckRequest" as CreditInformation, "CreditCheckInvalid" as CreditInvalid, "CreditCheckOk" as CreditValid, "enquiry" as Enquiry, "orderConfirmed" as OrderConfirmed, "orderRejected" as OrderRejected, "quote" as Quote, "quoteList" as QuoteList, "requestForQuote" as RequestForQuote; -protocol ESBBrokerProcess at Broker(role Buyer) { - - makeEnquiry(Enquiry) from Buyer; - - repeat { - run RequestForQuote at Broker from Broker; - } - - makeEnquiry(QuoteList) to Buyer; - - choice { - run CompleteTransaction at Broker(Buyer) from Buyer; - } or { - cancel(Cancel) from Buyer; - } - - protocol CompleteTransaction at Broker(role Buyer) { - buy(Buy) from Buyer; - - Broker introduces CreditAgency; - - checkCredit(CreditInformation) to CreditAgency; - - choice { - Broker introduces SupplierTxnProcessor; - - checkCredit(CreditValid) from CreditAgency; - confirm(OrderConfirmed) to SupplierTxnProcessor; - confirm(BookingReference) from SupplierTxnProcessor; - buy(BookingReference) to Buyer; - } or { - checkCredit(CreditInvalid) from CreditAgency; - buy(OrderRejected) to Buyer; - } - } - - protocol RequestForQuote at Broker { - Broker introduces SupplierQuoteEngine; - - getQuote(RequestForQuote) to SupplierQuoteEngine; - getQuote(Quote) from SupplierQuoteEngine; - } -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/ESBBroker@CreditAgency.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/ESBBroker@CreditAgency.spr deleted file mode 100644 index 7780e0491..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/ESBBroker@CreditAgency.spr +++ /dev/null @@ -1,10 +0,0 @@ -import xsd "bookingReference" as BookingReference, "buy" as Buy, "cancel" as Cancel, "CreditCheckRequest" as CreditInformation, "CreditCheckInvalid" as CreditInvalid, "CreditCheckOk" as CreditValid, "enquiry" as Enquiry, "orderConfirmed" as OrderConfirmed, "orderRejected" as OrderRejected, "quote" as Quote, "quoteList" as QuoteList, "requestForQuote" as RequestForQuote; -protocol ESBBrokerProcess at CreditAgency(role Broker) { - checkCredit(CreditInformation) from Broker; - - choice at CreditAgency { - checkCredit(CreditValid) to Broker; - } or { - checkCredit(CreditInvalid) to Broker; - } -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/ESBBroker@SupplierTxnProcessor.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/ESBBroker@SupplierTxnProcessor.spr deleted file mode 100644 index 5aea128f8..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/ESBBroker@SupplierTxnProcessor.spr +++ /dev/null @@ -1,7 +0,0 @@ -import xsd "bookingReference" as BookingReference, "buy" as Buy, "cancel" as Cancel, "CreditCheckRequest" as CreditInformation, "CreditCheckInvalid" as CreditInvalid, "CreditCheckOk" as CreditValid, "enquiry" as Enquiry, "orderConfirmed" as OrderConfirmed, "orderRejected" as OrderRejected, "quote" as Quote, "quoteList" as QuoteList, "requestForQuote" as RequestForQuote; -protocol ESBBrokerProcess at SupplierTxnProcessor { - Broker introduces SupplierTxnProcessor; - - confirm(OrderConfirmed) from Broker; - confirm(BookingReference) to Broker; -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/End@Buyer.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/End@Buyer.spr deleted file mode 100644 index 5aed51b44..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/End@Buyer.spr +++ /dev/null @@ -1,16 +0,0 @@ -import Order; -import Cancel; -import Invoice; - -protocol EndExample at Buyer { - Buyer introduces Seller; - - choice at Buyer { - Order to Seller; - } or { - Cancel to Seller; - end; - } - - Invoice from Seller; -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/End@Seller.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/End@Seller.spr deleted file mode 100644 index 119c085a4..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/End@Seller.spr +++ /dev/null @@ -1,15 +0,0 @@ -import Order; -import Cancel; -import Invoice; - -protocol EndExample at Seller (role Buyer) { - - choice { - Order from Buyer; - } or { - Cancel from Buyer; - end; - } - - Invoice to Buyer; -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/InlineProtocol@Buyer.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/InlineProtocol@Buyer.spr deleted file mode 100644 index aebc6c03f..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/InlineProtocol@Buyer.spr +++ /dev/null @@ -1,8 +0,0 @@ -import Order; -import protocol Sub from "ReferencedExternalProtocol.spr"; - -protocol InlineProtocol at Buyer { - Buyer introduces Seller; - - inline Sub at SubBuyer(Seller); -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/InlineProtocol@Seller.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/InlineProtocol@Seller.spr deleted file mode 100644 index 30d2e2b6e..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/InlineProtocol@Seller.spr +++ /dev/null @@ -1,6 +0,0 @@ -import Order; -import protocol Sub from "ReferencedExternalProtocol.spr"; - -protocol InlineProtocol at Seller (role Buyer) { - inline Sub at SubSeller(Buyer); -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/MultiPartyInteractionsAndChoice2@Broker.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/MultiPartyInteractionsAndChoice2@Broker.spr deleted file mode 100644 index a6c43f578..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/MultiPartyInteractionsAndChoice2@Broker.spr +++ /dev/null @@ -1,24 +0,0 @@ -import Order; -import Confirmation; -import OutOfStock; -import InvalidProduct; - -protocol MultiPartyInteractionsAndChoice2 at Broker(role Buyer) { - Order from Buyer; - - choice at Broker { - Broker introduces Seller; - - Order to Seller; - - choice { - Confirmation from Seller; - Confirmation to Buyer; - } or { - OutOfStock from Seller; - OutOfStock to Buyer; - } - } or { - invalidProduct(InvalidProduct) to Buyer; - } -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/MultiPartyInteractionsAndChoice2@Buyer.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/MultiPartyInteractionsAndChoice2@Buyer.spr deleted file mode 100644 index f69e4017c..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/MultiPartyInteractionsAndChoice2@Buyer.spr +++ /dev/null @@ -1,18 +0,0 @@ -import Order; -import Confirmation; -import OutOfStock; -import InvalidProduct; - -protocol MultiPartyInteractionsAndChoice2 at Buyer { - Buyer introduces Broker; - - Order to Broker; - - choice { - Confirmation from Broker; - } or { - OutOfStock from Broker; - } or { - invalidProduct(InvalidProduct) from Broker; - } -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/MultiPartyInteractionsAndChoice2@Seller.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/MultiPartyInteractionsAndChoice2@Seller.spr deleted file mode 100644 index c23bbfddb..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/MultiPartyInteractionsAndChoice2@Seller.spr +++ /dev/null @@ -1,14 +0,0 @@ -import Order; -import Confirmation; -import OutOfStock; -import InvalidProduct; - -protocol MultiPartyInteractionsAndChoice2 at Seller (role Broker) { - Order from Broker; - - choice at Seller { - Confirmation to Broker; - } or { - OutOfStock to Broker; - } -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/MultiPartyInteractionsAndChoice@Broker.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/MultiPartyInteractionsAndChoice@Broker.spr deleted file mode 100644 index a727b36dc..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/MultiPartyInteractionsAndChoice@Broker.spr +++ /dev/null @@ -1,33 +0,0 @@ -import Order; -import CreditCheck; -import CreditOk; -import Confirmation; -import OutOfStock; -import InsufficientCredit; - -protocol MultiPartyInteractionsAndChoice at Broker(role Buyer) { - Broker introduces CreditAgency; - - Order from Buyer; - - CreditCheck to CreditAgency; - - choice { - CreditOk from CreditAgency; - - Broker introduces Seller; - - Order to Seller; - - choice { - Confirmation from Seller; - Confirmation to Buyer; - } or { - OutOfStock from Seller; - OutOfStock to Buyer; - } - } or { - InsufficientCredit from CreditAgency; - InsufficientCredit to Buyer; - } -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/MultiPartyInteractionsAndChoice@Buyer.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/MultiPartyInteractionsAndChoice@Buyer.spr deleted file mode 100644 index fb0187d3b..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/MultiPartyInteractionsAndChoice@Buyer.spr +++ /dev/null @@ -1,20 +0,0 @@ -import Order; -import CreditCheck; -import CreditOk; -import Confirmation; -import OutOfStock; -import InsufficientCredit; - -protocol MultiPartyInteractionsAndChoice at Buyer { - Buyer introduces Broker; - - Order to Broker; - - choice { - Confirmation from Broker; - } or { - OutOfStock from Broker; - } or { - InsufficientCredit from Broker; - } -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/MultiPartyInteractionsAndChoice@CreditAgency.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/MultiPartyInteractionsAndChoice@CreditAgency.spr deleted file mode 100644 index fed0fd8e5..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/MultiPartyInteractionsAndChoice@CreditAgency.spr +++ /dev/null @@ -1,17 +0,0 @@ -import Order; -import CreditCheck; -import CreditOk; -import Confirmation; -import OutOfStock; -import InsufficientCredit; - -protocol MultiPartyInteractionsAndChoice at CreditAgency(role Broker) { - - CreditCheck from Broker; - - choice at CreditAgency { - CreditOk to Broker; - } or { - InsufficientCredit to Broker; - } -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/MultiPartyInteractionsAndChoice@Seller.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/MultiPartyInteractionsAndChoice@Seller.spr deleted file mode 100644 index f51028802..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/MultiPartyInteractionsAndChoice@Seller.spr +++ /dev/null @@ -1,16 +0,0 @@ -import Order; -import CreditCheck; -import CreditOk; -import Confirmation; -import OutOfStock; -import InsufficientCredit; - -protocol MultiPartyInteractionsAndChoice at Seller (role Broker) { - Order from Broker; - - choice at Seller { - Confirmation to Broker; - } or { - OutOfStock to Broker; - } -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/MulticastInteraction@Buyer.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/MulticastInteraction@Buyer.spr deleted file mode 100644 index 41f5e1452..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/MulticastInteraction@Buyer.spr +++ /dev/null @@ -1,7 +0,0 @@ -import Order; - -protocol MulticastInteraction at Buyer { - Buyer introduces SellerA, SellerB; - - Order to SellerA,SellerB; -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/MulticastInteraction@SellerA.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/MulticastInteraction@SellerA.spr deleted file mode 100644 index d3802a729..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/MulticastInteraction@SellerA.spr +++ /dev/null @@ -1,5 +0,0 @@ -import Order; - -protocol MulticastInteraction at SellerA (role Buyer) { - Order from Buyer; -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/Parallel@Buyer.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/Parallel@Buyer.spr deleted file mode 100644 index f4026397c..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/Parallel@Buyer.spr +++ /dev/null @@ -1,15 +0,0 @@ -import M1; -import M2; -import M3; - -protocol Parallel at Buyer { - Buyer introduces Seller; - - parallel { - M1 to Seller; - } and { - M2 to Seller; - } - - M3 to Seller; -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/Parallel@Seller.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/Parallel@Seller.spr deleted file mode 100644 index c5fd3dc22..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/Parallel@Seller.spr +++ /dev/null @@ -1,14 +0,0 @@ -import M1; -import M2; -import M3; - -protocol Parallel at Seller(role Buyer) { - - parallel { - M1 from Buyer; - } and { - M2 from Buyer; - } - - M3 from Buyer; -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/PurchaseGoods3@Buyer.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/PurchaseGoods3@Buyer.spr deleted file mode 100644 index f34670142..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/PurchaseGoods3@Buyer.spr +++ /dev/null @@ -1,18 +0,0 @@ -import xsd "{http://www.jboss.org/examples/store}AccountNotFound" as AccountNotFound, "{http://www.jboss.org/examples/store}BuyConfirmed" as BuyConfirmed, "{http://www.jboss.org/examples/store}BuyFailed" as BuyFailed, "{http://www.jboss.org/examples/store}BuyRequest" as BuyRequest from "http://www.jboss.org/examples/store"; -import xsd "{http://www.jboss.org/examples/creditAgency}CreditCheckRequest" as CreditCheckRequest, "{http://www.jboss.org/examples/creditAgency}CreditRating" as CreditRating, "{http://www.jboss.org/examples/creditAgency}CustomerUnknown" as CustomerUnknown from "http://www.jboss.org/examples/creditAgency"; -import xsd "{http://www.jboss.org/examples/logistics}DeliveryConfirmed" as DeliveryConfirmed, "{http://www.jboss.org/examples/logistics}DeliveryRequest" as DeliveryRequest from "http://www.jboss.org/examples/logistics"; -import xsd "{http://www.w3.org/2001/XMLSchema}string" as IDType, "{http://www.w3.org/2001/XMLSchema}anyURI" as URITokenType from "http://www.w3.org/2001/XMLSchema"; -protocol PurchaseGoodsProcess at Buyer { - Buyer introduces Store; - - buy(BuyRequest) to Store; - - choice { - buy(BuyConfirmed) from Store; - } or { - buy(BuyFailed) from Store; - } or { - buy(AccountNotFound) from Store; - - } -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/PurchaseGoods3@Logistics.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/PurchaseGoods3@Logistics.spr deleted file mode 100644 index fa7cb7753..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/PurchaseGoods3@Logistics.spr +++ /dev/null @@ -1,8 +0,0 @@ -import xsd "{http://www.jboss.org/examples/store}AccountNotFound" as AccountNotFound, "{http://www.jboss.org/examples/store}BuyConfirmed" as BuyConfirmed, "{http://www.jboss.org/examples/store}BuyFailed" as BuyFailed, "{http://www.jboss.org/examples/store}BuyRequest" as BuyRequest from "http://www.jboss.org/examples/store"; -import xsd "{http://www.jboss.org/examples/creditAgency}CreditCheckRequest" as CreditCheckRequest, "{http://www.jboss.org/examples/creditAgency}CreditRating" as CreditRating, "{http://www.jboss.org/examples/creditAgency}CustomerUnknown" as CustomerUnknown from "http://www.jboss.org/examples/creditAgency"; -import xsd "{http://www.jboss.org/examples/logistics}DeliveryConfirmed" as DeliveryConfirmed, "{http://www.jboss.org/examples/logistics}DeliveryRequest" as DeliveryRequest from "http://www.jboss.org/examples/logistics"; -import xsd "{http://www.w3.org/2001/XMLSchema}string" as IDType, "{http://www.w3.org/2001/XMLSchema}anyURI" as URITokenType from "http://www.w3.org/2001/XMLSchema"; -protocol PurchaseGoodsProcess at Logistics (role Store) { - deliver(DeliveryRequest) from Store; - deliver(DeliveryConfirmed) to Store; -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/PurchaseGoods3@Store.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/PurchaseGoods3@Store.spr deleted file mode 100644 index cc9b87639..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/PurchaseGoods3@Store.spr +++ /dev/null @@ -1,27 +0,0 @@ -import xsd "{http://www.jboss.org/examples/store}AccountNotFound" as AccountNotFound, "{http://www.jboss.org/examples/store}BuyConfirmed" as BuyConfirmed, "{http://www.jboss.org/examples/store}BuyFailed" as BuyFailed, "{http://www.jboss.org/examples/store}BuyRequest" as BuyRequest from "http://www.jboss.org/examples/store"; -import xsd "{http://www.jboss.org/examples/creditAgency}CreditCheckRequest" as CreditCheckRequest, "{http://www.jboss.org/examples/creditAgency}CreditRating" as CreditRating, "{http://www.jboss.org/examples/creditAgency}CustomerUnknown" as CustomerUnknown from "http://www.jboss.org/examples/creditAgency"; -import xsd "{http://www.jboss.org/examples/logistics}DeliveryConfirmed" as DeliveryConfirmed, "{http://www.jboss.org/examples/logistics}DeliveryRequest" as DeliveryRequest from "http://www.jboss.org/examples/logistics"; -import xsd "{http://www.w3.org/2001/XMLSchema}string" as IDType, "{http://www.w3.org/2001/XMLSchema}anyURI" as URITokenType from "http://www.w3.org/2001/XMLSchema"; -protocol PurchaseGoodsProcess at Store (role Buyer) { - Store introduces CreditAgency; - - buy(BuyRequest) from Buyer; - - checkCredit(CreditCheckRequest) to CreditAgency; - - choice { - checkCredit(CreditRating) from CreditAgency; - - choice at Store { - Store introduces Logistics; - deliver(DeliveryRequest) to Logistics; - deliver(DeliveryConfirmed) from Logistics; - buy(BuyConfirmed) to Buyer; - } or { - buy(BuyFailed) to Buyer; - } - } or { - checkCredit(CustomerUnknown) from CreditAgency; - buy(AccountNotFound) to Buyer; - } -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/Recur2@Buyer.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/Recur2@Buyer.spr deleted file mode 100644 index 6d9d0f103..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/Recur2@Buyer.spr +++ /dev/null @@ -1,22 +0,0 @@ -import Order; -import Finish; -import Rejected; -import Accepted; -import Another; - -protocol Recur at Buyer { - Buyer introduces Seller; - - rec Transaction { - Order to Seller; - - choice { - Transaction; - } or { - } - - Another to Seller; - } - - Finish to Seller; -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/Recur2@Seller.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/Recur2@Seller.spr deleted file mode 100644 index b5fee336a..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/Recur2@Seller.spr +++ /dev/null @@ -1,21 +0,0 @@ -import Order; -import Finish; -import Rejected; -import Accepted; -import Another; - -protocol Recur at Seller (role Buyer) { - - rec Transaction { - Order from Buyer; - - choice at Seller { - Transaction; - } or { - } - - Another from Buyer; - } - - Finish from Buyer; -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/Recur3@Buyer.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/Recur3@Buyer.spr deleted file mode 100644 index 1b9bf62db..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/Recur3@Buyer.spr +++ /dev/null @@ -1,24 +0,0 @@ -import Order; -import Finish; -import Rejected; -import Accepted; -import Another; - -protocol Recur at Buyer { - Buyer introduces Seller; - - rec Transaction { - Order to Seller; - - choice { - tryAgain() from Seller; - Transaction; - } or { - exit() from Seller; - } - - Another to Seller; - } - - Finish to Seller; -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/Recur3@Seller.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/Recur3@Seller.spr deleted file mode 100644 index 54ec253ab..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/Recur3@Seller.spr +++ /dev/null @@ -1,24 +0,0 @@ -import Order; -import Finish; -import Rejected; -import Accepted; -import Another; - -protocol Recur at Seller { - Buyer introduces Seller; - - rec Transaction { - Order from Buyer; - - choice at Seller { - tryAgain() to Buyer; - Transaction; - } or { - exit() to Buyer; - } - - Another from Buyer; - } - - Finish from Buyer; -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/Recur@Buyer.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/Recur@Buyer.spr deleted file mode 100644 index 668f11b48..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/Recur@Buyer.spr +++ /dev/null @@ -1,24 +0,0 @@ -import Order; -import Finish; -import Rejected; -import Accepted; -import Another; - -protocol Recur at Buyer { - Buyer introduces Seller; - - rec Transaction { - Order to Seller; - - choice { - tryAgain(Rejected) from Seller; - Transaction; - } or { - exit(Accepted) from Seller; - } - - Another to Seller; - } - - Finish to Seller; -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/Recur@Seller.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/Recur@Seller.spr deleted file mode 100644 index c31c04cf9..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/Recur@Seller.spr +++ /dev/null @@ -1,23 +0,0 @@ -import Order; -import Finish; -import Rejected; -import Accepted; -import Another; - -protocol Recur at Seller (role Buyer) { - - rec Transaction { - Order from Buyer; - - choice at Seller { - tryAgain(Rejected) to Buyer; - Transaction; - } or { - exit(Accepted) to Buyer; - } - - Another from Buyer; - } - - Finish from Buyer; -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/Repeat2@Buyer.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/Repeat2@Buyer.spr deleted file mode 100644 index 8973bbefd..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/Repeat2@Buyer.spr +++ /dev/null @@ -1,7 +0,0 @@ -protocol Repeat2 at Buyer{ - Buyer introduces Store; - - buy(BuyRequest) to Store; - - buy(BuyConfirmed) from Store; -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/Repeat2@CreditAgency.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/Repeat2@CreditAgency.spr deleted file mode 100644 index 27c776ee4..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/Repeat2@CreditAgency.spr +++ /dev/null @@ -1,4 +0,0 @@ -protocol Repeat2 at CreditAgency (role Store) { - checkCredit(CreditCheckRequest) from Store; - checkCredit(CreditRating) to Store; -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/Repeat@Buyer.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/Repeat@Buyer.spr deleted file mode 100644 index 2a58cd2a9..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/Repeat@Buyer.spr +++ /dev/null @@ -1,12 +0,0 @@ -import Order; -import Finish; - -protocol Repeat at Buyer { - Buyer introduces Seller; - - repeat at Buyer { - Order to Seller; - } - - Finish to Seller; -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/Repeat@Seller.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/Repeat@Seller.spr deleted file mode 100644 index 61680db47..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/Repeat@Seller.spr +++ /dev/null @@ -1,11 +0,0 @@ -import Order; -import Finish; - -protocol Repeat at Seller (role Buyer) { - - repeat at Buyer { - Order from Buyer; - } - - Finish from Buyer; -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/RunExternalProtocol@Buyer.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/RunExternalProtocol@Buyer.spr deleted file mode 100644 index 4cc650c2a..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/RunExternalProtocol@Buyer.spr +++ /dev/null @@ -1,11 +0,0 @@ -import Order; -import Confirm; -import protocol Sub from "ReferencedExternalProtocol.spr"; - -protocol RunSubProtocol at Buyer { - Buyer introduces Seller; - - run Sub at SubBuyer(Seller) from Buyer; - - Confirm from Seller; -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/RunExternalProtocol@Seller.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/RunExternalProtocol@Seller.spr deleted file mode 100644 index 39b771675..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/RunExternalProtocol@Seller.spr +++ /dev/null @@ -1,9 +0,0 @@ -import Order; -import Confirm; -import protocol Sub from "ReferencedExternalProtocol.spr"; - -protocol RunSubProtocol at Seller (role Buyer) { - run Sub at SubSeller(Buyer) from Buyer; - - Confirm to Buyer; -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/RunSubProtocol@Buyer.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/RunSubProtocol@Buyer.spr deleted file mode 100644 index a958fdd1c..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/RunSubProtocol@Buyer.spr +++ /dev/null @@ -1,14 +0,0 @@ -import Order; -import Confirm; - -protocol RunSubProtocol at Buyer { - Buyer introduces Seller; - - run Sub at SubBuyer(Seller) from Buyer; - - Confirm from Seller; - - protocol Sub at SubBuyer(role SubSeller) { - Order to SubSeller; - } -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/RunSubProtocol@Seller.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/RunSubProtocol@Seller.spr deleted file mode 100644 index 73f589589..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/RunSubProtocol@Seller.spr +++ /dev/null @@ -1,13 +0,0 @@ -import Order; -import Confirm; - -protocol RunSubProtocol at Seller (role Buyer) { - - run Sub at SubSeller(Buyer) from Buyer; - - Confirm to Buyer; - - protocol Sub at SubSeller(role SubBuyer) { - Order from SubBuyer; - } -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/SingleInteraction@Buyer.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/SingleInteraction@Buyer.spr deleted file mode 100644 index e2fefe4b4..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/SingleInteraction@Buyer.spr +++ /dev/null @@ -1,7 +0,0 @@ -import Order; - -protocol SingleInteraction at Buyer { - Buyer introduces Seller; - - Order to Seller; -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/SingleInteraction@Seller.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/SingleInteraction@Seller.spr deleted file mode 100644 index 8636036ae..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/SingleInteraction@Seller.spr +++ /dev/null @@ -1,5 +0,0 @@ -import Order; - -protocol SingleInteraction at Seller (role Buyer) { - Order from Buyer; -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/SingleInteractionXSDImport@Buyer.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/SingleInteractionXSDImport@Buyer.spr deleted file mode 100644 index 57aed3f10..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/SingleInteractionXSDImport@Buyer.spr +++ /dev/null @@ -1,13 +0,0 @@ -import xml "{http://www.acme.org/Purchasing}Order" as Order, - "{http://www.acme.org/Purchasing}Quote" as Quote - from "../schema/MySchema.xsd"; - -import java "Order" as Order, - "Quote" as Quote - from "org.scribble"; - -protocol SingleInteraction at Buyer { - Buyer introduces Seller; - - Order to Seller; -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/SingleInteractionXSDImport@Seller.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/SingleInteractionXSDImport@Seller.spr deleted file mode 100644 index 15e8869de..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/SingleInteractionXSDImport@Seller.spr +++ /dev/null @@ -1,11 +0,0 @@ -import xml "{http://www.acme.org/Purchasing}Order" as Order, - "{http://www.acme.org/Purchasing}Quote" as Quote - from "../schema/MySchema.xsd"; - -import java "Order" as Order, - "Quote" as Quote - from "org.scribble"; - -protocol SingleInteraction at Seller (role Buyer) { - Order from Buyer; -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/Unordered@Buyer.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/Unordered@Buyer.spr deleted file mode 100644 index b11bb3717..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/Unordered@Buyer.spr +++ /dev/null @@ -1,14 +0,0 @@ -import Order; -import Cancel; -import Finish; - -protocol Unordered at Buyer { - Buyer introduces Seller; - - unordered { - Order to Seller; - Cancel to Seller; - } - - Finish to Seller; -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/Unordered@Seller.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/Unordered@Seller.spr deleted file mode 100644 index 5cdf758c0..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/Unordered@Seller.spr +++ /dev/null @@ -1,13 +0,0 @@ -import Order; -import Cancel; -import Finish; - -protocol Unordered at Seller (role Buyer) { - - unordered { - Order from Buyer; - Cancel from Buyer; - } - - Finish from Buyer; -} diff --git a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/testcase/SCRIBBLE-125@C.spr b/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/testcase/SCRIBBLE-125@C.spr deleted file mode 100644 index c9fa6ecd2..000000000 --- a/qa/org.scribble.protocol.ctk/src/test/resources/tests/protocol/local/testcase/SCRIBBLE-125@C.spr +++ /dev/null @@ -1,2 +0,0 @@ -protocol Example at C (role A, role B) { -} \ No newline at end of file diff --git a/qa/pom.xml b/qa/pom.xml deleted file mode 100644 index a5bc4ebdf..000000000 --- a/qa/pom.xml +++ /dev/null @@ -1,38 +0,0 @@ - - 4.0.0 - org.scribble - qa - pom - 2.1.0-SNAPSHOT - Scribble::QA - - - org.scribble - parent - 2.1.0-SNAPSHOT - - - - - qa - - org.scribble.protocol.ctk - - - - - - - - org.apache.maven.plugins - maven-deploy-plugin - - true - - - - - - diff --git a/scribble-ast/pom.xml b/scribble-ast/pom.xml new file mode 100644 index 000000000..30b214f24 --- /dev/null +++ b/scribble-ast/pom.xml @@ -0,0 +1,26 @@ + + + 4.0.0 + + + scribble-ast + jar + + + + org.scribble + scribble-core + + + + + org.scribble + parent + 0.5.1-SNAPSHOT + + + + scribble-ast + + diff --git a/scribble-ast/src/main/java/org/scribble/ast/AstFactory.java b/scribble-ast/src/main/java/org/scribble/ast/AstFactory.java new file mode 100644 index 000000000..9507be715 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/AstFactory.java @@ -0,0 +1,259 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast; + +import java.util.List; + +import org.antlr.runtime.Token; +import org.scribble.ast.global.GChoice; +import org.scribble.ast.global.GConnect; +import org.scribble.ast.global.GContinue; +import org.scribble.ast.global.GDelegPayElem; +import org.scribble.ast.global.GDisconnect; +import org.scribble.ast.global.GDo; +import org.scribble.ast.global.GInteractionSeq; +import org.scribble.ast.global.GMsgTransfer; +import org.scribble.ast.global.GProtoBlock; +import org.scribble.ast.global.GProtoDecl; +import org.scribble.ast.global.GProtoDef; +import org.scribble.ast.global.GProtoHeader; +import org.scribble.ast.global.GRecursion; +import org.scribble.ast.global.GSessionNode; +import org.scribble.ast.global.GWrap; +import org.scribble.ast.local.LAcc; +import org.scribble.ast.local.LChoice; +import org.scribble.ast.local.LClientWrap; +import org.scribble.ast.local.LContinue; +import org.scribble.ast.local.LDisconnect; +import org.scribble.ast.local.LDo; +import org.scribble.ast.local.LInteractionSeq; +import org.scribble.ast.local.LProjectionDecl; +import org.scribble.ast.local.LProtoBlock; +import org.scribble.ast.local.LProtoDef; +import org.scribble.ast.local.LProtoHeader; +import org.scribble.ast.local.LRecursion; +import org.scribble.ast.local.LRecv; +import org.scribble.ast.local.LReq; +import org.scribble.ast.local.LSelfDecl; +import org.scribble.ast.local.LSend; +import org.scribble.ast.local.LServerWrap; +import org.scribble.ast.local.LSessionNode; +import org.scribble.ast.name.PayElemNameNode; +import org.scribble.ast.name.qualified.DataNameNode; +import org.scribble.ast.name.qualified.GProtoNameNode; +import org.scribble.ast.name.qualified.LProtoNameNode; +import org.scribble.ast.name.qualified.ModuleNameNode; +import org.scribble.ast.name.qualified.SigNameNode; +import org.scribble.ast.name.simple.AmbigNameNode; +import org.scribble.ast.name.simple.DataParamNode; +import org.scribble.ast.name.simple.ExtIdNode; +import org.scribble.ast.name.simple.IdNode; +import org.scribble.ast.name.simple.OpNode; +import org.scribble.ast.name.simple.RecVarNode; +import org.scribble.ast.name.simple.RoleNode; +import org.scribble.ast.name.simple.SigParamNode; +import org.scribble.core.type.kind.NonRoleParamKind; +import org.scribble.core.type.kind.PayElemKind; + + +// Pass null as Token t to create a fresh Token +// AstFactory is for making "fresh" nodes ("fresh" Tokens) with new dels -- cf. ScribNode reconstruct pattern (for Token and del preservation) +// Implementations located in scribble-parser, use ScribbleParser for Token construction +// Currently, used only in relatively niche places (since ANTLR now constructs all parsed nodes "directly") +public interface AstFactory +{ + IdNode IdNode(Token t, String text); + ExtIdNode ExtIdNode(Token t, String text); + + AmbigNameNode AmbigNameNode(Token t, String text); // Deprecate? Never need to make ambigname "manually" via af? (constructed only by ScribbleParser) + DataParamNode DataParamNode(Token t, String text); + OpNode OpNode(Token t, String text); + RecVarNode RecVarNode(Token t, String text); + RoleNode RoleNode(Token t, String text); + SigParamNode SigParamNode(Token t, String text); + + DataNameNode DataNameNode(Token t, List elems); + GProtoNameNode GProtoNameNode(Token t, List elems); + LProtoNameNode LProtoNameNode(Token t, List elems); + ModuleNameNode ModuleNameNode(Token t, List elems); + SigNameNode SigNameNode(Token t, List elems); + + Module Module(Token t, ModuleDecl mdecl, + List> imports, + List> nonprotos, + List> protos); + + ModuleDecl ModuleDecl(Token t, ModuleNameNode fullname); + ImportModule ImportModule(Token t, ModuleNameNode modname, + ModuleNameNode alias); // alias == null for no alias (child not added) + + DataDecl DataDecl(Token t, IdNode schema, ExtIdNode extName, + ExtIdNode extSource, DataNameNode name); + SigDecl SigDecl(Token t, IdNode schema, ExtIdNode extName, + ExtIdNode extSource, SigNameNode name); + GProtoDecl GProtoDecl(Token t, ProtoModList mods, GProtoHeader header, + GProtoDef def); + + // TODO: refactor to use ProtoModList, etc. + ProtoModList ProtoModList(Token t, List mods); + AuxMod AuxMod(Token t); + ExplicitMod ExplicitMod(Token t); + + GProtoHeader GProtocolHeader(Token t, GProtoNameNode name, RoleDeclList rs, + NonRoleParamDeclList ps); + RoleDeclList RoleDeclList(Token t, List ds); + RoleDecl RoleDecl(Token t, RoleNode r); + NonRoleParamDeclList NonRoleParamDeclList(Token t, + List> ds); + DataParamDecl DataParamDecl(Token t, DataParamNode p); + SigParamDecl SigParamDecl(Token t, SigParamNode p); + + GProtoDef GProtoDef(Token t, GProtoBlock block); + GProtoBlock GProtoBlock(Token t, GInteractionSeq seq); + GInteractionSeq GInteractionSeq(Token t, List elems); // CHECKME: ? extends GSessionNode ? -- and similar others? + + SigLitNode SigLitNode(Token t, OpNode op, PayElemList pay); + PayElemList PayElemList(Token t, List> elems); + UnaryPayElem UnaryPayElem(Token t, + PayElemNameNode name); + GDelegPayElem GDelegPayElem(Token t, GProtoNameNode name, RoleNode r); + + GMsgTransfer GMsgTransfer(Token t, RoleNode src, MsgNode msg, + List dsts); + GConnect GConnect(Token t, RoleNode src, MsgNode msg, RoleNode dst); + GDisconnect GDisconnect(Token t, RoleNode left, RoleNode right); + GWrap GWrap(Token t, RoleNode client, RoleNode server); + + GContinue GContinue(Token t, RecVarNode rv); + GDo GDo(Token t, GProtoNameNode proto, NonRoleArgList args, RoleArgList rs); + + RoleArgList RoleArgList(Token t, List rs); + RoleArg RoleArg(Token t, RoleNode r); + NonRoleArgList NonRoleArgList(Token t, List args); + NonRoleArg NonRoleArg(Token t, NonRoleArgNode arg); + + GChoice GChoice(Token t, RoleNode subj, List blocks); + GRecursion GRecursion(Token t, RecVarNode rv, GProtoBlock block); + + /*LProtoDecl LProtoDecl(Token t, ProtoModList mods, + LProtoHeader header, LProtoDef def); // Not currently used -- local protos not yet parsed, only projected*/ + + LProjectionDecl LProjectionDecl(Token t, ProtoModList mods, + LProtoHeader header, LProtoDef def, GProtoNameNode fullname, + RoleNode self); // del extends that of LProtoDecl + + LProtoHeader LProtoHeader(Token t, LProtoNameNode name, RoleDeclList rs, + NonRoleParamDeclList ps); + LSelfDecl LSelfDecl(Token t, RoleNode r); + + LProtoDef LProtoDef(Token t, LProtoBlock block); + LProtoBlock LProtoBlock(Token t, LInteractionSeq seq); + LInteractionSeq LInteractionSeq(Token t, List elems); + + // Following take "self" param in case of parsed Token (not actually supported yet) + LSend LSend(Token t, RoleNode self, MsgNode msg, RoleNode dst); + LRecv LRecv(Token t, RoleNode src, MsgNode msg, RoleNode self); + LAcc LAcc(Token t, RoleNode src, MsgNode msg, RoleNode self); + LReq LReq(Token t, RoleNode self, MsgNode msg, RoleNode dst); + LDisconnect LDisconnect(Token t, RoleNode self, RoleNode peer); + LClientWrap LClientWrap(Token t, RoleNode client, RoleNode server); + LServerWrap LServerWrap(Token t, RoleNode client, RoleNode server); + + LContinue LContinue(Token t, RecVarNode rv); + LDo LDo(Token t, LProtoNameNode proto, NonRoleArgList as, RoleArgList rs); + + LChoice LChoice(Token t, RoleNode subj, List blocks); + LRecursion LRecursion(Token t, RecVarNode rv, LProtoBlock block); +} + + + + + + + + + + + + + + + + + + + + + + + +/* + DummyProjectionRoleNode DummyProjectionRoleNode(); + + LDelegationElem LDelegationElem(CommonTree source, LProtocolNameNode name); + + LProtocolDecl LProtocolDecl(CommonTree source, List modifiers, + LProtocolHeader header, LProtocolDef def); + // Not currently used -- local protos not parsed, only projected + + LProjectionDecl LProjectionDecl(CommonTree source, + List modifiers, GProtocolName fullname, Role self, + LProtocolHeader header, LProtocolDef def); + // del extends that of LProtocolDecl + + LProtocolHeader LProtocolHeader(CommonTree source, LProtocolNameNode name, + RoleDeclList roledecls, NonRoleParamDeclList paramdecls); + + SelfRoleDecl SelfRoleDecl(CommonTree source, RoleNode namenode); + + LProtocolDef LProtocolDef(CommonTree source, LProtocolBlock block); + + LProtocolBlock LProtocolBlock(CommonTree source, LInteractionSeq seq); + + LInteractionSeq LInteractionSeq(CommonTree source, + List actions); + + LSend LSend(CommonTree source, RoleNode src, MessageNode msg, + List dests); + + LRecv LReceive(CommonTree source, RoleNode src, MessageNode msg, + List dests); + + LRequest LRequest(CommonTree source, RoleNode src, MessageNode msg, + RoleNode dest); + + LAccept LAccept(CommonTree source, RoleNode src, MessageNode msg, + RoleNode dest); + + /*LConnect LConnect(CommonTree source, RoleNode src, RoleNode dest); + LAccept LAccept(CommonTree source, RoleNode src, RoleNode dest);* / + + LDisconnect LDisconnect(CommonTree source, RoleNode self, RoleNode peer); + + LWrapClient LWrapClient(CommonTree source, RoleNode self, RoleNode peer); + + LWrapServer LWrapServer(CommonTree source, RoleNode self, RoleNode peer); + + LChoice LChoice(CommonTree source, RoleNode subj, + List blocks); + + LRecursion LRecursion(CommonTree source, RecVarNode recvar, + LProtocolBlock block); + + LContinue LContinue(CommonTree source, RecVarNode recvar); + + LDo LDo(CommonTree source, RoleArgList roles, NonRoleArgList args, + LProtocolNameNode proto); +*/ diff --git a/scribble-ast/src/main/java/org/scribble/ast/AuxMod.java b/scribble-ast/src/main/java/org/scribble/ast/AuxMod.java new file mode 100644 index 000000000..53fac4bb5 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/AuxMod.java @@ -0,0 +1,65 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast; + +import org.antlr.runtime.Token; +import org.scribble.del.DelFactory; + +public class AuxMod extends ProtoModNode +{ + // ScribTreeAdaptor#create constructor + public AuxMod(Token t) + { + super(t); + } + + // Tree#dupNode constructor + protected AuxMod(AuxMod node) + { + super(node); + } + + @Override + public AuxMod dupNode() + { + return new AuxMod(this); // return this also OK, since no children + } + + @Override + public void decorateDel(DelFactory df) + { + df.AuxMod(this); + } + + @Override + public boolean isAux() + { + return true; + } + + @Override + public String toString() + { + return "aux"; + } + + + + + + + + + public static final AuxMod AUX = new AuxMod((Token) null); +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/BasicInteraction.java b/scribble-ast/src/main/java/org/scribble/ast/BasicInteraction.java new file mode 100644 index 000000000..a205e8f77 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/BasicInteraction.java @@ -0,0 +1,34 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast; + +import org.antlr.runtime.Token; +import org.scribble.core.type.kind.ProtoKind; + +public abstract class BasicInteraction + extends SimpleSessionNode +{ + // ScribTreeAdaptor#create constructor + public BasicInteraction(Token t) + { + super(t); + } + + // Tree#dupNode constructor + public BasicInteraction(BasicInteraction node) + { + super(node); + } +} + diff --git a/scribble-ast/src/main/java/org/scribble/ast/Choice.java b/scribble-ast/src/main/java/org/scribble/ast/Choice.java new file mode 100644 index 000000000..1823047fb --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/Choice.java @@ -0,0 +1,91 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast; + +import java.util.List; +import java.util.stream.Collectors; + +import org.antlr.runtime.Token; +import org.scribble.ast.name.simple.RoleNode; +import org.scribble.core.type.kind.ProtoKind; +import org.scribble.util.Constants; +import org.scribble.util.ScribException; +import org.scribble.visit.AstVisitor; + +public abstract class Choice + extends CompoundInteraction +{ + public static final int SUBJ_CHILD_INDEX = 0; + public static final int BLOCK_CHILDREN_START_INDEX = 1; + + // ScribTreeAdaptor#create constructor + public Choice(Token t) + { + super(t); + } + + // Tree#dupNode constructor + protected Choice(Choice node) + { + super(node); + } + + public RoleNode getSubjectChild() + { + return (RoleNode) getChild(SUBJ_CHILD_INDEX); + } + + // Override in concrete sub for cast + public abstract List> getBlockChildren(); + + // "add", not "set" + public void addScribChildren(RoleNode subj, + List> blocks) + { + // Cf. above getters and Scribble.g children order + addChild(subj); + addChildren(blocks); + } + + @Override + public abstract Choice dupNode(); + + public Choice reconstruct(RoleNode subj, + List> blocks) + { + Choice dup = dupNode(); + dup.addScribChildren(subj, blocks); + dup.setDel(del()); // No copy + return dup; + } + + @Override + public Choice visitChildren(AstVisitor nv) throws ScribException + { + RoleNode subj = (RoleNode) visitChild(getSubjectChild(), nv); + List> blocks = + visitChildListWithClassEqualityCheck(this, getBlockChildren(), nv); + return reconstruct(subj, blocks); + } + + @Override + public String toString() + { + String sep = " " + Constants.OR_KW + " "; + return Constants.CHOICE_KW + " " + + Constants.AT_KW + " " + getSubjectChild() + " " + + getBlockChildren().stream().map(b -> b.toString()) + .collect(Collectors.joining(sep)); + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/CompoundInteraction.java b/scribble-ast/src/main/java/org/scribble/ast/CompoundInteraction.java new file mode 100644 index 000000000..716948b1b --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/CompoundInteraction.java @@ -0,0 +1,33 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast; + +import org.antlr.runtime.Token; +import org.scribble.core.type.kind.ProtoKind; + +public abstract class CompoundInteraction + extends CompoundSessionNode +{ + // ScribTreeAdaptor#create constructor + public CompoundInteraction(Token t) + { + super(t); + } + + // Tree#dupNode constructor + protected CompoundInteraction(CompoundInteraction node) + { + super(node); + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/CompoundSessionNode.java b/scribble-ast/src/main/java/org/scribble/ast/CompoundSessionNode.java new file mode 100644 index 000000000..f320a43da --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/CompoundSessionNode.java @@ -0,0 +1,34 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast; + +import org.antlr.runtime.Token; +import org.scribble.core.type.kind.ProtoKind; + +// Redundant? Is always a CompoundInteraction -- cf. SimpleSessionNode +public abstract class CompoundSessionNode + extends ScribNodeBase implements SessionNode +{ + // ScribTreeAdaptor#create constructor + public CompoundSessionNode(Token t) + { + super(t); + } + + // Tree#dupNode constructor + protected CompoundSessionNode(CompoundSessionNode node) + { + super(node); + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/ConnectAction.java b/scribble-ast/src/main/java/org/scribble/ast/ConnectAction.java new file mode 100644 index 000000000..37c64dcfc --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/ConnectAction.java @@ -0,0 +1,61 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast; + +import java.util.List; + +import org.antlr.runtime.Token; +import org.scribble.ast.name.simple.RoleNode; +import org.scribble.core.type.kind.ProtoKind; + +// TODO CHECKME: factor with MessageTransfer? +public abstract class ConnectAction + extends DirectedInteraction +{ + // ScribTreeAdaptor#create constructor + public ConnectAction(Token t) + { + super(t); + } + + // Tree#dupNode constructor + public ConnectAction(ConnectAction node) + { + super(node); + } + + // TODO: refactor + public RoleNode getDestinationChild() + { + List dests = getDestinationChildren(); + if (dests.size() != 1) + { + throw new RuntimeException("Shouldn't get in here: " + this); + // CHECKME: don't use common src/dst pattern between global/local? + } + return dests.get(0); + } + + // CHECKME: currently only used for toString, because current syntax allows "connect" with no explicit message ? + protected boolean isUnitMessage() + { + MsgNode n = getMessageNodeChild(); + if (!n.isSigLitNode()) + { + return false; + } + SigLitNode msn = (SigLitNode) n; + return msn.getOpChild().isEmpty() && msn.getPayloadListChild().isEmpty(); + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/Continue.java b/scribble-ast/src/main/java/org/scribble/ast/Continue.java new file mode 100644 index 000000000..f64dd6eb6 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/Continue.java @@ -0,0 +1,74 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast; + +import org.antlr.runtime.Token; +import org.scribble.ast.name.simple.RecVarNode; +import org.scribble.core.type.kind.ProtoKind; +import org.scribble.util.Constants; +import org.scribble.util.ScribException; +import org.scribble.visit.AstVisitor; + +public abstract class Continue + extends SimpleSessionNode +{ + public static final int RECVAR_CHILD_INDEX = 0; + + // ScribTreeAdaptor#create constructor + public Continue(Token t) + { + super(t); + } + + // Tree#dupNode constructor + protected Continue(Continue node) + { + super(node); + } + + // "add", not "set" + public void addScribChildren(RecVarNode rv) + { + // Cf. above getters and Scribble.g children order + addChild(rv); + } + + public abstract Continue dupNode(); + + public RecVarNode getRecVarChild() + { + return (RecVarNode) getChild(RECVAR_CHILD_INDEX); + } + + public Continue reconstruct(RecVarNode rv) + { + Continue dup = dupNode(); + dup.addScribChildren(rv); + dup.setDel(del()); // No copy + return dup; + } + + @Override + public Continue visitChildren(AstVisitor nv) throws ScribException + { + RecVarNode recvar = (RecVarNode) visitChild(getRecVarChild(), nv); + return reconstruct(recvar); + } + + @Override + public String toString() + { + return Constants.CONTINUE_KW + " " + getRecVarChild() + ";"; + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/DataDecl.java b/scribble-ast/src/main/java/org/scribble/ast/DataDecl.java new file mode 100644 index 000000000..56f5f59e0 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/DataDecl.java @@ -0,0 +1,86 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast; + +import org.antlr.runtime.Token; +import org.scribble.ast.name.qualified.DataNameNode; +import org.scribble.core.type.kind.DataKind; +import org.scribble.core.type.name.DataName; +import org.scribble.core.type.name.ModuleName; +import org.scribble.del.DelFactory; +import org.scribble.util.Constants; + +public class DataDecl extends NonProtoDecl +{ + // ScribTreeAdaptor#create constructor + public DataDecl(Token payload) + { + super(payload); + } + + // Tree#dupNode constructor + protected DataDecl(DataDecl node) + { + super(node); + } + + @Override + public DataNameNode getNameNodeChild() + { + return (DataNameNode) getRawNameNodeChild(); + } + + // Cf. CommonTree#dupNode + @Override + public DataDecl dupNode() + { + return new DataDecl(this); + } + + @Override + public void decorateDel(DelFactory df) + { + df.DataDecl(this); + } + + @Override + public boolean isDataDecl() + { + return true; + } + + // Simple name (ModuleDecl is the only NameDeclNode that uses qualified names) + @Override + public DataName getDeclName() + { + return getNameNodeChild().toName(); + } + + @Override + public DataName getFullMemberName(Module mod) + { + ModuleName fullmodname = mod.getFullModuleName(); + return new DataName(fullmodname, getDeclName()); + } + + @Override + public String toString() + { + return Constants.DATA_KW + " <" + getSchemaChild() + "> " + + getExtNameChild() + " " + + Constants.FROM_KW + " " + getExtSourceChild() + " " + + Constants.AS_KW + " " + getDeclName() + + ";"; + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/DataParamDecl.java b/scribble-ast/src/main/java/org/scribble/ast/DataParamDecl.java new file mode 100644 index 000000000..732edec8b --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/DataParamDecl.java @@ -0,0 +1,66 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast; + +import org.antlr.runtime.Token; +import org.scribble.ast.name.simple.DataParamNode; +import org.scribble.core.type.kind.DataKind; +import org.scribble.core.type.name.DataName; +import org.scribble.del.DelFactory; +import org.scribble.util.Constants; + +public class DataParamDecl extends NonRoleParamDecl +{ + // ScribTreeAdaptor#create constructor + public DataParamDecl(Token t) + { + super(t, DataKind.KIND); + } + + // Tree#dupNode constructor + public DataParamDecl(DataParamDecl node) + { + super(node); + } + + @Override + public DataParamNode getNameNodeChild() + { + return (DataParamNode) getRawNameNodeChild(); + } + + @Override + public DataParamDecl dupNode() + { + return new DataParamDecl(this); + } + + @Override + public void decorateDel(DelFactory df) + { + df.DataParamDecl(this); + } + + @Override + public DataName getDeclName() + { + return (DataName) getNameNodeChild().toName(); + } + + @Override + public String getKeyword() + { + return Constants.DATA_KW; + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/DirectedInteraction.java b/scribble-ast/src/main/java/org/scribble/ast/DirectedInteraction.java new file mode 100644 index 000000000..2b3eeda06 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/DirectedInteraction.java @@ -0,0 +1,101 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast; + +import java.util.List; +import java.util.stream.Collectors; + +import org.antlr.runtime.Token; +import org.scribble.ast.name.simple.RoleNode; +import org.scribble.core.type.kind.ProtoKind; +import org.scribble.core.type.name.Role; +import org.scribble.util.ScribException; +import org.scribble.visit.AstVisitor; + +// FIXME: rename (Simple)Interaction, after existing SimpleInteraction renamed +public abstract class DirectedInteraction + extends BasicInteraction +{ + public static final int MSG_CHILD_INDEX = 0; + public static final int SRC_CHILD_INDEX = 1; + public static final int DST_CHILDREN_START_INDEX = 2; + + // ScribTreeAdaptor#create constructor + public DirectedInteraction(Token t) + { + super(t); + } + + // Tree#dupNode constructor + public DirectedInteraction(DirectedInteraction node) + { + super(node); + } + + public MsgNode getMessageNodeChild() + { + return (MsgNode) getChild(MSG_CHILD_INDEX); + } + + public RoleNode getSourceChild() + { + return (RoleNode) getChild(SRC_CHILD_INDEX); + } + + public List getDestinationChildren() + { + List cs = getChildren(); + return cs.subList(DST_CHILDREN_START_INDEX, cs.size()).stream() + .map(x -> (RoleNode) x).collect(Collectors.toList()); + } + + public final List getDestinationRoles() + { + return getDestinationChildren().stream().map(rn -> rn.toName()) + .collect(Collectors.toList()); + } + + // "add", not "set" + public void addScribChildren(MsgNode msg, RoleNode src, List dsts) + { + // Cf. above getters and Scribble.g children order + addChild(msg); + addChild(src); + addChildren(dsts); + } + + public abstract DirectedInteraction dupNode(); + + public DirectedInteraction reconstruct(MsgNode msg, RoleNode src, + List dsts) + { + DirectedInteraction dup = dupNode(); + // Same order as getter indices + dup.addScribChildren(msg, src, dsts); + dup.setDel(del()); // No copy + return dup; + } + + @Override + public DirectedInteraction visitChildren(AstVisitor nv) + throws ScribException + { + MsgNode msg = (MsgNode) visitChild(getMessageNodeChild(), nv); + RoleNode src = (RoleNode) visitChild(getSourceChild(), nv); + List dests = visitChildListWithClassEqualityCheck(this, + getDestinationChildren(), nv); + return reconstruct(msg, src, dests); + } +} + diff --git a/scribble-ast/src/main/java/org/scribble/ast/DisconnectAction.java b/scribble-ast/src/main/java/org/scribble/ast/DisconnectAction.java new file mode 100644 index 000000000..2d4befc1d --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/DisconnectAction.java @@ -0,0 +1,86 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast; + +import org.antlr.runtime.Token; +import org.scribble.ast.name.simple.RoleNode; +import org.scribble.core.type.kind.ProtoKind; +import org.scribble.util.Constants; +import org.scribble.util.ScribException; +import org.scribble.visit.AstVisitor; + +// (G)Disconnect is symmetric (send/receive asymmetric/async; request/accept asymmetric/sync; (g)disconnect symmetric/async) +// However, LDisconnect is "symmetric" but self-oriented -- "left" used for self +public abstract class DisconnectAction + extends BasicInteraction +{ + public static final int LEFT_CHILD_INDEX = 0; + public static final int RIGHT_CHILD_INDEX = 1; + + // ScribTreeAdaptor#create constructor + public DisconnectAction(Token t) + { + super(t); + } + + // Tree#dupNode constructor + public DisconnectAction(DisconnectAction node) + { + super(node); + } + + public RoleNode getLeftChild() + { + return (RoleNode) getChild(LEFT_CHILD_INDEX); + } + + public RoleNode getRightChild() + { + return (RoleNode) getChild(RIGHT_CHILD_INDEX); + } + + // "add", not "set" + public void addScribChildren(RoleNode left, RoleNode right) + { + // Cf. above getters and Scribble.g children order + addChild(left); + addChild(right); + } + + public abstract DisconnectAction dupNode(); + + public DisconnectAction reconstruct(RoleNode left, RoleNode right) + { + DisconnectAction dup = dupNode(); + dup.addScribChildren(left, right); + dup.setDel(del()); // No copy + return dup; + } + + @Override + public DisconnectAction visitChildren(AstVisitor nv) + throws ScribException + { + RoleNode src = (RoleNode) visitChild(getLeftChild(), nv); + RoleNode dest = (RoleNode) visitChild(getRightChild(), nv); + return reconstruct(src, dest); + } + + @Override + public String toString() + { + return Constants.DISCONNECT_KW + " " + getLeftChild() + + " " + Constants.AND_KW + " " + getRightChild() + ";"; + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/Do.java b/scribble-ast/src/main/java/org/scribble/ast/Do.java new file mode 100644 index 000000000..36d60cbbe --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/Do.java @@ -0,0 +1,130 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast; + +import java.util.Iterator; + +import org.antlr.runtime.Token; +import org.scribble.ast.name.qualified.ProtoNameNode; +import org.scribble.core.lang.context.ModuleContext; +import org.scribble.core.type.kind.ProtoKind; +import org.scribble.core.type.name.ProtoName; +import org.scribble.core.type.name.Role; +import org.scribble.job.JobContext; +import org.scribble.util.Constants; +import org.scribble.util.ScribException; +import org.scribble.visit.AstVisitor; + +public abstract class Do + extends SimpleSessionNode // implements ScopedNode +{ + public static final int NAME_CHILD_INDEX = 0; + public static final int ARG_LIST_CHILD_INDEX = 1; + public static final int ROLE_LIST_CHILD_INDEX = 2; + + // ScribTreeAdaptor#create constructor + public Do(Token t) + { + super(t); + } + + // Tree#dupNode constructor + public Do(Do node) + { + super(node); + } + + public abstract ProtoNameNode getProtocolNameNode(); + + public NonRoleArgList getNonRoleListChild() + { + return (NonRoleArgList) getChild(ARG_LIST_CHILD_INDEX); + } + + // CHECKME: maybe wrap up role args and non-role args within the same container? + public RoleArgList getRoleListChild() + { + return (RoleArgList) getChild(ROLE_LIST_CHILD_INDEX); + } + + // "add", not "set" + public void addScribChildren(ProtoNameNode proto, NonRoleArgList as, + RoleArgList rs) + { + // Cf. above getters and Scribble.g children order + addChild(proto); // Order re. getter indices + addChild(as); + addChild(rs); + } + + public abstract Do dupNode(); + + public Do reconstruct(ProtoNameNode proto, NonRoleArgList as, + RoleArgList rs) + { + Do dup = dupNode(); + dup.addScribChildren(proto, as, rs); + dup.setDel(del()); // No copy + return dup; + } + + @Override + public Do visitChildren(AstVisitor nv) throws ScribException + { + RoleArgList ril = (RoleArgList) visitChild(getRoleListChild(), nv); + NonRoleArgList al = (NonRoleArgList) visitChild(getNonRoleListChild(), nv); + ProtoNameNode proto = visitChildWithClassEqualityCheck(this, + getProtocolNameNode(), nv); + return reconstruct(proto, al, ril); + } + + // FIXME: mcontext now redundant because NameDisambiguator converts all targets to full names -- NO: currently disamb doesn't + // To get full name from original target name, use mcontext visible names (e.g. in or before name disambiguation pass) + // This is still useful for subclass casting to G/LProtocolName + public ProtoName getTargetProtoDeclFullName(ModuleContext mcontext) + { + //return mcontext.checkProtocolDeclDependencyFullName(this.proto.toName()); + return getProtocolNameNode().toName(); // Pre: use after name disambiguation (maybe drop FullName suffix) + } + + // CHECKME: mcontext redundant, because redundant for getTargetProtocolDeclFullName + public abstract ProtoDecl getTargetProtocolDecl(JobContext jcontext, + ModuleContext mcontext); + + public Role getTargetRoleParameter(JobContext jcontext, + ModuleContext mcontext, Role role) + { + Iterator args = getRoleListChild().getRoles().iterator(); + Iterator params = getTargetProtocolDecl(jcontext, mcontext) + .getHeaderChild().getRoleDeclListChild().getRoles().iterator(); + while (args.hasNext()) + { + Role arg = args.next(); + Role param = params.next(); + if (arg.equals(role)) + { + return param; + } + } + throw new RuntimeException("Not an argument role: " + role); + } + + @Override + public String toString() + { + String s = Constants.DO_KW + " "; + return s + getProtocolNameNode() + getNonRoleListChild() + getRoleListChild() + + ";"; + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/DoArg.java b/scribble-ast/src/main/java/org/scribble/ast/DoArg.java new file mode 100644 index 000000000..cd063a8c3 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/DoArg.java @@ -0,0 +1,76 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast; + +import org.antlr.runtime.Token; +import org.scribble.util.ScribException; +import org.scribble.visit.AstVisitor; + +// TODO: rename better? DoArg, DoArgNode, ... +// CHECKME: make DoArg into an interface and have DoArgNode as direct children of Do? +// Cf. NameDeclNode/HeaderParameterDecl, i.e. wrappers for param names/arg values +// Simpler than NameDeclNode, doesn't constrain node-type correspondence for names +public abstract class DoArg extends ScribNodeBase +{ + // ScribTreeAdaptor#create constructor + public DoArg(Token t) + { + super(t); + } + + // Tree#dupNode constructor + public DoArg(DoArg node) + { + super(node); + } + + public abstract T getArgNodeChild(); + + // "add", not "set" + public void addScribChildren(T arg) + { + // Cf. above getters and Scribble.g children order + addChild(arg); + } + + public abstract DoArg dupNode(); + + public DoArg reconstruct(T arg) + { + DoArg dup = dupNode(); + dup.addScribChildren(arg); + dup.setDel(del()); // No copy + return dup; + } + + @Override + public DoArg visitChildren(AstVisitor nv) throws ScribException + { + ScribNode visited = visitChild(getArgNodeChild(), nv); // Disambiguation will replace AmbiguousNameNodes + // CHECKME: use visitChildWithClassEqualityCheck? + if (!(visited instanceof DoArgNode)) + { + throw new RuntimeException("Shouldn't get in here: " + visited); + } + @SuppressWarnings("unchecked") + T arg = (T) visited; + return reconstruct(arg); + } + + @Override + public String toString() + { + return getArgNodeChild().toString(); + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/DoArgList.java b/scribble-ast/src/main/java/org/scribble/ast/DoArgList.java new file mode 100644 index 000000000..daccb7251 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/DoArgList.java @@ -0,0 +1,85 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast; + +import java.util.List; +import java.util.stream.Collectors; + +import org.antlr.runtime.Token; +import org.scribble.util.ScribException; +import org.scribble.visit.AstVisitor; + +// Cf. HeaderParameterDeclList -- but not kinded, because cannot determine Arg kind directly from node syntax itself (kinding for ModelNodes is to supplement syntactic information, not "typing" work) +// DoArgList (NonRoleArgList) can be of mixed kinds, so DoArg (NonRoleArg) used as "wildcard" wrapper +// "? extends InstantiationNode" not enforced here (e.g. can put "? extends ModelNode"), because ultimately any instantiation of this class needs an actual instance of "Instantiation" which has to have a parameter that extends "InstantiationNode" +public abstract class DoArgList> extends ScribNodeBase +{ + // ScribTreeAdaptor#create constructor + public DoArgList(Token t) + { + super(t); + } + + // Tree#dupNode constructor + public DoArgList(DoArgList node) + { + super(node); + } + + protected List getRawArgChildren() + { + return getChildren(); + } + + public abstract List getArgChildren(); + + // "add", not "set" + public void addScribChildren(List args) + { + // Cf. above getters and Scribble.g children order + addChildren(args); + } + + @Override + public abstract DoArgList dupNode(); + + public DoArgList reconstruct(List args) + { + DoArgList dup = dupNode(); + dup.addScribChildren(args); + dup.setDel(del()); // No copy + return dup; + } + + @Override + public DoArgList visitChildren(AstVisitor nv) throws ScribException + { + List nds = + visitChildListWithClassEqualityCheck(this, getArgChildren(), nv); + return reconstruct(nds); + } + + public int length() + { + return getChildCount(); + } + + // Like HeaderParamDeclList, without enclosing braces -- added by subclasses + @Override + public String toString() + { + return getArgChildren().stream().map(a -> a.toString()) + .collect(Collectors.joining(", ")); + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/DoArgNode.java b/scribble-ast/src/main/java/org/scribble/ast/DoArgNode.java new file mode 100644 index 000000000..7f9ea2209 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/DoArgNode.java @@ -0,0 +1,21 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast; + +// DoArgNode for DoArg is "dual" to (Simple)NameNode for HeaderParamDecls -- but do args are not all necessarily e.g. simplenames so have to introduce a new interface +// RoleNodes and NonRoleArgNodes +public interface DoArgNode extends ScribNode +{ + +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/ExplicitMod.java b/scribble-ast/src/main/java/org/scribble/ast/ExplicitMod.java new file mode 100644 index 000000000..82cdb2470 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/ExplicitMod.java @@ -0,0 +1,56 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast; + +import org.antlr.runtime.Token; +import org.scribble.del.DelFactory; + +public class ExplicitMod extends ProtoModNode +{ + // ScribTreeAdaptor#create constructor + public ExplicitMod(Token t) + { + super(t); + } + + // Tree#dupNode constructor + protected ExplicitMod(ExplicitMod node) + { + super(node); + } + + @Override + public boolean isExplicit() + { + return true; + } + + @Override + public ExplicitMod dupNode() + { + return new ExplicitMod(this); // return this also OK, since no children + } + + @Override + public void decorateDel(DelFactory df) + { + df.ExplicitMod(this); + } + + @Override + public String toString() + { + return "explicit"; + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/ImportDecl.java b/scribble-ast/src/main/java/org/scribble/ast/ImportDecl.java new file mode 100644 index 000000000..331a3155a --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/ImportDecl.java @@ -0,0 +1,45 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast; + +import org.antlr.runtime.Token; +import org.scribble.core.type.kind.ImportKind; +import org.scribble.core.type.name.Name; + +// CHECKME: factor out more stuff from ImportModule and ImportMember into here? e.g. alias/name, reconstruct (or else no need for common super?) +public abstract class ImportDecl extends ScribNodeBase +{ + // ScribTreeAdaptor#create constructor + public ImportDecl(Token payload) + { + super(payload); + } + + // Tree#dupNode constructor + protected ImportDecl(ImportDecl node) + { + super(node); + } + + public abstract ImportDecl dupNode(); + + public boolean isImportModule() + { + return false; + } + + public abstract boolean hasAlias(); + + public abstract Name getAlias(); +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/ImportModule.java b/scribble-ast/src/main/java/org/scribble/ast/ImportModule.java new file mode 100644 index 000000000..b7af51c3d --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/ImportModule.java @@ -0,0 +1,128 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast; + +import org.antlr.runtime.Token; +import org.scribble.ast.name.qualified.ModuleNameNode; +import org.scribble.core.type.kind.ModuleKind; +import org.scribble.core.type.name.ModuleName; +import org.scribble.del.DelFactory; +import org.scribble.util.Constants; +import org.scribble.util.ScribException; +import org.scribble.visit.AstVisitor; + +public class ImportModule extends ImportDecl +{ + public static final int MODULENAME_CHILD = 0; + public static final int ALIAS_CHILD = 1; + + // ScribTreeAdaptor#create constructor + public ImportModule(Token payload) + { + super(payload); + } + + // Tree#dupNode constructor + protected ImportModule(ImportModule node) + { + super(node); + } + + // Full name ("import x.y.Z") + public ModuleNameNode getModuleNameNodeChild() + { + return (ModuleNameNode) getChild(MODULENAME_CHILD); + } + + // Pre: hasAlias -- no alias means no child + // Simple name + // No child if no alias (cf. hasAlias) -- cf. addScribChildren, alias == null + public ModuleNameNode getAliasNameNodeChild() + { + return (ModuleNameNode) getChild(ALIAS_CHILD); + } + + // "add", not "set" + public void addScribChildren(ModuleNameNode modname, ModuleNameNode alias) + { + // Cf. above getters and Scribble.g children order + addChild(modname); + if (alias != null) + { + addChild(alias); + } + } + + // Cf. CommonTree#dupNode + @Override + public ImportModule dupNode() + { + return new ImportModule(this); + } + + @Override + public void decorateDel(DelFactory df) + { + df.ImportModule(this); + } + + // alias == null if no alias + public ImportModule reconstruct(ModuleNameNode modname, ModuleNameNode alias) + { + ImportModule dup = dupNode(); + dup.addScribChildren(modname, alias); + dup.setDel(del()); // No copy + return dup; + } + + @Override + public ImportModule visitChildren(AstVisitor nv) throws ScribException + { + ModuleNameNode modname = (ModuleNameNode) + visitChild(getModuleNameNodeChild(), nv); + ModuleNameNode alias = hasAlias() + ? (ModuleNameNode) visitChild(getAliasNameNodeChild(), nv) + : null; + return reconstruct(modname, alias); + } + + @Override + public boolean isImportModule() + { + return true; + } + + @Override + public boolean hasAlias() + { + return getChildCount() > 1; + } + + @Override + public ModuleName getAlias() + { + return getAliasNameNodeChild().toName(); + } + + @Override + public String toString() + { + String s = Constants.IMPORT_KW + " " + getModuleNameNodeChild(); + if (hasAlias()) + { + s += " " + Constants.AS_KW + " " + getAlias(); + } + return s + ";"; + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/InteractionSeq.java b/scribble-ast/src/main/java/org/scribble/ast/InteractionSeq.java new file mode 100644 index 000000000..60477d36f --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/InteractionSeq.java @@ -0,0 +1,97 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast; + +import java.util.LinkedList; +import java.util.List; +import java.util.stream.Collectors; + +import org.antlr.runtime.Token; +import org.scribble.core.type.kind.ProtoKind; +import org.scribble.util.ScribException; +import org.scribble.visit.AstVisitor; + +public abstract class InteractionSeq + extends ScribNodeBase implements ProtoKindNode +{ + // ScribTreeAdaptor#create constructor + public InteractionSeq(Token t) + { + super(t); + } + + // Tree#dupNode constructor + public InteractionSeq(InteractionSeq node) + { + super(node); + } + + public abstract List> getInteractionChildren(); + + // "add", not "set" + public void addScribChildren(List> elems) + { + // Cf. above getters and Scribble.g children order + addChildren(elems); + } + + @Override + public abstract InteractionSeq dupNode(); + + public InteractionSeq reconstruct(List> elems) + { + InteractionSeq dup = dupNode(); + dup.addScribChildren(elems); + dup.setDel(del()); // No copy + return dup; + } + + @Override + public ScribNode visitChildren(AstVisitor nv) throws ScribException + { + List> actions = new LinkedList<>(); + for (SessionNode in : getInteractionChildren()) + { + //ProtocolKindNode visited = visitProtocolKindChildWithCastCheck(this, in, nv, ProtocolKindNode.class, in.getKind(), KIND_CAST); + // No: ProjectedChoiceDoPruning (and others?) needs to return null; CastCheck doesn't allow that // CHECKME + // TODO: make a unit test for this + ScribNode visited = visitChild(in, nv); + if (visited instanceof InteractionSeq) + { + @SuppressWarnings("unchecked") + InteractionSeq tmp = (InteractionSeq) visited; + actions.addAll(tmp.getInteractionChildren()); + } + else + { + @SuppressWarnings("unchecked") + SessionNode tmp = (SessionNode) visited; + actions.add(tmp); + } + } + return reconstruct(actions); + } + + public boolean isEmpty() + { + return getChildCount() == 0; //this.inters.isEmpty(); + } + + @Override + public String toString() + { + return getInteractionChildren().stream().map(i -> i.toString()) + .collect(Collectors.joining("\n")); + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/Module.java b/scribble-ast/src/main/java/org/scribble/ast/Module.java new file mode 100644 index 000000000..2902e5ae6 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/Module.java @@ -0,0 +1,264 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast; + +import java.util.LinkedList; +import java.util.List; +import java.util.Optional; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.stream.Collectors; + +import org.antlr.runtime.Token; +import org.scribble.ast.global.GProtoDecl; +import org.scribble.ast.local.LProtoDecl; +import org.scribble.core.type.kind.Kind; +import org.scribble.core.type.kind.ProtoKind; +import org.scribble.core.type.name.DataName; +import org.scribble.core.type.name.GProtoName; +import org.scribble.core.type.name.LProtoName; +import org.scribble.core.type.name.MemberName; +import org.scribble.core.type.name.ModuleName; +import org.scribble.core.type.name.ProtoName; +import org.scribble.core.type.name.SigName; +import org.scribble.del.DelFactory; +import org.scribble.util.ScribException; +import org.scribble.visit.AstVisitor; + +public class Module extends ScribNodeBase +{ + public static final int MODDECL_CHILD_INDEX = 0; + + // ScribTreeAdaptor#create constructor + public Module(Token payload) + { + super(payload); + } + + // Tree#dupNode constructor + protected Module(Module node) + { + super(node); + } + + public ModuleDecl getModuleDeclChild() + { + return (ModuleDecl) getChild(MODDECL_CHILD_INDEX); + } + + public List> getImportDeclChildren() + { + return getMemberChildren(x -> x instanceof ImportDecl, + x -> (ImportDecl) x); + } + + public List> getNonProtoDeclChildren() + { + return getMemberChildren(x -> x instanceof NonProtoDecl, + x -> (NonProtoDecl) x); + } + + public List> getProtoDeclChildren() + { + return getMemberChildren(x -> x instanceof ProtoDecl, + x -> (ProtoDecl) x); + } + + // Not requiring T extends ModuleMember, ImportDecl is not a ModuleMember + private List getMemberChildren( + Predicate instanceOf, Function cast) + { + List res = new LinkedList<>(); + boolean b = false; + // Start collecting from first instance, and stop on first non-instance or end + for (ScribNode c : getChildren()) + { + if (!b && instanceOf.test(c)) b = true; + else if (b && !instanceOf.test(c)) break; + if (b) res.add(cast.apply(c)); + } + return res; + } + + // "add", not "set" + public void addScribChildren(ModuleDecl moddecl, + List> imports, + List> data, List> protos) + { + // Cf. above getters and Scribble.g children order + addChild(moddecl); + addChildren(imports); + addChildren(data); + addChildren(protos); + } + + // Cf. CommonTree#dupNode + @Override + public Module dupNode() + { + return new Module(this); + } + + @Override + public void decorateDel(DelFactory df) + { + df.Module(this); + } + + // Set args as children on a dup of this -- children *not* cloned + protected Module reconstruct(ModuleDecl moddecl, List> imports, + List> data, List> protos) + { + Module dup = dupNode(); + dup.addScribChildren(moddecl, imports, data, protos); + dup.setDel(del()); // No copy + return dup; + } + + @Override + public Module visitChildren(AstVisitor nv) throws ScribException + { + ModuleDecl moddecl = (ModuleDecl) visitChild(getModuleDeclChild(), nv); + // class equality check probably too restrictive -- FIXME: remove class checks + List> imports = ScribNodeBase + .visitChildListWithClassEqualityCheck(this, getImportDeclChildren(), nv); + List> data = ScribNodeBase + .visitChildListWithClassEqualityCheck(this, getNonProtoDeclChildren(), nv); + List> protos = ScribNodeBase + .visitChildListWithClassEqualityCheck(this, getProtoDeclChildren(), nv); + return reconstruct(moddecl, imports, data, protos); + } + + public DataDecl getTypeDeclChild(DataName simpname) + { + return (DataDecl) getNonProtoDeclChild(simpname, NonProtoDecl::isDataDecl); + } + + public SigDecl getSigDeclChild(SigName simpname) + { + return (SigDecl) getNonProtoDeclChild(simpname, NonProtoDecl::isSigDecl); + } + + private NonProtoDecl getNonProtoDeclChild(MemberName simpname, + Predicate> f) + { + Optional> res = getNonProtoDeclChildren().stream() + .filter(x -> f.test(x) && x.getDeclName().equals(simpname)) + .findFirst(); // No duplication check, rely on WF + if (!res.isPresent()) + { + throw new RuntimeException("Data decl not found: " + simpname); + } + return res.get(); + } + + public List getGProtoDeclChildren() + { + return getProtoDeclChildren().stream().filter(x -> x.isGlobal()) + .map(x -> (GProtoDecl) x).collect(Collectors.toList()); + // Less efficient, but smaller code + } + + public List getLProtoDeclChildren() + { + return getProtoDeclChildren().stream().filter(x -> x.isLocal()) + .map(x -> (LProtoDecl) x).collect(Collectors.toList()); + // Less efficient, but smaller code + } + + // CHECKME: allow global and local protocols with same simpname in same module? -- currently, no? + public boolean hasGProtocolDecl(GProtoName simpname) + { + return hasProtocolDeclChild(simpname, ProtoDecl::isGlobal).isPresent(); + } + + // Pre: hasGProtocolDecl(simpname) + public GProtoDecl getGProtocolDeclChild(GProtoName simpname) + { + Optional> res = hasProtocolDeclChild(simpname, + ProtoDecl::isGlobal); + if (!res.isPresent()) + { + throw new RuntimeException("Global proto decl not found: " + simpname); + } + return (GProtoDecl) res.get(); + } + + public LProtoDecl getLProtocolDeclChild(LProtoName simpname) + { + Optional> res = hasProtocolDeclChild(simpname, + ProtoDecl::isLocal); + if (!res.isPresent()) + { + throw new RuntimeException("Local proto decl not found: " + simpname); + } + return (LProtoDecl) res.get(); + } + + private Optional> hasProtocolDeclChild( + ProtoName simpname, Predicate> f) + { + return getProtoDeclChildren().stream() + .filter(x -> f.test(x) && x.getHeaderChild().getDeclName().equals(simpname)) + .findFirst(); // No duplication check, rely on WF + } + + public ModuleName getFullModuleName() + { + return getModuleDeclChild().getFullModuleName(); + } + + @Override + public String toString() + { + String s = getModuleDeclChild().toString(); + for (ImportDecl id : getImportDeclChildren()) + { + s += "\n" + id; + } + for (NonProtoDecl dtd : getNonProtoDeclChildren()) + { + s += "\n" + dtd; + } + for (ProtoDecl pd : getProtoDeclChildren()) + { + s += "\n" + pd; + } + return s; + } +} + + + + + + + + + + + + + + + + + + + + /*private static final Predicate IS_GPROTOCOLDECL = + x -> (x instanceof ProtocolDecl) && ((ProtocolDecl) x).isGlobal(); + + private static final Function TO_GPROTOCOLDECL = + x -> (GProtocolDecl) x;*/ diff --git a/scribble-ast/src/main/java/org/scribble/ast/ModuleDecl.java b/scribble-ast/src/main/java/org/scribble/ast/ModuleDecl.java new file mode 100644 index 000000000..98c24e591 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/ModuleDecl.java @@ -0,0 +1,96 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast; + +import org.antlr.runtime.Token; +import org.scribble.ast.name.qualified.ModuleNameNode; +import org.scribble.core.type.kind.ModuleKind; +import org.scribble.core.type.name.ModuleName; +import org.scribble.del.DelFactory; +import org.scribble.util.Constants; +import org.scribble.util.ScribException; +import org.scribble.visit.AstVisitor; + +public class ModuleDecl extends NameDeclNode +{ + // ScribTreeAdaptor#create constructor + public ModuleDecl(Token t) + { + super(t); + } + + // Tree#dupNode constructor + protected ModuleDecl(ModuleDecl node) + { + super(node); + } + + @Override + public ModuleNameNode getNameNodeChild() + { + return (ModuleNameNode) getRawNameNodeChild(); + } + + // "add", not "set" + public void addScribChildren(ModuleNameNode name) + { + // Cf. above getters and Scribble.g children order + addChild(name); + } + + // Cf. CommonTree#dupNode + @Override + public ModuleDecl dupNode() + { + return new ModuleDecl(this); + } + + @Override + public void decorateDel(DelFactory df) + { + df.ModuleDecl(this); + } + + protected ModuleDecl reconstruct(ModuleNameNode name) + { + ModuleDecl dup = dupNode(); + dup.addScribChildren(name); + dup.setDel(del()); // No copy + return dup; + } + + @Override + public ModuleDecl visitChildren(AstVisitor nv) throws ScribException + { + ModuleNameNode name = (ModuleNameNode) visitChild(getNameNodeChild(), nv); + return reconstruct(name); + } + + public ModuleName getFullModuleName() + { + return (ModuleName) getNameNodeChild().toName(); + } + + @Override + public ModuleName getDeclName() + { + return getNameNodeChild().toName().getSimpleName(); // Uniform with other NameDeclNodes wrt. returning simple name + } + + @Override + public String toString() + { + return Constants.MODULE_KW + " " + getFullModuleName() + ";"; + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/ModuleMember.java b/scribble-ast/src/main/java/org/scribble/ast/ModuleMember.java new file mode 100644 index 000000000..c0ce26cab --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/ModuleMember.java @@ -0,0 +1,24 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast; + +import org.scribble.core.type.kind.ModuleMemberKind; +import org.scribble.core.type.name.MemberName; + +// Not an abstract class, NonProtocolDecl extends NameDeclNode (whereas ProtocolDecl uses ProtocolHeader for that) +public interface ModuleMember +{ + MemberName getFullMemberName(Module mod); + // Should not use ModuleContext -- i.e. works before ModuleContext is built (indeed, context building uses this) +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/MsgNode.java b/scribble-ast/src/main/java/org/scribble/ast/MsgNode.java new file mode 100644 index 000000000..26c4eaf5f --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/MsgNode.java @@ -0,0 +1,24 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast; + +import org.scribble.core.type.session.Msg; + +// A sig kind node: MessageSignatureNode, MessageSignatureNameNode or NonRoleParamNode +public interface MsgNode extends NonRoleArgNode +{ + Msg toMsg(); + + //Arg toArg(); // Not possible due to "diamond" with PayloadElemNameNode at AmbigNameNode +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/MsgTransfer.java b/scribble-ast/src/main/java/org/scribble/ast/MsgTransfer.java new file mode 100644 index 000000000..b73eb146d --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/MsgTransfer.java @@ -0,0 +1,35 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast; + +import org.antlr.runtime.Token; +import org.scribble.core.type.kind.ProtoKind; + +public abstract class MsgTransfer + extends DirectedInteraction +{ + // ScribTreeAdaptor#create constructor + public MsgTransfer(Token t) + { + super(t); + } + + // Tree#dupNode constructor + public MsgTransfer(MsgTransfer node) + { + super(node); + } +} + + diff --git a/scribble-ast/src/main/java/org/scribble/ast/NameDeclNode.java b/scribble-ast/src/main/java/org/scribble/ast/NameDeclNode.java new file mode 100644 index 000000000..5492874bb --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/NameDeclNode.java @@ -0,0 +1,57 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast; + +import org.antlr.runtime.Token; +import org.scribble.ast.name.NameNode; +import org.scribble.core.type.kind.Kind; +import org.scribble.core.type.name.Name; + +public abstract class NameDeclNode extends ScribNodeBase +{ + public static final int NAMENODE_CHILD_INDEX = 0; + + // ScribTreeAdaptor#create constructor + public NameDeclNode(Token t) + { + super(t); + } + + // Tree#dupNode constructor + public NameDeclNode(NameDeclNode node) + { + super(node); + } + + // CHECKME: always AmbigNameNode? + protected final NameNode getRawNameNodeChild() + { + if (getChildCount() < 1) // E.g., ProtocolHeader three children + { + throw new RuntimeException("Shouldn't get in here: " + getClass()); + } + NameNode name = (NameNode) getChild(NAMENODE_CHILD_INDEX); + return name; + } + + // Concrete subclasses should use getRawNameNodeChild() and cast + // (Avoids needing to explicitly record the kind, cf. NonRoleParamDecl) + // (Gets overridden anyway for return type) + public abstract NameNode getNameNodeChild(); + + // Return: *simple* name (cf. ModuleDecl) + // Concrete subclasses should use getNameNode, toName (simple name) and cast + // (Gets overridden anyway for return type) + public abstract Name getDeclName(); +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/NonProtoDecl.java b/scribble-ast/src/main/java/org/scribble/ast/NonProtoDecl.java new file mode 100644 index 000000000..2a87b1de6 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/NonProtoDecl.java @@ -0,0 +1,124 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast; + +import org.antlr.runtime.Token; +import org.scribble.ast.name.NameNode; +import org.scribble.ast.name.simple.ExtIdNode; +import org.scribble.ast.name.simple.IdNode; +import org.scribble.core.type.kind.NonProtoKind; +import org.scribble.util.ScribException; +import org.scribble.visit.AstVisitor; + +// Rename to something better +public abstract class NonProtoDecl + extends NameDeclNode implements ModuleMember +{ + // NameDeclNode.NAMENODE_CHILD_INDEX = 0; + public static final int SCHEMA_NODE_CHILD_INDEX = 1; + public static final int EXTNAME_NODE_CHILD_INDEX = 2; + public static final int EXTSOURCE_NODE_CHILD_INDEX = 3; + + // ScribTreeAdaptor#create constructor + public NonProtoDecl(Token payload) + { + super(payload); + } + + // Tree#dupNode constructor + protected NonProtoDecl(NonProtoDecl node) + { + super(node); + } + + // Redundant override, just for documentation + @Override + public abstract NameNode getNameNodeChild(); + + public IdNode getSchemaChild() + { + return (IdNode) getChild(SCHEMA_NODE_CHILD_INDEX); + } + + public ExtIdNode getExtNameChild() + { + return (ExtIdNode) getChild(EXTNAME_NODE_CHILD_INDEX); + } + + public ExtIdNode getExtSourceChild() + { + return (ExtIdNode) getChild(EXTSOURCE_NODE_CHILD_INDEX); + } + + // "add", not "set" + public void addScribChildren(NameNode name, IdNode schema, + ExtIdNode extName, ExtIdNode extSource) + { + // Cf. above getters and Scribble.g children order + addChild(name); + addChild(schema); + addChild(extName); + addChild(extSource); + } + + // CHECKME: maybe move to ModuleMember + public boolean isDataDecl() + { + return false; + } + + public boolean isSigDecl() + { + return false; + } + + @Override + public abstract NonProtoDecl dupNode(); + + public NonProtoDecl reconstruct(NameNode name, IdNode schema, + ExtIdNode extName, ExtIdNode extSource) + { + NonProtoDecl dup = dupNode(); + dup.addScribChildren(name, schema, extName, extSource); + dup.setDel(del()); // No copy + return dup; + } + + @Override + public NonProtoDecl visitChildren(AstVisitor nv) + throws ScribException + { + NameNode name = (NameNode) visitChildWithClassEqualityCheck(this, + getNameNodeChild(), nv); + IdNode schema = getSchemaChild(); + ExtIdNode extName = getExtNameChild(); + ExtIdNode extSource = getExtSourceChild(); + return reconstruct(name, schema, extName, extSource); + } + + public String getSchema() + { + return getSchemaChild().getText(); + } + + public String getExtName() + { + return getExtNameChild().getText(); + } + + public String getExtSource() + { + return getExtSourceChild().getText(); + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/NonRoleArg.java b/scribble-ast/src/main/java/org/scribble/ast/NonRoleArg.java new file mode 100644 index 000000000..9358573f1 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/NonRoleArg.java @@ -0,0 +1,52 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast; + +import org.antlr.runtime.Token; +import org.scribble.del.DelFactory; + +public class NonRoleArg extends DoArg +{ + public static final int ARG_NODE_CHILD_INDEX = 0; + + // ScribTreeAdaptor#create constructor + public NonRoleArg(Token t) + { + super(t); + } + + // Tree#dupNode constructor + public NonRoleArg(NonRoleArg node) + { + super(node); + } + + @Override + public NonRoleArgNode getArgNodeChild() + { + return (NonRoleArgNode) getChild(ARG_NODE_CHILD_INDEX); + } + + @Override + public NonRoleArg dupNode() + { + return new NonRoleArg(this); + } + + @Override + public void decorateDel(DelFactory df) + { + df.NonRoleArg(this); + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/NonRoleArgList.java b/scribble-ast/src/main/java/org/scribble/ast/NonRoleArgList.java new file mode 100644 index 000000000..bc9b951d7 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/NonRoleArgList.java @@ -0,0 +1,115 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast; + +import java.util.LinkedList; +import java.util.List; +import java.util.stream.Collectors; + +import org.antlr.runtime.Token; +import org.scribble.core.type.kind.NonRoleArgKind; +import org.scribble.core.type.kind.NonRoleParamKind; +import org.scribble.core.type.name.DataName; +import org.scribble.core.type.name.SigName; +import org.scribble.core.type.session.Arg; +import org.scribble.core.type.session.SigLit; +import org.scribble.del.DelFactory; + +// Cf. NonRoleParamDeclList +public class NonRoleArgList extends DoArgList +{ + // ScribTreeAdaptor#create constructor + public NonRoleArgList(Token t) + { + super(t); + } + + // Tree#dupNode constructor + public NonRoleArgList(NonRoleArgList node) + { + super(node); + } + + @Override + public List getArgChildren() + { + return getRawArgChildren().stream().map(x -> (NonRoleArg) x) + .collect(Collectors.toList()); + } + + public List getArgNodes() + { + return getArgChildren().stream().map(x -> x.getArgNodeChild()) + .collect(Collectors.toList()); + } + + public boolean isEmpty() + { + return getArgChildren().isEmpty(); + } + + // Can return a mix of arg kinds + public List> getArguments() + { + return getArgChildren().stream() + .map(x -> (Arg) x.getArgNodeChild().toArg()) + .collect(Collectors.toList()); + } + + // Cast all, assuming no Ambig + public List> getParamKindArgs() + { + List> cast = new LinkedList<>(); + for (Arg a : getArguments()) + { + if (a instanceof SigLit) + { + cast.add((SigLit) a); + } + else if (a instanceof DataName) + { + cast.add((DataName) a); + } + else if (a instanceof SigName) + { + cast.add((SigName) a); + } + else + { + throw new RuntimeException("TODO: " + a); + } + } + return cast; + } + + @Override + public NonRoleArgList dupNode() + { + return new NonRoleArgList(this); + } + + @Override + public void decorateDel(DelFactory df) + { + df.NonRoleArgList(this); + } + + @Override + public String toString() + { + return getArgChildren().isEmpty() + ? "" + : "<" + super.toString() + ">"; + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/NonRoleArgNode.java b/scribble-ast/src/main/java/org/scribble/ast/NonRoleArgNode.java new file mode 100644 index 000000000..8a1f0ff4e --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/NonRoleArgNode.java @@ -0,0 +1,52 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast; + +import org.scribble.core.type.kind.NonRoleArgKind; +import org.scribble.core.type.session.Arg; + +// sig or payloadtype kinds that can be used as do arg vals, cf. RoleNode +// "Value nodes" (sigs or names) that can be used as non-role subprotocol arguments (doesn't include role instantation arguments) +// N.B. not the actual argument node itself (that is NonRoleArg, element of NonRoleArgList, which wraps these nodes) +public interface NonRoleArgNode extends DoArgNode +{ + Arg toArg(); + + // Not kinded: point of this interface is don't know which kind the node is -- so use the "is" methods -- cf. AmbigNameNode inherits both sig and data kind + // And not all values are names, e.g. message sigs + default boolean isSigLitNode() + { + return false; + } + + default boolean isSigNameNode() + { + return false; + } + + default boolean isDataNameNode() + { + return false; + } + + default boolean isSigParamNode() + { + return false; + } + + default boolean isDataParamNode() + { + return false; + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/NonRoleParamDecl.java b/scribble-ast/src/main/java/org/scribble/ast/NonRoleParamDecl.java new file mode 100644 index 000000000..680964d38 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/NonRoleParamDecl.java @@ -0,0 +1,42 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast; + +import org.antlr.runtime.Token; +import org.scribble.core.type.kind.NonRoleParamKind; +import org.scribble.core.type.name.MemberName; + +// CHECKME: drop generic parameter and kind? +public abstract class NonRoleParamDecl + extends ParamDecl +{ + public final K kind; // CHECKME: factor up to super? + + // ScribTreeAdaptor#create constructor + public NonRoleParamDecl(Token t, K kind) + { + super(t); + this.kind = kind; + } + + // Tree#dupNode constructor + public NonRoleParamDecl(NonRoleParamDecl node) + { + super(node); + this.kind = node.kind; + } + + @Override + public abstract MemberName getDeclName(); // DataType/MessageSigName are MemberNames +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/NonRoleParamDeclList.java b/scribble-ast/src/main/java/org/scribble/ast/NonRoleParamDeclList.java new file mode 100644 index 000000000..deecc8b45 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/NonRoleParamDeclList.java @@ -0,0 +1,94 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast; + +import java.util.List; +import java.util.stream.Collectors; + +import org.antlr.runtime.Token; +import org.scribble.core.type.kind.NonRoleParamKind; +import org.scribble.core.type.name.MemberName; +import org.scribble.del.DelFactory; + +// Can contain "mixed" type/sig kinds +// Typing a bit awkward that this list has to use NonRoleParamKind as the "concrete" kind, while the NonRoleParamDecl elements use the actual concrete kind +// But OK because the NonRoleParamDecl nodes are immutable (the generic kind value is never rewritten after instantiation, only read) +public class NonRoleParamDeclList extends ParamDeclList +{ + // ScribTreeAdaptor#create constructor + public NonRoleParamDeclList(Token t) + { + super(t); + } + + // Tree#dupNode constructor + public NonRoleParamDeclList(NonRoleParamDeclList node) + { + super(node); + } + + @Override + public List> getDeclChildren() + { + @SuppressWarnings("unchecked") + List> cast = + getChildren().stream() + .map(x -> (NonRoleParamDecl) x) // Cast specifically to NonRoleParamKind (not "?") for hetero list + .collect(Collectors.toList()); + return cast; + } + + /*// "add", not "set" + public void addScribChildren(List> ds) + { + // Cf. above getters and Scribble.g children order + super.addChildren(ds); + }*/ + + @Override + public NonRoleParamDeclList dupNode() + { + return new NonRoleParamDeclList(this); + } + + @Override + public void decorateDel(DelFactory df) + { + df.NonRoleParamDeclList(this); + } + + @Override + public NonRoleParamDeclList reconstruct( + List> ds) + { + NonRoleParamDeclList dup = dupNode(); + dup.addScribChildren(ds); + dup.setDel(del()); // No copy + return dup; + } + + public List> getParams() + { + return getDeclChildren().stream().map(decl -> decl.getDeclName()) + .collect(Collectors.toList()); + } + + @Override + public String toString() + { + return (isEmpty()) + ? "" + : "<" + super.toString() + ">"; + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/ParamDecl.java b/scribble-ast/src/main/java/org/scribble/ast/ParamDecl.java new file mode 100644 index 000000000..026e306a6 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/ParamDecl.java @@ -0,0 +1,75 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast; + +import org.antlr.runtime.Token; +import org.scribble.ast.name.NameNode; +import org.scribble.core.type.kind.ParamKind; +import org.scribble.util.ScribException; +import org.scribble.visit.AstVisitor; + +// Names that are declared in a protocol header (roles and parameters -- not the protocol name though) +// RoleKind or (NonRole)ParamKind +public abstract class ParamDecl + extends NameDeclNode +{ + // ScribTreeAdaptor#create constructor + public ParamDecl(Token t) + { + super(t); + } + + // Tree#dupNode constructor + public ParamDecl(ParamDecl node) + { + super(node); + } + + @Override + public abstract NameNode getNameNodeChild(); // Always a "simple" name (e.g., like Role), but Type/Sig names are not SimpleNames + + public abstract String getKeyword(); + + // "add", not "set" + public void addScribChildren(NameNode name) + { + // Cf. above getters and Scribble.g children order + addChild(name); + } + + public abstract ParamDecl dupNode(); + + public ParamDecl reconstruct(NameNode name) // Always a "simple" name (e.g., like Role), but Type/Sig names are not SimpleNames + { + ParamDecl dup = dupNode(); + dup.addScribChildren(name); + dup.setDel(del()); // No copy + return dup; + } + + @Override + public ParamDecl visitChildren(AstVisitor nv) + throws ScribException + { + NameNode name = + visitChildWithClassEqualityCheck(this, getNameNodeChild(), nv); + return reconstruct(name); + } + + @Override + public String toString() + { + return getKeyword() + " " + getDeclName().toString(); + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/ParamDeclList.java b/scribble-ast/src/main/java/org/scribble/ast/ParamDeclList.java new file mode 100644 index 000000000..0637fa0d4 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/ParamDeclList.java @@ -0,0 +1,87 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast; + +import java.util.List; +import java.util.stream.Collectors; + +import org.antlr.runtime.Token; +import org.scribble.core.type.kind.ParamKind; +import org.scribble.util.ScribException; +import org.scribble.visit.AstVisitor; + + +// RoleKind or (NonRole)ParamKind +public abstract class ParamDeclList extends ScribNodeBase +{ + // ScribTreeAdaptor#create constructor + public ParamDeclList(Token t) + { + super(t); + } + + // Tree#dupNode constructor + public ParamDeclList(ParamDeclList node) + { + super(node); + } + + public abstract List> getDeclChildren(); + + // "add", not "set" + public void addScribChildren(List> ds) + { + // Cf. above getters and Scribble.g children order + super.addChildren(ds); + } + + @Override + public abstract ParamDeclList dupNode(); + + public ParamDeclList reconstruct( + List> ds) + { + ParamDeclList dup = dupNode(); + dup.addScribChildren(ds); + dup.setDel(del()); // No copy + return dup; + } + + @Override + public ParamDeclList visitChildren(AstVisitor v) + throws ScribException + { + List> ps = + visitChildListWithClassEqualityCheck(this, getDeclChildren(), v); + return reconstruct(ps); + } + + public final int length() + { + return getDeclChildren().size(); + } + + public final boolean isEmpty() + { + return length() == 0; + } + + // Without enclosing braces -- added by subclasses + @Override + public String toString() + { + return getDeclChildren().stream().map(x -> x.toString()) + .collect(Collectors.joining(", ")); + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/PayElem.java b/scribble-ast/src/main/java/org/scribble/ast/PayElem.java new file mode 100644 index 000000000..6ee4c8711 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/PayElem.java @@ -0,0 +1,33 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast; + +import org.scribble.core.type.kind.PayElemKind; +import org.scribble.core.type.name.PayElemType; + +// Not in grammar file -- but cf. DoArg (and PayloadElemList cf. DoArgList) -- i.e. need a wrapper for mixed and initially ambiguous name kinds +public interface PayElem extends ScribNode +{ + PayElemType toPayloadType(); // Mainly a wrapper method for the wrapped NameNode + + default boolean isGlobalDelegationElem() + { + return false; + } + + default boolean isLocalDelegationElem() + { + return false; + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/PayElemList.java b/scribble-ast/src/main/java/org/scribble/ast/PayElemList.java new file mode 100644 index 000000000..83320b044 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/PayElemList.java @@ -0,0 +1,100 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast; + +import java.util.List; +import java.util.stream.Collectors; + +import org.antlr.runtime.Token; +import org.scribble.core.type.name.PayElemType; +import org.scribble.core.type.session.Payload; +import org.scribble.del.DelFactory; +import org.scribble.util.ScribException; +import org.scribble.visit.AstVisitor; + +// Cf. DoArgList, but here we don't need as much abstraction (cf. RoleArgList, NonRoleArgList) +public class PayElemList extends ScribNodeBase +{ + // ScribTreeAdaptor#create constructor + public PayElemList(Token t) + { + super(t); + } + + // Tree#dupNode constructor + public PayElemList(PayElemList node) + { + super(node); + } + + List> getElementChildren() + { + return getChildren().stream().map(x -> (PayElem) x) + .collect(Collectors.toList()); + } + + // "add", not "set" + public void addScribChildren(List> elems) + { + // Cf. above getters and Scribble.g children order + super.addChildren(elems); + } + + @Override + public PayElemList dupNode() + { + return new PayElemList(this); + } + + @Override + public void decorateDel(DelFactory df) + { + df.PayElemList(this); + } + + protected PayElemList reconstruct(List> elems) + { + PayElemList dup = dupNode(); + dup.addScribChildren(elems); + dup.setDel(del()); // No copy + return dup; + } + + @Override + public PayElemList visitChildren(AstVisitor nv) throws ScribException + { + List> elems = + visitChildListWithClassEqualityCheck(this, getElementChildren(), nv); + return reconstruct(elems); + } + + public Payload toPayload() + { + List> elems = getElementChildren().stream() + .map(x -> x.toPayloadType()).collect(Collectors.toList()); + return new Payload(elems); + } + + public boolean isEmpty() + { + return getChildCount() == 0; + } + + @Override + public String toString() + { + return "(" + getElementChildren().stream().map(x -> x.toString()) + .collect(Collectors.joining(", ")) + ")"; + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/ProtoBlock.java b/scribble-ast/src/main/java/org/scribble/ast/ProtoBlock.java new file mode 100644 index 000000000..292392c0d --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/ProtoBlock.java @@ -0,0 +1,76 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast; + +import org.antlr.runtime.Token; +import org.scribble.core.type.kind.ProtoKind; +import org.scribble.util.ScribException; +import org.scribble.visit.AstVisitor; + +public abstract class ProtoBlock + extends ScribNodeBase +{ + public static final int SEQ_CHILD_INDEX = 0; + + // ScribTreeAdaptor#create constructor + public ProtoBlock(Token t) + { + super(t); + } + + // Tree#dupNode constructor + protected ProtoBlock(ProtoBlock node) + { + super(node); + } + + public abstract InteractionSeq getInteractSeqChild(); + + public boolean isEmpty() + { + return getInteractSeqChild().isEmpty(); + } + + // "add", not "set" + public void addScribChildren(InteractionSeq seq) + { + // Cf. above getters and Scribble.g children order + addChild(seq); + } + + @Override + public abstract ProtoBlock dupNode(); + + public ProtoBlock reconstruct(InteractionSeq seq) + { + ProtoBlock dup = dupNode(); + dup.addScribChildren(seq); + dup.setDel(del()); // No copy + return dup; + } + + @Override + public ProtoBlock visitChildren(AstVisitor nv) throws ScribException + { + InteractionSeq seq = + visitChildWithClassEqualityCheck(this, getInteractSeqChild(), nv); + return reconstruct(seq); + } + + @Override + public String toString() + { + return "{\n" + getInteractSeqChild() + "\n}"; // Empty block will contain an blank line + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/ProtoDecl.java b/scribble-ast/src/main/java/org/scribble/ast/ProtoDecl.java new file mode 100644 index 000000000..a5c0dbc6a --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/ProtoDecl.java @@ -0,0 +1,108 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast; + +import java.util.List; + +import org.antlr.runtime.Token; +import org.scribble.core.type.kind.ProtoKind; +import org.scribble.core.type.name.Role; +import org.scribble.util.ScribException; +import org.scribble.visit.AstVisitor; + +// CHECKME: visitChildren for modifiers +public abstract class ProtoDecl extends ScribNodeBase + implements ModuleMember, ProtoKindNode +{ + public static final int MODLIST_CHILD = 0; + public static final int HEADER_CHILD = 1; + public static final int DEF_CHILD = 2; + + // ScribTreeAdaptor#create constructor + protected ProtoDecl(Token t) + { + super(t); + } + + // Tree#dupNode constructor + protected ProtoDecl(ProtoDecl node) + { + super(node); + } + + public ProtoModList getModifierListChild() + { + return (ProtoModList) getChild(MODLIST_CHILD); + } + + // Implement in subclasses to avoid generic cast + public abstract ProtoHeader getHeaderChild(); + public abstract ProtoDef getDefChild(); + + // "add", not "set" + public void addScribChildren(ProtoModList mods, ProtoHeader header, + ProtoDef def) + { + // Cf. above getters and Scribble.g children order + addChild(mods); + addChild(header); + addChild(def); + } + + public boolean isAux() + { + return getModifierListChild().hasAux(); + } + + public boolean isExplicit() + { + return getModifierListChild().hasExplicit(); + } + + public abstract ProtoDecl dupNode(); + + public ProtoDecl reconstruct(ProtoModList mods, ProtoHeader header, + ProtoDef def) + { + ProtoDecl dup = dupNode(); + dup.addScribChildren(mods, header, def); + dup.setDel(del()); // No copy + return dup; + } + + @Override + public ProtoDecl visitChildren(AstVisitor v) throws ScribException + { + ProtoModList mods = visitChildWithClassEqualityCheck(this, + getModifierListChild(), v); + ProtoHeader header = + visitChildWithClassEqualityCheck(this, getHeaderChild(), v); + ProtoDef def = visitChildWithClassEqualityCheck(this, getDefChild(), v); + return reconstruct(mods, header, def); + } + + public List getRoles() + { + // WF disallows unused role declarations + return getHeaderChild().getRoleDeclListChild().getRoles(); + } + + @Override + public String toString() + { + ProtoModList mods = getModifierListChild(); + return (mods.isEmpty() ? "" : mods + " ") + getHeaderChild() + " " + + getDefChild(); + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/ProtoDef.java b/scribble-ast/src/main/java/org/scribble/ast/ProtoDef.java new file mode 100644 index 000000000..85d75c949 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/ProtoDef.java @@ -0,0 +1,69 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast; + +import org.antlr.runtime.Token; +import org.scribble.core.type.kind.ProtoKind; +import org.scribble.util.ScribException; +import org.scribble.visit.AstVisitor; + +public abstract class ProtoDef extends ScribNodeBase + implements ProtoKindNode +{ + public static final int BLOCK_CHILD_INDEX = 0; + + // ScribTreeAdaptor#create constructor + public ProtoDef(Token t) + { + super(t); + } + + // Tree#dupNode constructor + protected ProtoDef(ProtoDef node) + { + super(node); + } + public abstract ProtoBlock getBlockChild(); + + // "add", not "set" + public void addScribChildren(ProtoBlock block) + { + // Cf. above getters and Scribble.g children order + addChild(block); + } + + public abstract ProtoDef dupNode(); + + public ProtoDef reconstruct(ProtoBlock block) + { + ProtoDef dup = dupNode(); + dup.addScribChildren(block); + dup.setDel(del()); // No copy + return dup; + } + + @Override + public ProtoDef visitChildren(AstVisitor nv) throws ScribException + { + ProtoBlock block = + visitChildWithClassEqualityCheck(this, getBlockChild(), nv); + return reconstruct(block); + } + + @Override + public String toString() + { + return getBlockChild().toString(); + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/ProtoHeader.java b/scribble-ast/src/main/java/org/scribble/ast/ProtoHeader.java new file mode 100644 index 000000000..980f1a32c --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/ProtoHeader.java @@ -0,0 +1,111 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast; + +import org.antlr.runtime.Token; +import org.scribble.ast.name.qualified.ProtoNameNode; +import org.scribble.core.type.kind.ProtoKind; +import org.scribble.core.type.name.ProtoName; +import org.scribble.util.Constants; +import org.scribble.util.ScribException; +import org.scribble.visit.AstVisitor; + +// TODO: parameterize on global/local name node and role decl list (i.e. self roles) +public abstract class ProtoHeader + extends NameDeclNode implements ProtoKindNode +{ + public static final int NAMENODE_CHILD = 0; + public static final int PARAMDECLLIST_CHILD = 1; + public static final int ROLEDECLLIST_CHILD = 2; + + // ScribTreeAdaptor#create constructor + public ProtoHeader(Token t) + { + super(t); + } + + // Tree#dupNode constructor + protected ProtoHeader(ProtoHeader node) + { + super(node); + } + + // Simple name + @Override + public abstract ProtoNameNode getNameNodeChild(); + + public NonRoleParamDeclList getParamDeclListChild() + { + return (NonRoleParamDeclList) getChild(PARAMDECLLIST_CHILD); + } + + public RoleDeclList getRoleDeclListChild() + { + return (RoleDeclList) getChild(ROLEDECLLIST_CHILD); // TODO: swap order with paramdecllist (in grammar) + } + + // "add", not "set" + public void addScribChildren(ProtoNameNode name, NonRoleParamDeclList ps, + RoleDeclList rs) + { + // Cf. above getters and Scribble.g children order + addChild(name); + addChild(ps); + addChild(rs); + } + + public abstract ProtoHeader dupNode(); + + public ProtoHeader reconstruct(ProtoNameNode name, NonRoleParamDeclList ps, + RoleDeclList rs) + { + ProtoHeader dup = dupNode(); + dup.addScribChildren(name, ps, rs); + dup.setDel(del()); // No copy + return dup; + } + + @Override + public ProtoHeader visitChildren(AstVisitor nv) throws ScribException + { + /*ProtocolNameNode nameNodeChild = (ProtocolNameNode) visitChild( + getNameNodeChild(), nv);*/ // Don't really need to visit, and can avoid generic cast + RoleDeclList rdl = (RoleDeclList) visitChild(getRoleDeclListChild(), nv); + NonRoleParamDeclList pdl = (NonRoleParamDeclList) + visitChild(getParamDeclListChild(), nv); + return reconstruct(getNameNodeChild(), pdl, rdl); + } + + public boolean isParamDeclListEmpty() + { + return getParamDeclListChild().isEmpty(); + } + + @Override + public ProtoName getDeclName() + { + return getNameNodeChild().toName(); + } + + @Override + public String toString() + { + String s = Constants.PROTOCOL_KW + " " + getNameNodeChild(); + if (!isParamDeclListEmpty()) + { + s += getParamDeclListChild(); + } + return s + getRoleDeclListChild(); + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/ProtoKindNode.java b/scribble-ast/src/main/java/org/scribble/ast/ProtoKindNode.java new file mode 100644 index 000000000..dfa28f83c --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/ProtoKindNode.java @@ -0,0 +1,31 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast; + +import org.scribble.core.type.kind.ProtoKind; + +public interface ProtoKindNode extends ScribNode +{ + K getKind(); + + default boolean isGlobal() + { + return false; + } + + default boolean isLocal() + { + return false; + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/ProtoModList.java b/scribble-ast/src/main/java/org/scribble/ast/ProtoModList.java new file mode 100644 index 000000000..d19fc5ab7 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/ProtoModList.java @@ -0,0 +1,98 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast; + +import java.util.List; +import java.util.stream.Collectors; + +import org.antlr.runtime.Token; +import org.scribble.del.DelFactory; +import org.scribble.util.ScribException; +import org.scribble.visit.AstVisitor; + +// (Currently) a list of mod leaf nodes as AmbigNameNodes (cf., NameNode "elements") +public class ProtoModList extends ScribNodeBase +{ + // ScribTreeAdaptor#create constructor + public ProtoModList(Token t) + { + super(t); + } + + // Tree#dupNode constructor + protected ProtoModList(ProtoModList node) + { + super(node); + } + + public List getModChildren() + { + return ((List) getChildren()).stream().map(x -> (ProtoModNode) x) + .collect(Collectors.toList()); + } + + // "add", not "set" + public void addScribChildren(List mods) + { + addChildren(mods); + } + + // CHECKME: deprecate? cf. getModChildren + // Cf., NameNode::getSimpleNameList + public List getModList() + { + return getModChildren(); + } + + public boolean hasAux() + { + return getModList().stream().anyMatch(x -> x.isAux()); + } + + public boolean hasExplicit() + { + return getModList().stream().anyMatch(x -> x.isExplicit()); + } + + public boolean isEmpty() + { + return getChildCount() == 0; + } + + @Override + public ProtoModList dupNode() + { + return new ProtoModList(this); + } + + @Override + public void decorateDel(DelFactory df) + { + df.ProtoModList(this); + } + + @Override + public ProtoModList visitChildren(AstVisitor nv) throws ScribException + { + // CHECKME: no child visiting, no reconstruct? + return this; + } + + @Override + public String toString() + { + return getModList().stream().map(x -> x.toString()) + .collect(Collectors.joining(" ")); + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/ProtoModNode.java b/scribble-ast/src/main/java/org/scribble/ast/ProtoModNode.java new file mode 100644 index 000000000..6e8cf88ff --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/ProtoModNode.java @@ -0,0 +1,61 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast; + +import org.antlr.runtime.Token; +import org.scribble.core.lang.ProtoMod; +import org.scribble.util.ScribException; +import org.scribble.visit.AstVisitor; + +public abstract class ProtoModNode extends ScribNodeBase +{ + // ScribTreeAdaptor#create constructor + public ProtoModNode(Token t) + { + super(t); + } + + // Tree#dupNode constructor + protected ProtoModNode(ProtoModNode node) + { + super(node); + } + + public boolean isAux() + { + return false; + } + + public boolean isExplicit() + { + return false; + } + + @Override + public ProtoModNode visitChildren(AstVisitor nv) throws ScribException + { + return this; + } + + // cf. toName + public ProtoMod toProtoMod() // TODO: rename + { + switch (toString()) // Directly from Scribble.g KW + { + case "aux": return ProtoMod.AUX; + case "explicit": return ProtoMod.EXPLICIT; + default: throw new RuntimeException("Unknown modifier: " + this); + } + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/Recursion.java b/scribble-ast/src/main/java/org/scribble/ast/Recursion.java new file mode 100644 index 000000000..7cc0d6519 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/Recursion.java @@ -0,0 +1,80 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast; + +import org.antlr.runtime.Token; +import org.scribble.ast.name.simple.RecVarNode; +import org.scribble.core.type.kind.ProtoKind; +import org.scribble.util.Constants; +import org.scribble.util.ScribException; +import org.scribble.visit.AstVisitor; + +public abstract class Recursion + extends CompoundInteraction +{ + public static final int RECVAR_CHILD_INDEX = 0; + public static final int BODY_CHILD_INDEX = 1; + + // ScribTreeAdaptor#create constructor + public Recursion(Token t) + { + super(t); + } + + // Tree#dupNode constructor + protected Recursion(Recursion node) + { + super(node); + } + + public abstract Recursion dupNode(); + + public RecVarNode getRecVarChild() + { + return (RecVarNode) getChild(RECVAR_CHILD_INDEX); + } + + // "add", not "set" + public void addScribChildren(RecVarNode recvar, ProtoBlock block) + { + // Cf. above getters and Scribble.g children order + addChild(recvar); + addChild(block); + } + + public abstract ProtoBlock getBlockChild(); + + public Recursion reconstruct(RecVarNode recvar, ProtoBlock block) + { + Recursion dup = dupNode(); + dup.addScribChildren(recvar, block); + dup.setDel(del()); // No copy + return dup; + } + + @Override + public Recursion visitChildren(AstVisitor nv) throws ScribException + { + RecVarNode recvar = (RecVarNode) visitChild(getRecVarChild(), nv); + ProtoBlock block = visitChildWithClassEqualityCheck(this, + getBlockChild(), nv); + return reconstruct(recvar, block); + } + + @Override + public String toString() + { + return Constants.REC_KW + " " + getRecVarChild() + " " + getBlockChild(); + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/RoleArg.java b/scribble-ast/src/main/java/org/scribble/ast/RoleArg.java new file mode 100644 index 000000000..72445d5a0 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/RoleArg.java @@ -0,0 +1,52 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast; + +import org.antlr.runtime.Token; +import org.scribble.ast.name.simple.RoleNode; +import org.scribble.del.DelFactory; + +// CHECKME: can this be simplified to an interface? (also NonRoleArg) +public class RoleArg extends DoArg +{ + // ScribTreeAdaptor#create constructor + public RoleArg(Token t) + { + super(t); + } + + // Tree#dupNode constructor + public RoleArg(RoleArg node) + { + super(node); + } + + @Override + public RoleNode getArgNodeChild() + { + return (RoleNode) getChild(0); + } + + @Override + public RoleArg dupNode() + { + return new RoleArg(this); + } + + @Override + public void decorateDel(DelFactory df) + { + df.RoleArg(this); + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/RoleArgList.java b/scribble-ast/src/main/java/org/scribble/ast/RoleArgList.java new file mode 100644 index 000000000..9c0587e78 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/RoleArgList.java @@ -0,0 +1,68 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast; + +import java.util.List; +import java.util.stream.Collectors; + +import org.antlr.runtime.Token; +import org.scribble.core.type.name.Role; +import org.scribble.del.DelFactory; + +public class RoleArgList extends DoArgList +{ + // ScribTreeAdaptor#create constructor + public RoleArgList(Token t) + { + super(t); + } + + // Tree#dupNode constructor + public RoleArgList(RoleArgList node) + { + super(node); + } + + @Override + public List getArgChildren() + { + return getRawArgChildren().stream().map(x -> (RoleArg) x) + .collect(Collectors.toList()); + } + + // The role arguments + public List getRoles() + { + return getArgChildren().stream().map(ri -> ri.getArgNodeChild().toName()) + .collect(Collectors.toList()); + } + + @Override + public RoleArgList dupNode() + { + return new RoleArgList(this); + } + + @Override + public void decorateDel(DelFactory df) + { + df.RoleArgList(this); + } + + @Override + public String toString() + { + return "(" + super.toString() + ")"; + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/RoleDecl.java b/scribble-ast/src/main/java/org/scribble/ast/RoleDecl.java new file mode 100644 index 000000000..5ac6380b7 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/RoleDecl.java @@ -0,0 +1,66 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast; + +import org.antlr.runtime.Token; +import org.scribble.ast.name.simple.RoleNode; +import org.scribble.core.type.kind.RoleKind; +import org.scribble.core.type.name.Role; +import org.scribble.del.DelFactory; +import org.scribble.util.Constants; + +public class RoleDecl extends ParamDecl +{ + // ScribTreeAdaptor#create constructor + public RoleDecl(Token t) + { + super(t); + } + + // Tree#dupNode constructor + public RoleDecl(RoleDecl node) + { + super(node); + } + + @Override + public RoleNode getNameNodeChild() + { + return (RoleNode) getRawNameNodeChild(); + } + + @Override + public RoleDecl dupNode() + { + return new RoleDecl(this); + } + + @Override + public void decorateDel(DelFactory df) + { + df.RoleDecl(this); + } + + @Override + public Role getDeclName() + { + return getNameNodeChild().toName(); + } + + @Override + public String getKeyword() + { + return Constants.ROLE_KW; + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/RoleDeclList.java b/scribble-ast/src/main/java/org/scribble/ast/RoleDeclList.java new file mode 100644 index 000000000..d95750e47 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/RoleDeclList.java @@ -0,0 +1,68 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast; + +import java.util.List; +import java.util.stream.Collectors; + +import org.antlr.runtime.Token; +import org.scribble.core.type.kind.RoleKind; +import org.scribble.core.type.name.Role; +import org.scribble.del.DelFactory; + +public class RoleDeclList extends ParamDeclList +{ + // ScribTreeAdaptor#create constructor + public RoleDeclList(Token t) + { + super(t); + } + + // Tree#dupNode constructor + public RoleDeclList(RoleDeclList node) + { + super(node); + } + + @Override + public List getDeclChildren() + { + return ((List) getChildren()).stream().map(x -> (RoleDecl) x) + .collect(Collectors.toList()); + } + + public List getRoles() + { + return getDeclChildren().stream().map(decl -> decl.getDeclName()) + .collect(Collectors.toList()); + } + + @Override + public RoleDeclList dupNode() + { + return new RoleDeclList(this); + } + + @Override + public void decorateDel(DelFactory df) + { + df.RoleDeclList(this); + } + + @Override + public String toString() + { + return "(" + super.toString() + ")"; + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/ScribNil.java b/scribble-ast/src/main/java/org/scribble/ast/ScribNil.java new file mode 100644 index 000000000..b3a10b3be --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/ScribNil.java @@ -0,0 +1,45 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast; + +import org.antlr.runtime.Token; +import org.antlr.runtime.tree.CommonTree; +import org.scribble.del.DelFactory; + +public class ScribNil extends ScribNodeBase +{ + // Used by (Scrib)TreeAdapator + public ScribNil() + { + super((Token) null); // CHECKME: null Token + } + + // Copy constructor + protected ScribNil(CommonTree node) + { + super((ScribNodeBase) node); + } + + @Override + public ScribNodeBase dupNode() + { + return new ScribNil(this); // CHECKME: nil can have children(?), so may need to actually copy + } + + @Override + public void decorateDel(DelFactory df) + { + throw new RuntimeException("Shouldn't get in here: "); + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/ScribNode.java b/scribble-ast/src/main/java/org/scribble/ast/ScribNode.java new file mode 100644 index 000000000..32115ef0b --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/ScribNode.java @@ -0,0 +1,60 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast; + +import java.util.List; + +import org.antlr.runtime.tree.CommonTree; +import org.antlr.runtime.tree.Tree; +import org.scribble.del.ScribDel; +import org.scribble.util.ScribException; +import org.scribble.visit.AstVisitor; +import org.scribble.visit.SimpleAstVisitor; +import org.scribble.visit.SimpleAstVisitorNoThrows; + +/** + * This is the generic object from which all Scribble AST objects + * are derived. + */ +public interface ScribNode extends Tree +{ + CommonTree getSource(); + // Can explicitly track an "original" source, cf. always using the "current" node as its own source + // Can be better for some error messages, e.g., during/after some AST transfomations + + @Override + ScribNode getParent(); + + //@Override -- no: super return not generic + List getChildren(); + + ScribNode clone(); + + ScribDel del(); + //ScribNode del(ScribDel del); + + ScribNode accept(AstVisitor nv) throws ScribException; // The "top-level" method, e.g., module.accept(v) (cf. Job::runVisitorOnModule) + ScribNode visitChildren(AstVisitor nv) throws ScribException; + + // For "simpler" visiting patterns than above + default T visitWith(SimpleAstVisitor v) throws ScribException // "Top-level" visitor entry method + { + return v.visit(this); // N.B. ScribNode has getParent + } + + default T visitWith(SimpleAstVisitorNoThrows v) // "Top-level" visitor entry method, c.f. STypeAggNoThrow + { + return v.visit(this); // N.B. ScribNode has getParent + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/ScribNodeBase.java b/scribble-ast/src/main/java/org/scribble/ast/ScribNodeBase.java new file mode 100644 index 000000000..5cc7202fa --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/ScribNodeBase.java @@ -0,0 +1,272 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast; + +import java.util.Collections; +import java.util.List; +import java.util.function.Function; +import java.util.stream.Collectors; + +import org.antlr.runtime.Token; +import org.antlr.runtime.tree.CommonTree; +import org.scribble.core.type.kind.Global; +import org.scribble.core.type.kind.Local; +import org.scribble.core.type.kind.ProtoKind; +import org.scribble.del.DelFactory; +import org.scribble.del.ScribDel; +import org.scribble.util.RuntimeScribException; +import org.scribble.util.ScribException; +import org.scribble.util.ScribNodeUtil; +import org.scribble.util.ScribUtil; +import org.scribble.visit.AstVisitor; + +/** + * This is the generic object from which all Scribble model objects + * are derived. + * + * ScribNodeBase is to ScribNode, as ANTLR CommonTree is to Tree. + */ +public abstract class ScribNodeBase extends CommonTree implements ScribNode +{ + private final CommonTree source; // Track "original" source where applicable + + protected ScribDel del; + + // Used by (Scrib)TreeAdapator + public ScribNodeBase(Token payload) + { + super(payload); + this.source = this; // Record parser construction as source + } + + // Copy constructor + protected ScribNodeBase(ScribNodeBase node) + { + super(node); + this.source = node.getSource(); // Keep ref to original as source (cf., this) + // A (partially) reconstructed/generated node may still have no parent (i.e., null) at the moment an error is raised during visit pass + // Can always use AntlrSourceException to blame the "child" (the original node) during visit rather than "visited", E.g., bad.syntax.disamb.doarglist.DoArgList06 + } + + @Override + public final CommonTree getSource() + { + return this.source; + } + + @Override + public ScribNode getParent() + { + return (ScribNode) super.getParent(); + } + + @Override + public ScribNode getChild(int i) + { + return (ScribNode) super.getChild(i); + } + + // N.B. "overriding" base ANTLR behaviour of (sometimes?) returning null when + // getChildCount() == 0 by returning an empty list instead + @Override + public List getChildren() + { + if (getChildCount() == 0) + { + return Collections.emptyList(); + } + return ((List) super.getChildren()).stream().map(x -> (ScribNode) x) + .collect(Collectors.toList()); + } + + // CHECKME: redundant? given this.addChildren + // Non-defenseive + // CHECKME: "generic" visitChildren and reconstruct via get/setChildren? -- maybe too implicit, cannot easily see child visiting order + protected void setChildren(List children) + { + children.forEach(x -> + { + //x.setParent(this); // Not needed, cf. BaseTree#addChild(Tree) + addChild(x); + }); + } + + // CHECKME: rework as ANTLR node (deep) copy (maybe "clone") -- no: ANTLR dupNode is node only copy (actually, dupNode is node "shell" only, doesn't even keep children, let alone copy them) + // N.B. does not copy children nor del + // Should call Tree#dupNode constructor (i.e., children not dup'd) -- do not "return this" (unless childress), ends up with children duplicated (because node "dup'd" with children, then children added again) + @Override + public abstract ScribNodeBase dupNode(); + + // Internal shallow copy for (immutable) ModelNodes -- does not keep the del (copy is used internally for del setter, and keeping the del needs knowledge of super fields) + // Generally copy is only for shallow copy of object and "immediate" fields (not super fields), cf. ProtocolDecl, ProtocolDeclContext, etc + @Deprecated + protected final ScribNodeBase copy() // Deprecated: because ANTLR Tree is not immutable (has a "parent" field) + { + throw new RuntimeException("Deprecated"); + } + + // Deep (tree) clone, i.e., children also cloned + // Makes a new del via AF (i.e. fresh, not a copy of old del) -- cf. reconstruct, keeps old del (the same instance) + // No: now just keep old del -- by default, del's are immutable + /*@Override + public abstract ScribNodeBase clone(AstFactory af);*/ + + public ScribNodeBase clone() + { + ScribNodeBase dup = (ScribNodeBase) dupNode(); + getChildren().forEach(x -> dup.addChild(x.clone())); + dup.del = this.del; + return dup; + } + + @Override + public final ScribDel del() + { + return this.del; + } + + // Decorate with a fresh del (cf. reconstruct: dupNode, setDel) + public abstract void decorateDel(DelFactory df); + + // Defensive + /*@Override + public final ScribNodeBase del(ScribDel del) + { + ScribNodeBase clone = clone(); // Need full clone because parent field prevents immutable construction + clone.setDel(del); + return clone; + }*/ + + // Non-defensive + protected final void setDel(ScribDel del) + { + this.del = del; + } + + // Defensive helper with cast check -- currently unused + public static final T del(T n, ScribDel del) + { + ScribNodeBase copy = ((ScribNodeBase) n).clone(); // Need deep clone, since children have parent field + copy.setDel(del); + return ScribNodeUtil.castNodeByClass(n, copy); + } + + @Override + public ScribNode accept(AstVisitor v) throws ScribException + { + return v.visit(this); + } + + @Override + public ScribNode visitChildren(AstVisitor v) throws ScribException + { + return this; + } + + // Used to be more relevant, previously there was an explicit parent parameter + protected ScribNode visitChild(ScribNode child, AstVisitor v) throws ScribException + { + return v.visit(child); // cf. child.accept(v) ? + } + + // FIXME: remove parent parameter, to make uniform with visitChild + // Used when a generic cast would otherwise be needed (non-generic children casts don't need this) -- doesn't check any generic parameters, relies on concrete values being instances of non-parameterised types + // Subtype constraint on visited could still be too restrictive, e.g. AmbigNameNodeDel (although it doesn't matter there), e.g. unfolding continue's into recursion's + protected final static T visitChildWithClassEqualityCheck( + ScribNode parent, T child, AstVisitor v) throws ScribException + { + ScribNode visited = ((ScribNodeBase) parent).visitChild(child, v); + // Same subtyping flexibility as standard cast + return ScribNodeUtil.checkNodeClassEquality(child, visited); + } + + protected final static List + visitChildListWithClassEqualityCheck( + ScribNode parent, List children, AstVisitor v) + throws ScribException + { + return visitChildListWith(parent, children, v, + (T t) -> ScribUtil.handleLambdaScribbleException( + () -> ScribNodeBase + .visitChildWithClassEqualityCheck(parent, t, v))); // -> T + } + + // Just a list-map with handling for promoted exceptions (via handleLambdaScribbleException) -- could move to Util (where handleLambdaScribbleException is) + private final static List visitChildListWith( + ScribNode parent, List children, AstVisitor nv, Function c) + throws ScribException + { + /*List visited = new LinkedList<>(); + for (T n : children) + { + visited.add(c.call()); + } + return visited;*/ + // Maybe the below exception hack is not worth it? Simpler to throw directly as ScribbleException, as above + try + { + return children.stream().map(x -> c.apply(x)) + .collect(Collectors.toList()); + } + catch (RuntimeScribException rse) + { + Throwable cause = rse.getCause(); + if (cause instanceof ScribException) + { + throw (ScribException) cause; + } + throw (RuntimeException) cause; + } + } + + + // Following would fit better in ProtocolKindNode, except it is an interface + + // Takes clazz+kind to handle generic ProtocolKindNodes -- cf. ScribUtil.castNodeByClass, for casting to ground class types + // R is expected to be N, i.e. the generic (ProtocolKindNode) class N parameterised by K + protected final static , K extends ProtoKind, + R extends ProtoKindNode> + R visitProtocolKindChildWithCastCheck( + ScribNode parent, ScribNode child, AstVisitor nv, Class clazz, K kind, + Function cast) throws ScribException + { + ScribNode visited = ((ScribNodeBase) parent).visitChild(child, nv); + if (!clazz.isAssignableFrom(visited.getClass())) + { + throw new RuntimeException(nv.getClass() + " generic visit error: " + + clazz + ", " + visited.getClass()); + } + ProtoKindNode pkn = (ProtoKindNode) visited; + if ((pkn.isGlobal() && !kind.equals(Global.KIND)) + || (pkn.isLocal() && !kind.equals(Local.KIND))) + { + throw new RuntimeException(nv.getClass() + " generic visit error: " + + pkn.getClass() + ", " + kind); + } + return cast.apply(pkn); + } + + protected final static , + K extends ProtoKind, R extends ProtoKindNode> + List visitProtocolKindChildListWithCastCheck( + ScribNode parent, List children, AstVisitor nv, Class c, K k, + Function f) throws ScribException + { + return visitChildListWith(parent, children, nv, + (T t) -> ScribUtil.handleLambdaScribbleException( + () -> ScribNodeBase + .visitProtocolKindChildWithCastCheck(parent, t, nv, c, k, f))); + // -> R + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/SessionNode.java b/scribble-ast/src/main/java/org/scribble/ast/SessionNode.java new file mode 100644 index 000000000..38c2ab63e --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/SessionNode.java @@ -0,0 +1,23 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast; + +import org.scribble.core.type.kind.ProtoKind; + +// A SessionNode is an AST node that corresponds to a session type constructor -- elements of InteractionSeq nodes +// The SessionNodeDel hierarchy corresponds to this SessionNode hierarchy +public interface SessionNode extends ProtoKindNode +{ + +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/SigDecl.java b/scribble-ast/src/main/java/org/scribble/ast/SigDecl.java new file mode 100644 index 000000000..692a3cbb6 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/SigDecl.java @@ -0,0 +1,85 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast; + +import org.antlr.runtime.Token; +import org.scribble.ast.name.qualified.SigNameNode; +import org.scribble.core.type.kind.SigKind; +import org.scribble.core.type.name.ModuleName; +import org.scribble.core.type.name.SigName; +import org.scribble.del.DelFactory; +import org.scribble.util.Constants; + +public class SigDecl extends NonProtoDecl +{ + // ScribTreeAdaptor#create constructor + public SigDecl(Token payload) + { + super(payload); + } + + // Tree#dupNode constructor + protected SigDecl(SigDecl node) + { + super(node); + } + + @Override + public SigNameNode getNameNodeChild() + { + return (SigNameNode) getRawNameNodeChild(); + } + + // Cf. CommonTree#dupNode + @Override + public SigDecl dupNode() + { + return new SigDecl(this); + } + + @Override + public void decorateDel(DelFactory df) + { + df.SigDecl(this); + } + + @Override + public boolean isSigDecl() + { + return true; + } + + @Override + public SigName getDeclName() + { + return getNameNodeChild().toName(); + } + + @Override + public SigName getFullMemberName(Module mod) + { + ModuleName fullmodname = mod.getFullModuleName(); + return new SigName(fullmodname, getDeclName()); + } + + @Override + public String toString() + { + return Constants.SIG_KW + " <" + getSchemaChild() + "> " + + getExtNameChild() + " " + + Constants.FROM_KW + " " + getExtSourceChild() + " " + + Constants.AS_KW + " " + getDeclName() + + ";"; + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/SigLitNode.java b/scribble-ast/src/main/java/org/scribble/ast/SigLitNode.java new file mode 100644 index 000000000..b7d31ee32 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/SigLitNode.java @@ -0,0 +1,111 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast; + +import org.antlr.runtime.Token; +import org.scribble.ast.name.simple.OpNode; +import org.scribble.core.type.session.SigLit; +import org.scribble.del.DelFactory; +import org.scribble.util.ScribException; +import org.scribble.visit.AstVisitor; + +public class SigLitNode extends ScribNodeBase implements MsgNode +{ + public static final int OP_CHILD_INDEX = 0; + public static final int PAYLOAD_CHILD_INDEX = 1; + + // ScribTreeAdaptor#create constructor + public SigLitNode(Token t) + { + super(t); + } + + // Tree#dupNode constructor + public SigLitNode(SigLitNode node) + { + super(node); + } + + public OpNode getOpChild() + { + return (OpNode) getChild(OP_CHILD_INDEX); + } + + public PayElemList getPayloadListChild() + { + return (PayElemList) getChild(PAYLOAD_CHILD_INDEX); + } + + // "add", not "set" + public void addScribChildren(OpNode op, PayElemList pay) + { + addChild(op); + addChild(pay); + } + + @Override + public SigLitNode dupNode() + { + return new SigLitNode(this); + } + + @Override + public void decorateDel(DelFactory df) + { + df.SigLitNode(this); + } + + public SigLitNode reconstruct(OpNode op, PayElemList pay) + { + SigLitNode dup = dupNode(); + dup.addScribChildren(op, pay); + dup.setDel(del()); // No copy + return dup; + } + + @Override + public SigLitNode visitChildren(AstVisitor nv) throws ScribException + { + OpNode op = (OpNode) visitChild(getOpChild(), nv); + PayElemList pay = (PayElemList) + visitChild(getPayloadListChild(), nv); + return reconstruct(op, pay); + } + + @Override + public boolean isSigLitNode() + { + return true; + } + + // Make a direct scoped version? (taking scope as argument) + @Override + public SigLit toArg() + { + return new SigLit(getOpChild().toName(), + getPayloadListChild().toPayload()); + } + + @Override + public SigLit toMsg() + { + return toArg(); + } + + @Override + public String toString() + { + return getOpChild().toString() + getPayloadListChild().toString(); + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/SigParamDecl.java b/scribble-ast/src/main/java/org/scribble/ast/SigParamDecl.java new file mode 100644 index 000000000..d5c868699 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/SigParamDecl.java @@ -0,0 +1,67 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast; + +import org.antlr.runtime.Token; +import org.scribble.ast.name.simple.SigParamNode; +import org.scribble.core.type.kind.SigKind; +import org.scribble.core.type.name.SigName; +import org.scribble.del.DelFactory; +import org.scribble.util.Constants; + +public class SigParamDecl extends NonRoleParamDecl +{ + // ScribTreeAdaptor#create constructor + public SigParamDecl(Token t) + { + super(t, SigKind.KIND); + } + + // Tree#dupNode constructor + public SigParamDecl(SigParamDecl node) + { + super(node); + } + + @Override + public SigParamNode getNameNodeChild() + { + return (SigParamNode) getRawNameNodeChild(); // CHECKME: make Type/Sig(Param)Node? + } + + @Override + public SigParamDecl dupNode() + { + return new SigParamDecl(this); + } + + @Override + public void decorateDel(DelFactory df) + { + df.SigParamDecl(this); + } + + @Override + //public MemberName getDeclName() + public SigName getDeclName() + { + return (SigName) getNameNodeChild().toName(); + } + + @Override + public String getKeyword() + { + return Constants.SIG_KW; + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/SimpleSessionNode.java b/scribble-ast/src/main/java/org/scribble/ast/SimpleSessionNode.java new file mode 100644 index 000000000..e64bc5692 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/SimpleSessionNode.java @@ -0,0 +1,34 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast; + +import org.antlr.runtime.Token; +import org.scribble.core.type.kind.ProtoKind; + +// Name should be read (Simple ( SessionNode )) +public abstract class SimpleSessionNode + extends ScribNodeBase implements SessionNode +{ + // ScribTreeAdaptor#create constructor + public SimpleSessionNode(Token t) + { + super(t); + } + + // Tree#dupNode constructor + public SimpleSessionNode(SimpleSessionNode node) + { + super(node); + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/UnaryPayElem.java b/scribble-ast/src/main/java/org/scribble/ast/UnaryPayElem.java new file mode 100644 index 000000000..8066acbfc --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/UnaryPayElem.java @@ -0,0 +1,110 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast; + +import org.antlr.runtime.Token; +import org.scribble.ast.name.PayElemNameNode; +import org.scribble.core.type.kind.PayElemKind; +import org.scribble.core.type.name.PayElemType; +import org.scribble.del.DelFactory; +import org.scribble.util.ScribException; +import org.scribble.visit.AstVisitor; + + +// TODO: make abstract, and make a DataTypeElem subclass with DataTypeKind parameter instance (alongside LDelegationElem) + +// FIXME: refactor: generic typing issues, no concrete name field any more +// Cf. DoArg, wrapper for a (unary) name node of potentially unknown kind (needs disamb) +// PayloadTypeKind is DataType or Local, but Local has its own special subclass (and protocol params not allowed), so this should implicitly be for DataType only +// AST hierarchy requires unary and delegation (binary pair) payloads to be structurally distinguished +//public class DataTypeElem extends PayloadElem +public class UnaryPayElem extends ScribNodeBase + implements PayElem// extends PayloadElem +{ + // cf. Scribble.g + public static final int NAME_CHILD_INDEX = 0; + + // ScribTreeAdaptor#create constructor + public UnaryPayElem(Token t) + { + super(t); + } + + // Tree#dupNode constructor + public UnaryPayElem(UnaryPayElem node) + { + super(node); + } + + public PayElemNameNode getNameChild() + { + // FIXME + PayElemNameNode name = (PayElemNameNode) getChild(NAME_CHILD_INDEX); + // CHECKME: probably need to record an explicit kind token, for "cast checking" + // Cannot use ScribNodeBase.visitChildWithCastCheck because this is not a ProtocolKindNode + return name; + } + + // "add", not "set" + public void addScribChildren(PayElemNameNode name) + { + // Cf. above getters and Scribble.g children order + addChild(name); + } + + @Override + public UnaryPayElem dupNode() + { + return new UnaryPayElem<>(this); + } + + @Override + public void decorateDel(DelFactory df) + { + df.UnaryPayElem(this); + } + + public UnaryPayElem reconstruct(PayElemNameNode name) + { + UnaryPayElem dup = dupNode(); + dup.addScribChildren(name); + dup.setDel(del()); // No copy + return dup; + } + + @Override + public UnaryPayElem visitChildren(AstVisitor nv) + throws ScribException + { + @SuppressWarnings("unchecked") + PayElemNameNode name = (PayElemNameNode) visitChild( + getNameChild(), nv); + // CHECKME: probably need to record an explicit kind token, for "cast checking" + // Cannot use ScribNodeBase.visitChildWithCastCheck because this is not a ProtocolKindNode + return reconstruct(name); + } + + @Override + public PayElemType toPayloadType() + { + return getNameChild().toPayloadType(); + } + + @Override + public String toString() + { + return getNameChild().toString(); + } +} + diff --git a/scribble-ast/src/main/java/org/scribble/ast/WrapAction.java b/scribble-ast/src/main/java/org/scribble/ast/WrapAction.java new file mode 100644 index 000000000..60b2b4eef --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/WrapAction.java @@ -0,0 +1,73 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast; + +import java.util.List; + +import org.antlr.runtime.Token; +import org.scribble.ast.name.simple.RoleNode; +import org.scribble.core.type.kind.ProtoKind; + +public abstract class WrapAction + extends DirectedInteraction +{ + // ScribTreeAdaptor#create constructor + public WrapAction(Token t) + { + super(t); + } + + // Tree#dupNode constructor + public WrapAction(WrapAction node) + { + super(node); + } + + public RoleNode getClientChild() + { + return (RoleNode) getSourceChild(); + } + + public RoleNode getServerChild() + { + return getDestinationChild(); + } + + // Cf. ConnectAction + public RoleNode getDestinationChild() + { + List dests = getDestinationChildren(); + if (dests.size() != 1) + { + throw new RuntimeException("Shouldn't get in here: " + this); + // CHECKME: don't use common src/dst pattern between global/local? + } + return dests.get(0); + } + + @Override + public void addScribChildren(MsgNode msg, RoleNode src, List dsts) + { + throw new RuntimeException("Unsupported for LWrapAction: " + msg); + } + + // "add", not "set" + // "Overrides" DirectedInteraction::addScribChildren + public void addScribChildren(RoleNode client, RoleNode server) + { + // Cf. above getters and Scribble.g children order + addChild(client); + addChild(server); + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/global/GChoice.java b/scribble-ast/src/main/java/org/scribble/ast/global/GChoice.java new file mode 100644 index 000000000..c0fe600cc --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/global/GChoice.java @@ -0,0 +1,58 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast.global; + +import java.util.List; +import java.util.stream.Collectors; + +import org.antlr.runtime.Token; +import org.scribble.ast.Choice; +import org.scribble.ast.ScribNode; +import org.scribble.core.type.kind.Global; +import org.scribble.del.DelFactory; + +public class GChoice extends Choice implements GCompoundSessionNode +{ + // ScribTreeAdaptor#create constructor + public GChoice(Token t) + { + super(t); + } + + // Tree#dupNode constructor + protected GChoice(GChoice node) + { + super(node); + } + + @Override + public List getBlockChildren() + { + List cs = getChildren(); + return cs.subList(Choice.BLOCK_CHILDREN_START_INDEX, cs.size()).stream() + .map(x -> (GProtoBlock) x).collect(Collectors.toList()); + } + + @Override + public GChoice dupNode() + { + return new GChoice(this); + } + + @Override + public void decorateDel(DelFactory df) + { + df.GChoice(this); + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/global/GCompoundSessionNode.java b/scribble-ast/src/main/java/org/scribble/ast/global/GCompoundSessionNode.java new file mode 100644 index 000000000..07306a52c --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/global/GCompoundSessionNode.java @@ -0,0 +1,19 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast.global; + +public interface GCompoundSessionNode extends GSessionNode +{ + +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/global/GConnect.java b/scribble-ast/src/main/java/org/scribble/ast/global/GConnect.java new file mode 100644 index 000000000..b43e652bb --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/global/GConnect.java @@ -0,0 +1,57 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast.global; + +import org.antlr.runtime.Token; +import org.scribble.ast.ConnectAction; +import org.scribble.core.type.kind.Global; +import org.scribble.del.DelFactory; +import org.scribble.util.Constants; + +// TODO: make GConnectionAction and factor this class with GWrap (cf. LConnectionAction) +public class GConnect extends ConnectAction + implements GSimpleSessionNode +{ + // ScribTreeAdaptor#create constructor + public GConnect(Token t) + { + super(t); + } + + // Tree#dupNode constructor + public GConnect(GConnect node) + { + super(node); + } + + @Override + public GConnect dupNode() + { + return new GConnect(this); + } + + @Override + public void decorateDel(DelFactory df) + { + df.GConnect(this); + } + + @Override + public String toString() + { + return (isUnitMessage() ? "" : getMessageNodeChild() + " ") + + Constants.CONNECT_KW + " " + getSourceChild() + " " + Constants.TO_KW + + " " + getDestinationChild() + ";"; + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/global/GContinue.java b/scribble-ast/src/main/java/org/scribble/ast/global/GContinue.java new file mode 100644 index 000000000..6957bde1b --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/global/GContinue.java @@ -0,0 +1,46 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast.global; + +import org.antlr.runtime.Token; +import org.scribble.ast.Continue; +import org.scribble.core.type.kind.Global; +import org.scribble.del.DelFactory; + +public class GContinue extends Continue implements GSimpleSessionNode +{ + // ScribTreeAdaptor#create constructor + public GContinue(Token t) + { + super(t); + } + + // Tree#dupNode constructor + protected GContinue(GContinue node) + { + super(node); + } + + @Override + public GContinue dupNode() + { + return new GContinue(this); + } + + @Override + public void decorateDel(DelFactory df) + { + df.GContinue(this); + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/global/GDelegPayElem.java b/scribble-ast/src/main/java/org/scribble/ast/global/GDelegPayElem.java new file mode 100644 index 000000000..4ad4614aa --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/global/GDelegPayElem.java @@ -0,0 +1,114 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast.global; + +import org.antlr.runtime.Token; +import org.scribble.ast.PayElem; +import org.scribble.ast.ScribNodeBase; +import org.scribble.ast.name.qualified.GProtoNameNode; +import org.scribble.ast.name.simple.RoleNode; +import org.scribble.core.type.kind.Local; +import org.scribble.core.type.name.GDelegType; +import org.scribble.core.type.name.PayElemType; +import org.scribble.del.DelFactory; +import org.scribble.util.ScribException; +import org.scribble.visit.AstVisitor; + +// A "name pair" payload elem (current AST hierarchy induces this pattern), cf. UnaryPayloadElem (also differs in no parsing ambig against parameters) +// The this.name will be global kind, but overall this node is local kind +//public class DelegationElem extends PayloadElem +public class GDelegPayElem extends ScribNodeBase implements PayElem +{ + public static final int PROTO_CHILD_INDEX = 0; + public static final int ROLE_CHILD_INDEX = 1; + + // ScribTreeAdaptor#create constructor + public GDelegPayElem(Token t) + { + super(t); + } + + // Tree#dupNode constructor + public GDelegPayElem(GDelegPayElem node) + { + super(node); + } + + // Becomes full name after disambiguation + public GProtoNameNode getProtocolChild() + { + return (GProtoNameNode) getChild(PROTO_CHILD_INDEX); + } + + public RoleNode getRoleChild() + { + return (RoleNode) getChild(ROLE_CHILD_INDEX); + } + + // "add", not "set" + public void addScribChildren(GProtoNameNode proto, RoleNode role) + { + // Cf. above getters and Scribble.g children order + addChild(proto); + addChild(role); + } + + @Override + public GDelegPayElem dupNode() + { + return new GDelegPayElem(this); + } + + @Override + public void decorateDel(DelFactory df) + { + df.GDelegPayElem(this); + } + + public GDelegPayElem reconstruct(GProtoNameNode proto, RoleNode role) + { + GDelegPayElem dup = dupNode(); + dup.addScribChildren(proto, role); + dup.setDel(del()); // No copy + return dup; + } + + @Override + public GDelegPayElem visitChildren(AstVisitor nv) throws ScribException + { + GProtoNameNode name = (GProtoNameNode) + visitChild(getProtocolChild(), nv); + RoleNode role = (RoleNode) visitChild(getRoleChild(), nv); + return reconstruct(name, role); + } + + @Override + public boolean isGlobalDelegationElem() + { + return true; + } + + @Override + public PayElemType toPayloadType() + { + return new GDelegType(getProtocolChild().toName(), + getRoleChild().toName()); + } + + @Override + public String toString() + { + return getProtocolChild() + "@" + getRoleChild(); + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/global/GDisconnect.java b/scribble-ast/src/main/java/org/scribble/ast/global/GDisconnect.java new file mode 100644 index 000000000..a324f4aac --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/global/GDisconnect.java @@ -0,0 +1,47 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast.global; + +import org.antlr.runtime.Token; +import org.scribble.ast.DisconnectAction; +import org.scribble.core.type.kind.Global; +import org.scribble.del.DelFactory; + +public class GDisconnect extends DisconnectAction + implements GSimpleSessionNode +{ + // ScribTreeAdaptor#create constructor + public GDisconnect(Token t) + { + super(t); + } + + // Tree#dupNode constructor + public GDisconnect(GDisconnect node) + { + super(node); + } + + @Override + public void decorateDel(DelFactory df) + { + df.GDisconnect(this); + } + + @Override + public GDisconnect dupNode() + { + return new GDisconnect(this); + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/global/GDo.java b/scribble-ast/src/main/java/org/scribble/ast/global/GDo.java new file mode 100644 index 000000000..c00216659 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/global/GDo.java @@ -0,0 +1,71 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast.global; + +import org.antlr.runtime.Token; +import org.scribble.ast.Do; +import org.scribble.ast.name.qualified.GProtoNameNode; +import org.scribble.core.lang.context.ModuleContext; +import org.scribble.core.type.kind.Global; +import org.scribble.core.type.name.GProtoName; +import org.scribble.del.DelFactory; +import org.scribble.job.JobContext; + +public class GDo extends Do implements GSimpleSessionNode +{ + // ScribTreeAdaptor#create constructor + public GDo(Token t) + { + super(t); + } + + // Tree#dupNode constructor + public GDo(GDo node) + { + super(node); + } + + @Override + public GProtoNameNode getProtocolNameNode() + { + return (GProtoNameNode) getChild(Do.NAME_CHILD_INDEX); + } + + @Override + public GProtoDecl getTargetProtocolDecl(JobContext jobc, + ModuleContext modc) + { + GProtoName fullname = getTargetProtoDeclFullName(modc); + return jobc.getModule(fullname.getPrefix()) + .getGProtocolDeclChild(fullname.getSimpleName()); + } + + @Override + public GDo dupNode() + { + return new GDo(this); + } + + @Override + public void decorateDel(DelFactory df) + { + df.GDo(this); + } + + @Override + public GProtoName getTargetProtoDeclFullName(ModuleContext modc) + { + return (GProtoName) super.getTargetProtoDeclFullName(modc); + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/global/GInteractionSeq.java b/scribble-ast/src/main/java/org/scribble/ast/global/GInteractionSeq.java new file mode 100644 index 000000000..88435a816 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/global/GInteractionSeq.java @@ -0,0 +1,57 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast.global; + +import java.util.List; +import java.util.stream.Collectors; + +import org.antlr.runtime.Token; +import org.scribble.ast.InteractionSeq; +import org.scribble.core.type.kind.Global; +import org.scribble.del.DelFactory; + +public class GInteractionSeq extends InteractionSeq + implements GScribNode +{ + // ScribTreeAdaptor#create constructor + public GInteractionSeq(Token t) + { + super(t); + } + + // Tree#dupNode constructor + public GInteractionSeq(GInteractionSeq node) + { + super(node); + } + + @Override + public List getInteractionChildren() + { + return getChildren().stream().map(n -> (GSessionNode) n) + .collect(Collectors.toList()); + } + + @Override + public GInteractionSeq dupNode() + { + return new GInteractionSeq(this); + } + + @Override + public void decorateDel(DelFactory df) + { + df.GInteractionSeq(this); + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/global/GMsgTransfer.java b/scribble-ast/src/main/java/org/scribble/ast/global/GMsgTransfer.java new file mode 100644 index 000000000..dfc90632c --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/global/GMsgTransfer.java @@ -0,0 +1,61 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast.global; + +import java.util.stream.Collectors; + +import org.antlr.runtime.Token; +import org.scribble.ast.MsgTransfer; +import org.scribble.core.type.kind.Global; +import org.scribble.del.DelFactory; +import org.scribble.util.Constants; + +public class GMsgTransfer extends MsgTransfer + implements GSimpleSessionNode +{ + // ScribTreeAdaptor#create constructor + public GMsgTransfer(Token t) + { + super(t); + } + + // Tree#dupNode constructor + public GMsgTransfer(GMsgTransfer node) + { + super(node); + } + + @Override + public GMsgTransfer dupNode() + { + return new GMsgTransfer(this); + } + + @Override + public void decorateDel(DelFactory df) + { + df.GMsgTransfer(this); + } + + @Override + public String toString() + { + return getMessageNodeChild() + " " + Constants.FROM_KW + + " " + getSourceChild() + " " + Constants.TO_KW + + " " + + getDestinationChildren().stream().map(x -> x.toString()) + .collect(Collectors.joining(", ")) + + ";"; + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/global/GProtoBlock.java b/scribble-ast/src/main/java/org/scribble/ast/global/GProtoBlock.java new file mode 100644 index 000000000..0ff579d50 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/global/GProtoBlock.java @@ -0,0 +1,52 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast.global; + +import org.antlr.runtime.Token; +import org.scribble.ast.ProtoBlock; +import org.scribble.core.type.kind.Global; +import org.scribble.del.DelFactory; + +public class GProtoBlock extends ProtoBlock implements GScribNode +{ + // ScribTreeAdaptor#create constructor + public GProtoBlock(Token t) + { + super(t); + } + + // Tree#dupNode constructor + protected GProtoBlock(GProtoBlock node) + { + super(node); + } + + @Override + public GInteractionSeq getInteractSeqChild() + { + return (GInteractionSeq) getChild(ProtoBlock.SEQ_CHILD_INDEX); + } + + @Override + public GProtoBlock dupNode() + { + return new GProtoBlock(this); + } + + @Override + public void decorateDel(DelFactory df) + { + df.GProtoBlock(this); + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/global/GProtoDecl.java b/scribble-ast/src/main/java/org/scribble/ast/global/GProtoDecl.java new file mode 100644 index 000000000..aac0be95c --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/global/GProtoDecl.java @@ -0,0 +1,69 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast.global; + +import org.antlr.runtime.Token; +import org.scribble.ast.Module; +import org.scribble.ast.ProtoDecl; +import org.scribble.core.type.kind.Global; +import org.scribble.core.type.name.GProtoName; +import org.scribble.del.DelFactory; + +public class GProtoDecl extends ProtoDecl implements GScribNode +{ + // ScribTreeAdaptor#create constructor + public GProtoDecl(Token t) + { + super(t); + } + + // Tree#dupNode constructor + protected GProtoDecl(GProtoDecl node) + { + super(node); + } + + @Override + public GProtoHeader getHeaderChild() + { + return (GProtoHeader) getChild(ProtoDecl.HEADER_CHILD); + } + + @Override + public GProtoDef getDefChild() + { + return (GProtoDef) getChild(ProtoDecl.DEF_CHILD); + } + + // Cf. CommonTree#dupNode + @Override + public GProtoDecl dupNode() + { + return new GProtoDecl(this); + } + + @Override + public void decorateDel(DelFactory df) + { + df.GProtoDecl(this); + } + + @Override + public GProtoName getFullMemberName(Module mod) // TODO: remove mod from meth sig + { + Module m = (Module) getParent(); + return new GProtoName(m.getFullModuleName(), + getHeaderChild().getDeclName()); + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/global/GProtoDef.java b/scribble-ast/src/main/java/org/scribble/ast/global/GProtoDef.java new file mode 100644 index 000000000..6f656425f --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/global/GProtoDef.java @@ -0,0 +1,52 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast.global; + +import org.antlr.runtime.Token; +import org.scribble.ast.ProtoDef; +import org.scribble.core.type.kind.Global; +import org.scribble.del.DelFactory; + +public class GProtoDef extends ProtoDef implements GScribNode +{ + // ScribTreeAdaptor#create constructor + public GProtoDef(Token t) + { + super(t); + } + + // Tree#dupNode constructor + protected GProtoDef(GProtoDef node) + { + super(node); + } + + @Override + public GProtoBlock getBlockChild() + { + return (GProtoBlock) getChild(ProtoDef.BLOCK_CHILD_INDEX); + } + + @Override + public GProtoDef dupNode() + { + return new GProtoDef(this); + } + + @Override + public void decorateDel(DelFactory df) + { + df.GProtoDef(this); + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/global/GProtoHeader.java b/scribble-ast/src/main/java/org/scribble/ast/global/GProtoHeader.java new file mode 100644 index 000000000..affbe1ff5 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/global/GProtoHeader.java @@ -0,0 +1,67 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast.global; + +import org.antlr.runtime.Token; +import org.scribble.ast.ProtoHeader; +import org.scribble.ast.name.qualified.GProtoNameNode; +import org.scribble.core.type.kind.Global; +import org.scribble.core.type.name.GProtoName; +import org.scribble.del.DelFactory; +import org.scribble.util.Constants; + +public class GProtoHeader extends ProtoHeader implements GScribNode +{ + // ScribTreeAdaptor#create constructor + public GProtoHeader(Token t) + { + super(t); + } + + // Tree#dupNode constructor + protected GProtoHeader(GProtoHeader node) + { + super(node); + } + + @Override + public GProtoHeader dupNode() + { + return new GProtoHeader(this); + } + + @Override + public void decorateDel(DelFactory df) + { + df.GProtoHeader(this); + } + + @Override + public GProtoNameNode getNameNodeChild() + { + return (GProtoNameNode) getRawNameNodeChild(); + } + + @Override + public GProtoName getDeclName() + { + return (GProtoName) super.getDeclName(); + } + + @Override + public String toString() + { + return Constants.GLOBAL_KW + " " + super.toString(); + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/global/GRecursion.java b/scribble-ast/src/main/java/org/scribble/ast/global/GRecursion.java new file mode 100644 index 000000000..3f1f76159 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/global/GRecursion.java @@ -0,0 +1,54 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast.global; + +import org.antlr.runtime.Token; +import org.scribble.ast.Recursion; +import org.scribble.core.type.kind.Global; +import org.scribble.del.DelFactory; + + +public class GRecursion extends Recursion + implements GCompoundSessionNode +{ + // ScribTreeAdaptor#create constructor + public GRecursion(Token t) + { + super(t); + } + + // Tree#dupNode constructor + protected GRecursion(GRecursion node) + { + super(node); + } + + @Override + public GProtoBlock getBlockChild() + { + return (GProtoBlock) getChild(Recursion.BODY_CHILD_INDEX); + } + + @Override + public GRecursion dupNode() + { + return new GRecursion(this); + } + + @Override + public void decorateDel(DelFactory df) + { + df.GRecursion(this); + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/global/GScribNode.java b/scribble-ast/src/main/java/org/scribble/ast/global/GScribNode.java new file mode 100644 index 000000000..74d175207 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/global/GScribNode.java @@ -0,0 +1,32 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast.global; + +import org.scribble.ast.ProtoKindNode; +import org.scribble.core.type.kind.Global; + +public interface GScribNode extends ProtoKindNode +{ + @Override + default boolean isGlobal() + { + return true; + } + + @Override + default Global getKind() + { + return Global.KIND; + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/global/GSessionNode.java b/scribble-ast/src/main/java/org/scribble/ast/global/GSessionNode.java new file mode 100644 index 000000000..f5268b1aa --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/global/GSessionNode.java @@ -0,0 +1,23 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast.global; + +import org.scribble.ast.SessionNode; +import org.scribble.core.type.kind.Global; + +// Alternatively to interface, use GlobalNode subclass with delegation to "super" base (e.g. Choice) classes +public interface GSessionNode extends SessionNode, GScribNode +{ + //public LInteractionSeq project(AstFactory af, Role self); // TODO +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/global/GSimpleSessionNode.java b/scribble-ast/src/main/java/org/scribble/ast/global/GSimpleSessionNode.java new file mode 100644 index 000000000..7088f7993 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/global/GSimpleSessionNode.java @@ -0,0 +1,19 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast.global; + +public interface GSimpleSessionNode extends GSessionNode +{ + +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/global/GWrap.java b/scribble-ast/src/main/java/org/scribble/ast/global/GWrap.java new file mode 100644 index 000000000..162afc363 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/global/GWrap.java @@ -0,0 +1,75 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast.global; + +import org.antlr.runtime.Token; +import org.scribble.ast.WrapAction; +import org.scribble.ast.name.simple.RoleNode; +import org.scribble.core.type.kind.Global; +import org.scribble.del.DelFactory; +import org.scribble.util.Constants; +import org.scribble.util.ScribException; +import org.scribble.visit.AstVisitor; + +// TODO: factor out base Wrap (cf. Disconnect) -- Wrap is a ConnectionAction? +public class GWrap extends WrapAction + implements GSimpleSessionNode +{ + // ScribTreeAdaptor#create constructor + public GWrap(Token t) + { + super(t); + } + + // Tree#dupNode constructor + public GWrap(GWrap node) + { + super(node); + } + + @Override + public GWrap dupNode() + { + return new GWrap(this); + } + + @Override + public void decorateDel(DelFactory df) + { + df.GWrap(this); + } + + public GWrap reconstruct(RoleNode client, RoleNode server) + { + GWrap n = dupNode(); + n.addScribChildren(client, server); + n.setDel(del()); // No copy + return n; + } + + @Override + public GWrap visitChildren(AstVisitor nv) throws ScribException + { + RoleNode src = (RoleNode) visitChild(getClientChild(), nv); + RoleNode dest = (RoleNode) visitChild(getServerChild(), nv); + return reconstruct(src, dest); + } + + @Override + public String toString() + { + return Constants.WRAP_KW + " " + getClientChild() + + " " + Constants.TO_KW + " " + getServerChild() + ";"; + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/local/LAcc.java b/scribble-ast/src/main/java/org/scribble/ast/local/LAcc.java new file mode 100644 index 000000000..2a9874041 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/local/LAcc.java @@ -0,0 +1,66 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast.local; + +import org.antlr.runtime.Token; +import org.scribble.ast.name.simple.RoleNode; +import org.scribble.del.DelFactory; +import org.scribble.util.Constants; + +public class LAcc extends LConnectAction implements LSimpleSessionNode +{ + // ScribTreeAdaptor#create constructor + public LAcc(Token t) + { + super(t); + } + + // Tree#dupNode constructor + public LAcc(LAcc node) + { + super(node); + } + + // CHECKME: factor out implementations with LRecv as default methods + @Override + public RoleNode getSelfChild() + { + return getDestinationChild(); // CHECKME: don't use common src/dst pattern between global/local? + } + + @Override + public RoleNode getPeerChild() + { + return getSourceChild(); + } + + @Override + public LAcc dupNode() + { + return new LAcc(this); + } + + @Override + public void decorateDel(DelFactory df) + { + df.LAcc(this); + } + + @Override + public String toString() + { + return (isUnitMessage() ? "" : getMessageNodeChild() + " ") // TODO: deprecate ommitted "()" special case + + Constants.ACCEPT_KW + " " + getSourceChild() + ";"; + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/local/LChoice.java b/scribble-ast/src/main/java/org/scribble/ast/local/LChoice.java new file mode 100644 index 000000000..b2d04b8cf --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/local/LChoice.java @@ -0,0 +1,58 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast.local; + +import java.util.List; +import java.util.stream.Collectors; + +import org.antlr.runtime.Token; +import org.scribble.ast.Choice; +import org.scribble.ast.ScribNode; +import org.scribble.core.type.kind.Local; +import org.scribble.del.DelFactory; + +public class LChoice extends Choice implements LCompoundSessionNode +{ + // ScribTreeAdaptor#create constructor + public LChoice(Token t) + { + super(t); + } + + // Tree#dupNode constructor + protected LChoice(LChoice node) + { + super(node); + } + + @Override + public List getBlockChildren() + { + List cs = getChildren(); + return cs.subList(Choice.BLOCK_CHILDREN_START_INDEX, cs.size()).stream() + .map(x -> (LProtoBlock) x).collect(Collectors.toList()); + } + + @Override + public LChoice dupNode() + { + return new LChoice(this); + } + + @Override + public void decorateDel(DelFactory df) + { + df.LChoice(this); + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/local/LClientWrap.java b/scribble-ast/src/main/java/org/scribble/ast/local/LClientWrap.java new file mode 100644 index 000000000..d80e4617b --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/local/LClientWrap.java @@ -0,0 +1,86 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast.local; + +import org.antlr.runtime.Token; +import org.scribble.ast.name.simple.RoleNode; +import org.scribble.del.DelFactory; +import org.scribble.util.Constants; +import org.scribble.util.ScribException; +import org.scribble.visit.AstVisitor; + +public class LClientWrap extends LWrapAction + implements LSimpleSessionNode +{ + // ScribTreeAdaptor#create constructor + public LClientWrap(Token t) + { + super(t); + } + + // Tree#dupNode constructor + public LClientWrap(LClientWrap node) + { + super(node); + } + + // CHECKME: factor out implementations with LSend as default methods + @Override + public RoleNode getSelfChild() + { + return getSourceChild(); + } + + @Override + public RoleNode getPeerChild() + { + return getDestinationChild(); // Multi-connect/req not supported + } + + @Override + public LClientWrap dupNode() + { + return new LClientWrap(this); + } + + @Override + public void decorateDel(DelFactory df) + { + df.LClientWrap(this); + } + + // TODO: factor out a base + public LClientWrap reconstruct(RoleNode client, RoleNode server) + { + LClientWrap n = dupNode(); + n.addScribChildren(client, server); + n.setDel(del()); // No copy + return n; + } + + // TODO: factor out a base + @Override + public LClientWrap visitChildren(AstVisitor nv) throws ScribException + { + RoleNode src = (RoleNode) visitChild(getClientChild(), nv); + RoleNode dest = (RoleNode) visitChild(getClientChild(), nv); + return reconstruct(src, dest); + } + + @Override + public String toString() + { + return Constants.CLIENTWRAP_KW + getServerChild() + ";"; + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/local/LCompoundSessionNode.java b/scribble-ast/src/main/java/org/scribble/ast/local/LCompoundSessionNode.java new file mode 100644 index 000000000..3072c52ab --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/local/LCompoundSessionNode.java @@ -0,0 +1,19 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast.local; + +public interface LCompoundSessionNode extends LSessionNode +{ + +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/local/LConnectAction.java b/scribble-ast/src/main/java/org/scribble/ast/local/LConnectAction.java new file mode 100644 index 000000000..7c7348f88 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/local/LConnectAction.java @@ -0,0 +1,39 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast.local; + +import org.antlr.runtime.Token; +import org.scribble.ast.ConnectAction; +import org.scribble.ast.name.simple.RoleNode; +import org.scribble.core.type.kind.Local; + +public abstract class LConnectAction extends ConnectAction + implements LSimpleSessionNode +{ + // ScribTreeAdaptor#create constructor + public LConnectAction(Token t) + { + super(t); + } + + // Tree#dupNode constructor + public LConnectAction(LConnectAction node) + { + super(node); + } + + // CHECKME: make an LDirectedAction interface? cf. LMsgTransfer -- CHECKME: factor out implementations as default methods with Send/Recv? + public abstract RoleNode getSelfChild(); // Post: "self" RoleNode + public abstract RoleNode getPeerChild(); +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/local/LContinue.java b/scribble-ast/src/main/java/org/scribble/ast/local/LContinue.java new file mode 100644 index 000000000..8b79ddd56 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/local/LContinue.java @@ -0,0 +1,46 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast.local; + +import org.antlr.runtime.Token; +import org.scribble.ast.Continue; +import org.scribble.core.type.kind.Local; +import org.scribble.del.DelFactory; + +public class LContinue extends Continue implements LSimpleSessionNode +{ + // ScribTreeAdaptor#create constructor + public LContinue(Token t) + { + super(t); + } + + // Tree#dupNode constructor + protected LContinue(LContinue node) + { + super(node); + } + + @Override + public LContinue dupNode() + { + return new LContinue(this); + } + + @Override + public void decorateDel(DelFactory df) + { + df.LContinue(this); + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/local/LDelegElem.java b/scribble-ast/src/main/java/org/scribble/ast/local/LDelegElem.java new file mode 100644 index 000000000..f78393a1d --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/local/LDelegElem.java @@ -0,0 +1,47 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast.local; + +import org.antlr.runtime.Token; +import org.scribble.ast.UnaryPayElem; +import org.scribble.core.type.kind.Local; +import org.scribble.del.DelFactory; + +// N.B. extends UnaryPayloadElem, not DelegationElem +public class LDelegElem extends UnaryPayElem +{ + // ScribTreeAdaptor#create constructor + public LDelegElem(Token t) + { + super(t); + } + + // Tree#dupNode constructor + public LDelegElem(LDelegElem node) + { + super(node); + } + + @Override + public LDelegElem dupNode() + { + return new LDelegElem(this); + } + + @Override + public void decorateDel(DelFactory df) + { + throw new RuntimeException("TODO: " + this); + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/local/LDisconnect.java b/scribble-ast/src/main/java/org/scribble/ast/local/LDisconnect.java new file mode 100644 index 000000000..cc529195d --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/local/LDisconnect.java @@ -0,0 +1,66 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast.local; + +import org.antlr.runtime.Token; +import org.scribble.ast.DisconnectAction; +import org.scribble.ast.name.simple.RoleNode; +import org.scribble.core.type.kind.Local; +import org.scribble.del.DelFactory; +import org.scribble.util.Constants; + +public class LDisconnect extends DisconnectAction + implements LSimpleSessionNode +{ + // ScribTreeAdaptor#create constructor + public LDisconnect(Token t) + { + super(t); + } + + // Tree#dupNode constructor + public LDisconnect(LDisconnect node) + { + super(node); + } + + // Cf. core LDisconnect + public RoleNode getSelfChild() + { + return getLeftChild(); + } + + public RoleNode getPeerChild() + { + return getRightChild(); + } + + @Override + public void decorateDel(DelFactory df) + { + df.LDisconnect(this); + } + + @Override + public LDisconnect dupNode() + { + return new LDisconnect(this); + } + + @Override + public String toString() + { + return Constants.DISCONNECT_KW + " " + getRightChild() + ";"; // FIXME: make explicit, using right as peer (cf. core.type) + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/local/LDo.java b/scribble-ast/src/main/java/org/scribble/ast/local/LDo.java new file mode 100644 index 000000000..14da7ab36 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/local/LDo.java @@ -0,0 +1,72 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast.local; + +import org.antlr.runtime.Token; +import org.scribble.ast.Do; +import org.scribble.ast.name.qualified.LProtoNameNode; +import org.scribble.core.lang.context.ModuleContext; +import org.scribble.core.type.kind.Local; +import org.scribble.core.type.name.LProtoName; +import org.scribble.del.DelFactory; +import org.scribble.job.JobContext; + +public class LDo extends Do implements LSimpleSessionNode +{ + + // ScribTreeAdaptor#create constructor + public LDo(Token t) + { + super(t); + } + + // Tree#dupNode constructor + public LDo(LDo node) + { + super(node); + } + + @Override + public LProtoNameNode getProtocolNameNode() + { + return (LProtoNameNode) getChild(Do.NAME_CHILD_INDEX); + } + + @Override + public LProtoDecl getTargetProtocolDecl(JobContext jobc, + ModuleContext modc) + { + LProtoName fullname = getTargetProtoDeclFullName(modc); + return jobc.getModule(fullname.getPrefix()) + .getLProtocolDeclChild(fullname.getSimpleName()); + } + + @Override + public LDo dupNode() + { + return new LDo(this); + } + + @Override + public void decorateDel(DelFactory df) + { + df.LDo(this); + } + + @Override + public LProtoName getTargetProtoDeclFullName(ModuleContext modc) + { + return (LProtoName) super.getTargetProtoDeclFullName(modc); + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/local/LInteractionSeq.java b/scribble-ast/src/main/java/org/scribble/ast/local/LInteractionSeq.java new file mode 100644 index 000000000..d2be6a0c4 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/local/LInteractionSeq.java @@ -0,0 +1,57 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast.local; + +import java.util.List; +import java.util.stream.Collectors; + +import org.antlr.runtime.Token; +import org.scribble.ast.InteractionSeq; +import org.scribble.core.type.kind.Local; +import org.scribble.del.DelFactory; + +public class LInteractionSeq extends InteractionSeq + implements LSessionNode +{ + // ScribTreeAdaptor#create constructor + public LInteractionSeq(Token t) + { + super(t); + } + + // Tree#dupNode constructor + public LInteractionSeq(LInteractionSeq node) + { + super(node); + } + + @Override + public List getInteractionChildren() + { + return getChildren().stream().map(n -> (LSessionNode) n) + .collect(Collectors.toList()); + } + + @Override + public LInteractionSeq dupNode() + { + return new LInteractionSeq(this); + } + + @Override + public void decorateDel(DelFactory df) + { + df.LInteractionSeq(this); + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/local/LMsgTransfer.java b/scribble-ast/src/main/java/org/scribble/ast/local/LMsgTransfer.java new file mode 100644 index 000000000..20bfd4dd2 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/local/LMsgTransfer.java @@ -0,0 +1,39 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast.local; + +import org.antlr.runtime.Token; +import org.scribble.ast.MsgTransfer; +import org.scribble.ast.name.simple.RoleNode; +import org.scribble.core.type.kind.Local; + +public abstract class LMsgTransfer extends MsgTransfer + implements LSimpleSessionNode +{ + // ScribTreeAdaptor#create constructor + public LMsgTransfer(Token t) + { + super(t); + } + + // Tree#dupNode constructor + public LMsgTransfer(LMsgTransfer node) + { + super(node); + } + + // CHECKME: make an LDirectedAction interface? cf. LConnectAction -- CHECKME: factor out implementations as default methods with Acc/Req? + public abstract RoleNode getSelfChild(); // Post: "self" RoleNode + public abstract RoleNode getPeerChild(); +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/local/LProjectionDecl.java b/scribble-ast/src/main/java/org/scribble/ast/local/LProjectionDecl.java new file mode 100644 index 000000000..0baa89b71 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/local/LProjectionDecl.java @@ -0,0 +1,87 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast.local; + +import org.antlr.runtime.Token; +import org.scribble.ast.ProtoDef; +import org.scribble.ast.ProtoHeader; +import org.scribble.ast.ProtoModList; +import org.scribble.ast.name.qualified.GProtoNameNode; +import org.scribble.ast.name.simple.RoleNode; +import org.scribble.core.type.kind.Local; +import org.scribble.del.DelFactory; + +public class LProjectionDecl extends LProtoDecl +{ + // Continues on from ProtoDecl, cf. ProtoDecl.DEF_CHILD + public static final int GLOBAL_CHILD = 3; // Cf. "parent", confusing with Antlr + public static final int SELF_CHILD = 4; + + //public final GProtoName parent; // FIXME: additional ast child? + + // ScribTreeAdaptor#create constructor + public LProjectionDecl(Token t) + { + super(t); + } + + // Tree#dupNode constructor + protected LProjectionDecl(LProtoDecl node) + { + super(node); + } + + public GProtoNameNode getGlobalChild() + { + return (GProtoNameNode) getChild(GLOBAL_CHILD); + } + + public RoleNode getSelfChild() + { + return (RoleNode) getChild(SELF_CHILD); + } + + // "add", not "set" + public void addScribChildren(ProtoModList mods, ProtoHeader header, + ProtoDef def, GProtoNameNode global, RoleNode self) + { + // Cf. above getters and Scribble.g children order + super.addScribChildren(mods, header, def); + addChild(global); + addChild(self); + } + + // Cf. CommonTree#dupNode + @Override + public LProtoDecl dupNode() + { + return new LProtoDecl(this); + } + + @Override + public void decorateDel(DelFactory df) + { + df.LProjectionDecl(this); + } + + @Override + public String toString() + { + // Duplicated from ProtoDecl + ProtoModList mods = getModifierListChild(); + return (mods.isEmpty() ? "" : mods + " ") + getHeaderChild() + " " // FIXME: self role decl (cf. LProtocol.rolesToString) + + "projects " + getGlobalChild() + " " // Cf. core.lang.local.LProjection + + getDefChild(); + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/local/LProtoBlock.java b/scribble-ast/src/main/java/org/scribble/ast/local/LProtoBlock.java new file mode 100644 index 000000000..591ea878a --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/local/LProtoBlock.java @@ -0,0 +1,52 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast.local; + +import org.antlr.runtime.Token; +import org.scribble.ast.ProtoBlock; +import org.scribble.core.type.kind.Local; +import org.scribble.del.DelFactory; + +public class LProtoBlock extends ProtoBlock implements LScribNode +{ + // ScribTreeAdaptor#create constructor + public LProtoBlock(Token t) + { + super(t); + } + + // Tree#dupNode constructor + protected LProtoBlock(LProtoBlock node) + { + super(node); + } + + @Override + public LInteractionSeq getInteractSeqChild() + { + return (LInteractionSeq) getChild(ProtoBlock.SEQ_CHILD_INDEX); + } + + @Override + public LProtoBlock dupNode() + { + return new LProtoBlock(this); + } + + @Override + public void decorateDel(DelFactory df) + { + df.LProtoBlock(this); + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/local/LProtoDecl.java b/scribble-ast/src/main/java/org/scribble/ast/local/LProtoDecl.java new file mode 100644 index 000000000..e06ded600 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/local/LProtoDecl.java @@ -0,0 +1,70 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast.local; + +import org.antlr.runtime.Token; +import org.scribble.ast.Module; +import org.scribble.ast.ProtoDecl; +import org.scribble.core.type.kind.Local; +import org.scribble.core.type.name.LProtoName; +import org.scribble.del.DelFactory; + +// Maybe make abstract with concrete parsed (LParsedDecl) and projected (LProjectionDecl) subclasses +public class LProtoDecl extends ProtoDecl implements LSessionNode +{ + // ScribTreeAdaptor#create constructor + public LProtoDecl(Token t) + { + super(t); + } + + // Tree#dupNode constructor + protected LProtoDecl(LProtoDecl node) + { + super(node); + } + + @Override + public LProtoHeader getHeaderChild() + { + return (LProtoHeader) getChild(ProtoDecl.HEADER_CHILD); + } + + @Override + public LProtoDef getDefChild() + { + return (LProtoDef) getChild(ProtoDecl.DEF_CHILD); + } + + // Cf. CommonTree#dupNode + @Override + public LProtoDecl dupNode() + { + return new LProtoDecl(this); + } + + @Override + public void decorateDel(DelFactory df) + { + df.LProtoDecl(this); + } + + @Override + public LProtoName getFullMemberName(Module mod) // TODO: remove mod from meth sig + { + Module m = (Module) getParent(); + return new LProtoName(m.getFullModuleName(), + getHeaderChild().getDeclName()); + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/local/LProtoDef.java b/scribble-ast/src/main/java/org/scribble/ast/local/LProtoDef.java new file mode 100644 index 000000000..8e98afdcd --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/local/LProtoDef.java @@ -0,0 +1,52 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast.local; + +import org.antlr.runtime.Token; +import org.scribble.ast.ProtoDef; +import org.scribble.core.type.kind.Local; +import org.scribble.del.DelFactory; + +public class LProtoDef extends ProtoDef implements LSessionNode +{ + // ScribTreeAdaptor#create constructor + public LProtoDef(Token t) + { + super(t); + } + + // Tree#dupNode constructor + protected LProtoDef(LProtoDef node) + { + super(node); + } + + @Override + public LProtoBlock getBlockChild() + { + return (LProtoBlock) getChild(ProtoDef.BLOCK_CHILD_INDEX); + } + + @Override + public LProtoDef dupNode() + { + return new LProtoDef(this); + } + + @Override + public void decorateDel(DelFactory df) + { + df.LProtoDef(this); + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/local/LProtoHeader.java b/scribble-ast/src/main/java/org/scribble/ast/local/LProtoHeader.java new file mode 100644 index 000000000..ccb64f5c3 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/local/LProtoHeader.java @@ -0,0 +1,67 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast.local; + +import org.antlr.runtime.Token; +import org.scribble.ast.ProtoHeader; +import org.scribble.ast.name.qualified.LProtoNameNode; +import org.scribble.core.type.kind.Local; +import org.scribble.core.type.name.LProtoName; +import org.scribble.del.DelFactory; +import org.scribble.util.Constants; + +public class LProtoHeader extends ProtoHeader implements LSessionNode +{ + // ScribTreeAdaptor#create constructor + public LProtoHeader(Token t) + { + super(t); + } + + // Tree#dupNode constructor + protected LProtoHeader(LProtoHeader node) + { + super(node); + } + + @Override + public LProtoHeader dupNode() + { + return new LProtoHeader(this); + } + + @Override + public void decorateDel(DelFactory df) + { + df.LProtoHeader(this); + } + + @Override + public LProtoNameNode getNameNodeChild() + { + return (LProtoNameNode) getRawNameNodeChild(); + } + + @Override + public LProtoName getDeclName() + { + return (LProtoName) super.getDeclName(); + } + + @Override + public String toString() + { + return Constants.LOCAL_KW + " " + super.toString(); + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/local/LRecursion.java b/scribble-ast/src/main/java/org/scribble/ast/local/LRecursion.java new file mode 100644 index 000000000..e806db82b --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/local/LRecursion.java @@ -0,0 +1,52 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast.local; + +import org.antlr.runtime.Token; +import org.scribble.ast.Recursion; +import org.scribble.core.type.kind.Local; +import org.scribble.del.DelFactory; + +public class LRecursion extends Recursion implements LCompoundSessionNode +{ + // ScribTreeAdaptor#create constructor + public LRecursion(Token t) + { + super(t); + } + + // Tree#dupNode constructor + protected LRecursion(LRecursion node) + { + super(node); + } + + @Override + public LProtoBlock getBlockChild() + { + return (LProtoBlock) getChild(Recursion.BODY_CHILD_INDEX); + } + + @Override + public LRecursion dupNode() + { + return new LRecursion(this); + } + + @Override + public void decorateDel(DelFactory df) + { + df.LRecursion(this); + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/local/LRecv.java b/scribble-ast/src/main/java/org/scribble/ast/local/LRecv.java new file mode 100644 index 000000000..74efffc98 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/local/LRecv.java @@ -0,0 +1,72 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast.local; + +import java.util.List; + +import org.antlr.runtime.Token; +import org.scribble.ast.name.simple.RoleNode; +import org.scribble.del.DelFactory; +import org.scribble.util.Constants; + +public class LRecv extends LMsgTransfer +{ + // ScribTreeAdaptor#create constructor + public LRecv(Token t) + { + super(t); + } + + // Tree#dupNode constructor + public LRecv(LRecv node) + { + super(node); + } + + @Override + public RoleNode getSelfChild() + { + List dsts = getDestinationChildren(); + if (dsts.size() > 1) + { + throw new RuntimeException("Shouldn't get in here: " + this); // CHECKME: don't use common src/dst pattern between global/local? + } + return dsts.get(0); + } + + @Override + public RoleNode getPeerChild() + { + return getSourceChild(); + } + + @Override + public LRecv dupNode() + { + return new LRecv(this); + } + + @Override + public void decorateDel(DelFactory df) + { + df.LRecv(this); + } + + @Override + public String toString() + { + return getMessageNodeChild() + " " + Constants.FROM_KW + " " + + getSourceChild() + ";"; + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/local/LReq.java b/scribble-ast/src/main/java/org/scribble/ast/local/LReq.java new file mode 100644 index 000000000..5ec85e2d3 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/local/LReq.java @@ -0,0 +1,66 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast.local; + +import org.antlr.runtime.Token; +import org.scribble.ast.name.simple.RoleNode; +import org.scribble.del.DelFactory; +import org.scribble.util.Constants; + +public class LReq extends LConnectAction implements LSimpleSessionNode +{ + // ScribTreeAdaptor#create constructor + public LReq(Token t) + { + super(t); + } + + // Tree#dupNode constructor + public LReq(LReq node) + { + super(node); + } + + // CHECKME: factor out implementations with LSend as default methods + @Override + public RoleNode getSelfChild() + { + return getSourceChild(); + } + + @Override + public RoleNode getPeerChild() + { + return getDestinationChild(); // Multi-connect/req not supported + } + + @Override + public LReq dupNode() + { + return new LReq(this); + } + + @Override + public void decorateDel(DelFactory df) + { + df.LReq(this); + } + + @Override + public String toString() + { + return (isUnitMessage() ? "" : getMessageNodeChild() + " ") // TODO: deprecate ommitted "()" special case + + Constants.REQUEST_KW + " " + getDestinationChild() + ";"; + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/local/LScribNode.java b/scribble-ast/src/main/java/org/scribble/ast/local/LScribNode.java new file mode 100644 index 000000000..ada5ec403 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/local/LScribNode.java @@ -0,0 +1,32 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast.local; + +import org.scribble.ast.ProtoKindNode; +import org.scribble.core.type.kind.Local; + +public interface LScribNode extends ProtoKindNode +{ + @Override + default boolean isLocal() + { + return true; + } + + @Override + default Local getKind() + { + return Local.KIND; + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/local/LSelfDecl.java b/scribble-ast/src/main/java/org/scribble/ast/local/LSelfDecl.java new file mode 100644 index 000000000..4782a36a4 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/local/LSelfDecl.java @@ -0,0 +1,52 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast.local; + +import org.antlr.runtime.Token; +import org.scribble.ast.RoleDecl; +import org.scribble.del.DelFactory; +import org.scribble.util.Constants; + +public class LSelfDecl extends RoleDecl +{ + // ScribTreeAdaptor#create constructor + public LSelfDecl(Token t) + { + super(t); + } + + // Tree#dupNode constructor + public LSelfDecl(LSelfDecl node) + { + super(node); + } + + @Override + public LSelfDecl dupNode() + { + return new LSelfDecl(this); + } + + @Override + public void decorateDel(DelFactory df) + { + df.LSelfDecl(this); + } + + @Override + public String getKeyword() + { + return Constants.SELF_KW; // Main reason for this subclass; overriding various toStrings awkward + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/local/LSend.java b/scribble-ast/src/main/java/org/scribble/ast/local/LSend.java new file mode 100644 index 000000000..eb8c8a254 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/local/LSend.java @@ -0,0 +1,76 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast.local; + +import java.util.List; +import java.util.stream.Collectors; + +import org.antlr.runtime.Token; +import org.scribble.ast.name.simple.RoleNode; +import org.scribble.del.DelFactory; +import org.scribble.util.Constants; + +public class LSend extends LMsgTransfer +{ + // ScribTreeAdaptor#create constructor + public LSend(Token t) + { + super(t); + } + + // Tree#dupNode constructor + public LSend(LSend node) + { + super(node); + } + + @Override + public RoleNode getSelfChild() + { + return getSourceChild(); + } + + @Override + public RoleNode getPeerChild() + { + List dsts = getDestinationChildren(); + if (dsts.size() > 1) + { + throw new RuntimeException("[TODO] Multi-send: " + this); + } + return dsts.get(0); + } + + @Override + public LSend dupNode() + { + return new LSend(this); + } + + @Override + public void decorateDel(DelFactory df) + { + df.LSend(this); + } + + @Override + public String toString() + { + return getMessageNodeChild() + " " + Constants.TO_KW + + " " + + getDestinationChildren().stream().map(x -> x.toString()) + .collect(Collectors.joining(", ")) + + ";"; + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/local/LServerWrap.java b/scribble-ast/src/main/java/org/scribble/ast/local/LServerWrap.java new file mode 100644 index 000000000..2656bd785 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/local/LServerWrap.java @@ -0,0 +1,87 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast.local; + +import org.antlr.runtime.Token; +import org.scribble.ast.name.simple.RoleNode; +import org.scribble.del.DelFactory; +import org.scribble.util.Constants; +import org.scribble.util.ScribException; +import org.scribble.visit.AstVisitor; + +// TODO: factor out base Wrap (cf. Disconnect) +public class LServerWrap extends LWrapAction + implements LSimpleSessionNode +{ + // ScribTreeAdaptor#create constructor + public LServerWrap(Token t) + { + super(t); + } + + // Tree#dupNode constructor + public LServerWrap(LServerWrap node) + { + super(node); + } + + // CHECKME: factor out implementations with LRecv as default methods + @Override + public RoleNode getSelfChild() + { + return getDestinationChild(); // CHECKME: don't use common src/dst pattern between global/local? + } + + @Override + public RoleNode getPeerChild() + { + return getSourceChild(); + } + + @Override + public LServerWrap dupNode() + { + return new LServerWrap(this); + } + + @Override + public void decorateDel(DelFactory df) + { + df.LServerWrap(this); + } + + // TODO: factor out a base + public LServerWrap reconstruct(RoleNode client, RoleNode server) + { + LServerWrap n = dupNode(); + n.addScribChildren(client, server); + n.setDel(del()); // No copy + return n; + } + + // TODO: factor out a base + @Override + public LServerWrap visitChildren(AstVisitor nv) throws ScribException + { + RoleNode src = (RoleNode) visitChild(getClientChild(), nv); + RoleNode dest = (RoleNode) visitChild(getServerChild(), nv); + return reconstruct(src, dest); + } + + @Override + public String toString() + { + return Constants.SERVERWRAP_KW + " " + getClientChild() + ";"; + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/local/LSessionNode.java b/scribble-ast/src/main/java/org/scribble/ast/local/LSessionNode.java new file mode 100644 index 000000000..c4b1c07bd --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/local/LSessionNode.java @@ -0,0 +1,32 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast.local; + +import org.scribble.ast.SessionNode; +import org.scribble.core.type.kind.Local; + +public interface LSessionNode extends SessionNode, LScribNode +{ + @Override + default boolean isLocal() + { + return true; + } + + @Override + default Local getKind() + { + return Local.KIND; + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/local/LSimpleSessionNode.java b/scribble-ast/src/main/java/org/scribble/ast/local/LSimpleSessionNode.java new file mode 100644 index 000000000..88861cd57 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/local/LSimpleSessionNode.java @@ -0,0 +1,19 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast.local; + +public interface LSimpleSessionNode extends LSessionNode +{ + +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/local/LWrapAction.java b/scribble-ast/src/main/java/org/scribble/ast/local/LWrapAction.java new file mode 100644 index 000000000..b233e5a84 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/local/LWrapAction.java @@ -0,0 +1,38 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast.local; + +import org.antlr.runtime.Token; +import org.scribble.ast.WrapAction; +import org.scribble.ast.name.simple.RoleNode; +import org.scribble.core.type.kind.Local; + +public abstract class LWrapAction extends WrapAction +{ + // ScribTreeAdaptor#create constructor + public LWrapAction(Token t) + { + super(t); + } + + // Tree#dupNode constructor + public LWrapAction(LWrapAction node) + { + super(node); + } + + // CHECKME: make an LDirectedAction interface? cf. LMsgTransfer -- CHECKME: factor out implementations as default methods with Send/Recv? + public abstract RoleNode getSelfChild(); // Post: "self" RoleNode + public abstract RoleNode getPeerChild(); +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/name/NameNode.java b/scribble-ast/src/main/java/org/scribble/ast/name/NameNode.java new file mode 100644 index 000000000..70c4a2689 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/name/NameNode.java @@ -0,0 +1,119 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast.name; + +import java.util.List; +import java.util.stream.Collectors; + +import org.antlr.runtime.Token; +import org.scribble.ast.ScribNodeBase; +import org.scribble.ast.name.simple.IdNode; +import org.scribble.core.type.kind.Kind; +import org.scribble.core.type.name.Named; + +// Children are IdNode elements (each IdNode records a String text element) +// Kind parameter used for typing help, but NameNodes don't record kind as state (not part of the syntax) -- so kind doesn't affect e.g. equals (i.e. name nodes of different kinds are still only compared syntactically) +public abstract class NameNode extends ScribNodeBase + implements Named +{ + // ScribTreeAdaptor#create constructor + public NameNode(Token t) + { + super(t); + } + + // Tree#dupNode constructor + protected NameNode(NameNode node) + { + super(node); + } + + @Override + public List getChildren() + { + return super.getChildren().stream().map(x -> (IdNode) x) + .collect(Collectors.toList()); + } + + public abstract NameNode dupNode(); + + // Factored abstractly from getChildren, for SimpleNameNode to override (SimpleNameNode has no children) + public List getElements() + { + return getChildren().stream() + .map(x -> x.getText()).collect(Collectors.toList()); + } + + protected final List getPrefixElements() + { + List elems = getElements(); + return elems.subList(0, elems.size()-1); + } + + protected final String getLastElement() + { + List names = getElements(); + return names.get(names.size() - 1); + } + + public int getElementCount() + { + return getChildCount(); + } + + public boolean isEmpty() + { + return getElementCount() == 0; + } + + protected boolean isPrefixed() + { + return getElementCount() > 1; + } + + @Override + public String toString() + { + return toName().toString(); + } + + // CHECKME: is equals/hashCode actually needed for these ScribNodes? (cf. Name) + // CHECKME: should NameNodes ever be used in an equality checking context? (cf. other AST nodes) -- this work should be done using sesstype.Name instead? + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof NameNode)) + { + return false; + } + NameNode them = (NameNode) o; + return them.canEquals(this) + && getElements().equals(them.getElements()); + } + + public abstract boolean canEquals(Object o); + + @Override + public int hashCode() + { + int hash = 317; + hash = 31 * hash + getElements().hashCode(); + // Hash the String values, not the actual Tree nodes + return hash; + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/name/PayElemNameNode.java b/scribble-ast/src/main/java/org/scribble/ast/name/PayElemNameNode.java new file mode 100644 index 000000000..3a5017168 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/name/PayElemNameNode.java @@ -0,0 +1,30 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast.name; + +import org.scribble.ast.NonRoleArgNode; +import org.scribble.core.type.kind.PayElemKind; +import org.scribble.core.type.name.PayElemType; + + +// A datatype kind node: DataTypeNode or NonRoleParameterNode -- not necessarily simple nor qualified +// Actually, datatype or global protocol kind, if delegation supported -- for "structural delegation" this would not directly be a name node any more (like MessageNode) +//public interface PayloadElemNameNode extends NonRoleArgNode +public interface PayElemNameNode extends NonRoleArgNode +{ + //PayloadType toPayloadType(); + //PayloadType toPayloadType(); // Currently can assume the only possible kind is DataTypeKind (delegation is by (non-ambig) delegationelem) + //PayloadType toPayloadType(); // FIXME: generic parameter for kind (data/local) + PayElemType toPayloadType(); +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/name/qualified/DataNameNode.java b/scribble-ast/src/main/java/org/scribble/ast/name/qualified/DataNameNode.java new file mode 100644 index 000000000..667936ddd --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/name/qualified/DataNameNode.java @@ -0,0 +1,106 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast.name.qualified; + +import org.antlr.runtime.Token; +import org.scribble.ast.name.PayElemNameNode; +import org.scribble.core.type.kind.DataKind; +import org.scribble.core.type.name.DataName; +import org.scribble.core.type.session.Arg; +import org.scribble.del.DelFactory; + +//public class DataTypeNode extends MemberNameNode implements PayloadElemNameNode +public class DataNameNode extends MemberNameNode + implements PayElemNameNode +{ + // ScribTreeAdaptor#create constructor + public DataNameNode(Token t) + { + super(t); + } + + // Tree#dupNode constructor + protected DataNameNode(DataNameNode node) + { + super(node); + } + + @Override + public DataNameNode dupNode() + { + return new DataNameNode(this); + } + + @Override + public void decorateDel(DelFactory df) + { + df.DataNameNode(this); + } + + @Override + public DataName toName() + { + DataName membname = new DataName(getLastElement()); + return isPrefixed() + ? new DataName(getModuleNamePrefix(), membname) + : membname; + } + + @Override + public boolean isDataNameNode() + { + return true; + } + + @Override + public Arg toArg() + { + return toPayloadType(); + } + + @Override + public DataName toPayloadType() + { + return toName(); + } + + // CHECKME: is equals/hashCode actually needed for these ScribNodes? (cf. Name) + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof DataNameNode)) + { + return false; + } + return ((DataNameNode) o).canEquals(this) && super.equals(o); + } + + @Override + public boolean canEquals(Object o) + { + return o instanceof DataNameNode; + } + + @Override + public int hashCode() + { + int hash = 409; + hash = 31 * hash + super.hashCode(); + return hash; + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/name/qualified/GProtoNameNode.java b/scribble-ast/src/main/java/org/scribble/ast/name/qualified/GProtoNameNode.java new file mode 100644 index 000000000..dd46e4ee7 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/name/qualified/GProtoNameNode.java @@ -0,0 +1,83 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast.name.qualified; + +import org.antlr.runtime.Token; +import org.scribble.core.type.kind.Global; +import org.scribble.core.type.name.GProtoName; +import org.scribble.del.DelFactory; + +public class GProtoNameNode extends ProtoNameNode +{ + // ScribTreeAdaptor#create constructor + public GProtoNameNode(Token t) + { + super(t); + } + + // Tree#dupNode constructor + public GProtoNameNode(GProtoNameNode node) + { + super(node); + } + + @Override + public GProtoNameNode dupNode() + { + return new GProtoNameNode(this); + } + + @Override + public void decorateDel(DelFactory df) + { + df.GProtoNameNode(this); + } + + @Override + public GProtoName toName() + { + GProtoName membname = new GProtoName(getLastElement()); + return isPrefixed() + ? new GProtoName(getModuleNamePrefix(), membname) + : membname; + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof GProtoNameNode)) + { + return false; + } + return ((GProtoNameNode) o).canEquals(this) && super.equals(o); + } + + @Override + public boolean canEquals(Object o) + { + return o instanceof GProtoNameNode; + } + + @Override + public int hashCode() + { + int hash = 419; + hash = 31 * hash + super.hashCode(); + return hash; + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/name/qualified/LProtoNameNode.java b/scribble-ast/src/main/java/org/scribble/ast/name/qualified/LProtoNameNode.java new file mode 100644 index 000000000..e74077bb8 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/name/qualified/LProtoNameNode.java @@ -0,0 +1,98 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast.name.qualified; + +import org.antlr.runtime.Token; +import org.scribble.ast.name.PayElemNameNode; +import org.scribble.core.type.kind.Local; +import org.scribble.core.type.name.LProtoName; +import org.scribble.core.type.session.Arg; +import org.scribble.del.DelFactory; + +public class LProtoNameNode extends ProtoNameNode + implements PayElemNameNode +{ + // ScribTreeAdaptor#create constructor + public LProtoNameNode(Token t) + { + super(t); + } + + // Tree#dupNode constructor + protected LProtoNameNode(LProtoNameNode node) + { + super(node); + } + + @Override + public LProtoNameNode dupNode() + { + return new LProtoNameNode(this); + } + + @Override + public void decorateDel(DelFactory df) + { + df.LProtoNameNode(this); + } + + @Override + public LProtoName toName() + { + LProtoName membname = new LProtoName(getLastElement()); + return isPrefixed() + ? new LProtoName(getModuleNamePrefix(), membname) + : membname; + } + + @Override + public LProtoName toPayloadType() + { + return toName(); + } + + @Override + public Arg toArg() + { + return toPayloadType(); + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof LProtoNameNode)) + { + return false; + } + return super.equals(o); // Does canEqual + } + + @Override + public boolean canEquals(Object o) + { + return o instanceof LProtoNameNode; + } + + @Override + public int hashCode() + { + int hash = 421; + hash = 31 * hash + super.hashCode(); + return hash; + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/name/qualified/MemberNameNode.java b/scribble-ast/src/main/java/org/scribble/ast/name/qualified/MemberNameNode.java new file mode 100644 index 000000000..fcd7e8391 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/name/qualified/MemberNameNode.java @@ -0,0 +1,52 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast.name.qualified; + +import java.util.Arrays; +import java.util.List; + +import org.antlr.runtime.Token; +import org.scribble.core.type.kind.Kind; +import org.scribble.core.type.name.ModuleName; +import org.scribble.core.type.name.PackageName; + +public abstract class MemberNameNode + extends QualNameNode +{ + // ScribTreeAdaptor#create constructor + public MemberNameNode(Token t) + { + super(t); + } + + // Tree#dupNode constructor + protected MemberNameNode(MemberNameNode node) + { + super(node); + } + + protected ModuleName getModuleNamePrefix() + { + List prefix = getPrefixElements(); + ModuleName mn = new ModuleName(prefix.get(prefix.size()-1)); + if (prefix.size() == 1) + { + return mn; + } + return new ModuleName( + new PackageName( + Arrays.copyOf(prefix.toArray(new String[0]), prefix.size() - 1)), + mn); + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/name/qualified/ModuleNameNode.java b/scribble-ast/src/main/java/org/scribble/ast/name/qualified/ModuleNameNode.java new file mode 100644 index 000000000..2c80a0b81 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/name/qualified/ModuleNameNode.java @@ -0,0 +1,86 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast.name.qualified; + +import org.antlr.runtime.Token; +import org.scribble.core.type.kind.ModuleKind; +import org.scribble.core.type.name.ModuleName; +import org.scribble.core.type.name.PackageName; +import org.scribble.del.DelFactory; + +public class ModuleNameNode extends QualNameNode +{ + // ScribTreeAdaptor#create constructor + public ModuleNameNode(Token t) + { + super(t); + } + + // Tree#dupNode constructor + protected ModuleNameNode(ModuleNameNode node) + { + super(node); + } + + @Override + public ModuleNameNode dupNode() + { + return new ModuleNameNode(this); + } + + @Override + public void decorateDel(DelFactory df) + { + df.ModuleNameNode(this); + } + + @Override + public ModuleName toName() + { + ModuleName modname = new ModuleName(getLastElement()); + return isPrefixed() + ? new ModuleName( + new PackageName(getPrefixElements().toArray(new String[0])), + modname) + : modname; + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof ModuleNameNode)) + { + return false; + } + return ((ModuleNameNode) o).canEquals(this) && super.equals(o); + } + + @Override + public boolean canEquals(Object o) + { + return o instanceof ModuleNameNode; + } + + @Override + public int hashCode() + { + int hash = 409; + hash = 31 * hash + super.hashCode(); + return hash; + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/name/qualified/ProtoNameNode.java b/scribble-ast/src/main/java/org/scribble/ast/name/qualified/ProtoNameNode.java new file mode 100644 index 000000000..0b7722e0a --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/name/qualified/ProtoNameNode.java @@ -0,0 +1,36 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast.name.qualified; + +import org.antlr.runtime.Token; +import org.scribble.core.type.kind.ProtoKind; +import org.scribble.core.type.name.ProtoName; + +public abstract class ProtoNameNode + extends MemberNameNode +{ + // ScribTreeAdaptor#create constructor + public ProtoNameNode(Token t) + { + super(t); + } + + // Tree#dupNode constructor + protected ProtoNameNode(ProtoNameNode node) + { + super(node); + } + + public abstract ProtoName toName(); +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/name/qualified/QualNameNode.java b/scribble-ast/src/main/java/org/scribble/ast/name/qualified/QualNameNode.java new file mode 100644 index 000000000..7e0f92573 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/name/qualified/QualNameNode.java @@ -0,0 +1,34 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast.name.qualified; + +import org.antlr.runtime.Token; +import org.scribble.ast.name.NameNode; +import org.scribble.core.type.kind.Kind; + +// Any name that could be compound/qualified (but could also be a singleton) +public abstract class QualNameNode extends NameNode +{ + // ScribTreeAdaptor#create constructor + public QualNameNode(Token t) + { + super(t); + } + + // Tree#dupNode constructor + protected QualNameNode(QualNameNode node) + { + super(node); + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/name/qualified/SigNameNode.java b/scribble-ast/src/main/java/org/scribble/ast/name/qualified/SigNameNode.java new file mode 100644 index 000000000..162da080e --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/name/qualified/SigNameNode.java @@ -0,0 +1,103 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast.name.qualified; + +import org.antlr.runtime.Token; +import org.scribble.ast.MsgNode; +import org.scribble.core.type.kind.SigKind; +import org.scribble.core.type.name.SigName; +import org.scribble.del.DelFactory; + +public class SigNameNode extends MemberNameNode + implements MsgNode +{ + // ScribTreeAdaptor#create constructor + public SigNameNode(Token t) + { + super(t); + } + + // Tree#dupNode constructor + protected SigNameNode(SigNameNode node) + { + super(node); + } + + @Override + public SigNameNode dupNode() + { + return new SigNameNode(this); + } + + @Override + public void decorateDel(DelFactory df) + { + df.SigNameNode(this); + } + + @Override + public SigName toName() + { + SigName membname = new SigName(getLastElement()); + return isPrefixed() ? new SigName(getModuleNamePrefix(), membname) + : membname; + } + + @Override + public boolean isSigNameNode() + { + return true; + } + + // Difference between toName and toMessage is scope? does that make sense? + @Override + public SigName toMsg() + { + return toName(); + } + + @Override + public SigName toArg() + { + return toMsg(); + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof SigNameNode)) + { + return false; + } + return ((SigNameNode) o).canEquals(this) && super.equals(o); + } + + @Override + public boolean canEquals(Object o) + { + return o instanceof SigNameNode; + } + + @Override + public int hashCode() + { + int hash = 421; + hash = 31 * hash + super.hashCode(); + return hash; + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/name/simple/AmbigNameNode.java b/scribble-ast/src/main/java/org/scribble/ast/name/simple/AmbigNameNode.java new file mode 100644 index 000000000..5c525e9ce --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/name/simple/AmbigNameNode.java @@ -0,0 +1,111 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast.name.simple; + +import org.antlr.runtime.Token; +import org.scribble.ast.MsgNode; +import org.scribble.ast.name.PayElemNameNode; +import org.scribble.core.type.kind.AmbigKind; +import org.scribble.core.type.kind.DataKind; +import org.scribble.core.type.kind.NonRoleArgKind; +import org.scribble.core.type.name.AmbigName; +import org.scribble.core.type.name.PayElemType; +import org.scribble.core.type.session.Arg; +import org.scribble.core.type.session.Msg; +import org.scribble.del.DelFactory; + +// Primitive payload type, MessageSigName or parameter names only: if name is parsed as a CompoundNameNodes, it must be a payload type (not ambiguous in this case) +public class AmbigNameNode extends SimpleNameNode + implements MsgNode, PayElemNameNode // FIXME: currently hardcoded to DataTypeKind for payload elems ? +{ + // Scribble.g, IDENTIFIER<...Node>[$IDENTIFIER] + // N.B. ttype (an "imaginary node" type) is discarded, t is a ScribbleParser.ID token type + public AmbigNameNode(int ttype, Token t) + { + super(t); + } + + // Tree#dupNode constructor + protected AmbigNameNode(AmbigNameNode node) + { + super(node); + } + + @Override + public AmbigNameNode dupNode() + { + return new AmbigNameNode(this); + } + + @Override + public void decorateDel(DelFactory df) + { + df.AmbigNameNode(this); + } + + @Override + public Arg toArg() + { + throw new RuntimeException( + "Ambiguous name node not disambiguated: " + this); + } + + @Override + public Msg toMsg() + { + throw new RuntimeException( + "Ambiguous name node not disambiguated: " + this); + } + + @Override + public PayElemType toPayloadType() // As a payload elem, currently hardcoded to expect only DataTypeKind (protocol payloads not supported) + { + throw new RuntimeException( + "Ambiguous name node not disambiguated: " + this); + } + + @Override + public AmbigName toName() + { + return new AmbigName(getText()); + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof AmbigNameNode)) + { + return false; + } + return ((AmbigNameNode) o).canEquals(this) && super.equals(o); + } + + @Override + public boolean canEquals(Object o) + { + return o instanceof AmbigNameNode; + } + + @Override + public int hashCode() + { + int hash = 3659; + hash = 31 * super.hashCode(); + return hash; + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/name/simple/DataParamNode.java b/scribble-ast/src/main/java/org/scribble/ast/name/simple/DataParamNode.java new file mode 100644 index 000000000..34c9e018a --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/name/simple/DataParamNode.java @@ -0,0 +1,103 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast.name.simple; + +import org.antlr.runtime.Token; +import org.scribble.ast.name.PayElemNameNode; +import org.scribble.core.type.kind.DataKind; +import org.scribble.core.type.name.DataName; +import org.scribble.del.DelFactory; + +public class DataParamNode extends NonRoleParamNode + implements PayElemNameNode // As a payload, can only be a DataType (so hardcode) +{ + // Scribble.g, IDENTIFIER<...Node>[$IDENTIFIER] + // N.B. ttype (an "imaginary node" type) is discarded, t is a ScribbleParser.ID token type + public DataParamNode(int ttype, Token t) + { + super(t, DataKind.KIND); + } + + // Tree#dupNode constructor + protected DataParamNode(DataParamNode node) + { + super(node); + } + + @Override + public DataParamNode dupNode() + { + return new DataParamNode(this); + } + + @Override + public void decorateDel(DelFactory df) + { + df.DataParamNode(this); + } + + // N.B. no "DataParamName" + @Override + public DataName toName() + { + return new DataName(getText()); + } + + @Override + public DataName toArg() + { + // As a payload kind, currently hardcorded to data type kinds (protocol payloads not supported) + return toPayloadType(); + } + + @Override + public DataName toPayloadType() // Currently can assume the only possible kind for NonRoleParamNode is DataTypeKind + { + return toName(); + } + + @Override + public boolean isDataParamNode() + { + return true; + } + + @Override + public int hashCode() + { + int hash = 8599; + hash = 31 * super.hashCode(); + return hash; + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof DataParamNode)) + { + return false; + } + return super.equals(o); + } + + @Override + public boolean canEquals(Object o) + { + return o instanceof DataParamNode; + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/name/simple/ExtIdNode.java b/scribble-ast/src/main/java/org/scribble/ast/name/simple/ExtIdNode.java new file mode 100644 index 000000000..eea5bddf4 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/name/simple/ExtIdNode.java @@ -0,0 +1,67 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast.name.simple; + +import org.antlr.runtime.Token; + +// N.B. without surrounding quotes "..." -- cf. ScribTreeAdaptor.create +// N.B. no del attached, so not currently visited +public class ExtIdNode extends IdNode // CHECKME: e.g., toName gives Id +{ + // ScribTreeAdaptor#create constructor + public ExtIdNode(Token t) + { + super(t); + } + + // Tree#dupNode constructor + protected ExtIdNode(ExtIdNode node) + { + super(node); + } + + @Override + public ExtIdNode dupNode() + { + return new ExtIdNode(this); + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof ExtIdNode)) + { + return false; + } + return ((ExtIdNode) o).canEquals(this) && super.equals(o); + } + + @Override + public boolean canEquals(Object o) + { + return o instanceof ExtIdNode; + } + + @Override + public int hashCode() + { + int hash = 13007; + hash = 31 * super.hashCode(); + return hash; + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/name/simple/IdNode.java b/scribble-ast/src/main/java/org/scribble/ast/name/simple/IdNode.java new file mode 100644 index 000000000..d3122e40a --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/name/simple/IdNode.java @@ -0,0 +1,99 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast.name.simple; + +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.antlr.runtime.Token; +import org.scribble.ast.AstFactory; +import org.scribble.core.type.kind.IdKind; +import org.scribble.core.type.name.Id; +import org.scribble.del.DelFactory; + +// Kind can be disregarded, the "true" kind (for qualified names) recorded by the parent +public class IdNode extends SimpleNameNode +{ + // ScribTreeAdaptor#create constructor + public IdNode(Token t) + { + super(t); + } + + // Tree#dupNode constructor + protected IdNode(IdNode node) + { + super(node); + } + + // CHECKME: move to af? + public static List from(AstFactory af, String[] elems) + { + return Stream.of(elems).map(x -> af.IdNode(null, x)) + .collect(Collectors.toList()); + } + + @Override + public IdNode dupNode() + { + return new IdNode(this); + } + + @Override + public void decorateDel(DelFactory df) + { + df.IdNode(this); + } + + @Override + public String getText() + { + return getToken().getText(); + } + + @Override + public Id toName() + { + return new Id(getText()); + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof IdNode)) + { + return false; + } + return ((IdNode) o).canEquals(this) && super.equals(o); + } + + @Override + public boolean canEquals(Object o) + { + return o instanceof IdNode; + } + + @Override + public int hashCode() + { + int hash = 331; + hash = 31 * super.hashCode(); + return hash; + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/name/simple/NonRoleParamNode.java b/scribble-ast/src/main/java/org/scribble/ast/name/simple/NonRoleParamNode.java new file mode 100644 index 000000000..dae52b068 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/name/simple/NonRoleParamNode.java @@ -0,0 +1,68 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast.name.simple; + +import org.antlr.runtime.Token; +import org.scribble.core.type.kind.NonRoleParamKind; + +// An unambiguous kinded parameter (ambiguous parameters handled by disambiguation) that isn't a role -- e.g. DataType/MessageSigName param +public abstract class NonRoleParamNode extends + SimpleNameNode // As a payload, can only be a DataType (so hardcode) +{ + public final K kind; // CHECKME: still useful, now there are concrete subclasses? + + public NonRoleParamNode(Token t, K kind) + { + super(t); + this.kind = kind; + } + + // Tree#dupNode constructor + protected NonRoleParamNode(NonRoleParamNode node)//, String id) + { + super(node); + this.kind = node.kind; + } + + @Override + public int hashCode() + { + int hash = 317; + hash = 31 * super.hashCode(); + hash = 31 * this.kind.hashCode(); + return hash; + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof NonRoleParamNode)) + { + return false; + } + NonRoleParamNode them = (NonRoleParamNode) o; + return super.equals(o) // Does canEqual + && this.kind.equals(them.kind); + } + + @Override + public boolean canEquals(Object o) + { + return o instanceof NonRoleParamNode; + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/name/simple/OpNode.java b/scribble-ast/src/main/java/org/scribble/ast/name/simple/OpNode.java new file mode 100644 index 000000000..7618f81d7 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/name/simple/OpNode.java @@ -0,0 +1,95 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast.name.simple; + +import org.antlr.runtime.Token; +import org.scribble.core.type.kind.OpKind; +import org.scribble.core.type.name.Op; +import org.scribble.del.DelFactory; + + +public class OpNode extends SimpleNameNode +{ + // Determine by token text -- cannot use token type int in core, value is a ScribbleParser constant + public static final String EMPTY_OP_TOKEN_TEXT = "__EMPTY_OP"; // Cf. Scribble.g + + public OpNode(Token t) + { + super(t); + } + + // Scribble.g, IDENTIFIER<...Node>[$IDENTIFIER] + // ttype is just ScribblParser.IDENTIFIER, t is the IDENTIFIER token + public OpNode(int ttype, Token t) + { + this(t); + } + + // Tree#dupNode constructor + protected OpNode(OpNode node) + { + super(node); + } + + @Override + public OpNode dupNode() + { + return new OpNode(this); + } + + @Override + public void decorateDel(DelFactory df) + { + df.OpNode(this); + } + + @Override + public Op toName() + { + String id = getText(); + if (id.equals(EMPTY_OP_TOKEN_TEXT)) + { + return Op.EMPTY_OP; + } + return new Op(id); + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof OpNode)) + { + return false; + } + return super.equals(o); // Does canEqual + } + + @Override + public boolean canEquals(Object o) + { + return o instanceof OpNode; + } + + @Override + public int hashCode() + { + int hash = 347; + hash = 31 * super.hashCode(); + return hash; + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/name/simple/RecVarNode.java b/scribble-ast/src/main/java/org/scribble/ast/name/simple/RecVarNode.java new file mode 100644 index 000000000..34a1c90d8 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/name/simple/RecVarNode.java @@ -0,0 +1,81 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast.name.simple; + +import org.antlr.runtime.Token; +import org.scribble.core.type.kind.RecVarKind; +import org.scribble.core.type.name.RecVar; +import org.scribble.del.DelFactory; + +public class RecVarNode extends SimpleNameNode +{ + // Scribble.g, IDENTIFIER<...Node>[$IDENTIFIER] + // N.B. ttype (an "imaginary node" type) is discarded, t is a ScribbleParser.ID token type + public RecVarNode(int ttype, Token t) + { + super(t); + } + + // Tree#dupNode constructor + protected RecVarNode(RecVarNode node) + { + super(node); + } + + @Override + public RecVarNode dupNode() + { + return new RecVarNode(this); + } + + @Override + public void decorateDel(DelFactory df) + { + df.RecVarNode(this); + } + + @Override + public RecVar toName() + { + return new RecVar(getText()); + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof RecVarNode)) + { + return false; + } + return super.equals(o); // Does canEqual + } + + @Override + public boolean canEquals(Object o) + { + return o instanceof RecVarNode; + } + + @Override + public int hashCode() + { + int hash = 349; + hash = 31 * super.hashCode(); + return hash; + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/name/simple/RoleNode.java b/scribble-ast/src/main/java/org/scribble/ast/name/simple/RoleNode.java new file mode 100644 index 000000000..da32135cf --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/name/simple/RoleNode.java @@ -0,0 +1,84 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast.name.simple; + +import org.antlr.runtime.Token; +import org.scribble.ast.DoArgNode; +import org.scribble.core.type.kind.RoleKind; +import org.scribble.core.type.name.Role; +import org.scribble.del.DelFactory; + +public class RoleNode extends SimpleNameNode implements DoArgNode +{ + //public static final RoleNode SELF = ...; // No: no token info + + // Scribble.g, IDENTIFIER<...Node>[$IDENTIFIER] + // N.B. ttype (an "imaginary node" type) is discarded, t is a ScribbleParser.ID token type + public RoleNode(int ttype, Token t) + { + super(t); + } + + // Tree#dupNode constructor + protected RoleNode(RoleNode node) + { + super(node); + } + + @Override + public RoleNode dupNode() + { + return new RoleNode(this); + } + + @Override + public void decorateDel(DelFactory df) + { + df.RoleNode(this); + } + + @Override + public Role toName() + { + return new Role(getText()); + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof RoleNode)) + { + return false; + } + return ((RoleNode) o).canEquals(this) && super.equals(o); + } + + @Override + public boolean canEquals(Object o) + { + return o instanceof RoleNode; + } + + @Override + public int hashCode() + { + int hash = 353; + hash = 31 * super.hashCode(); + return hash; + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/name/simple/SigParamNode.java b/scribble-ast/src/main/java/org/scribble/ast/name/simple/SigParamNode.java new file mode 100644 index 000000000..a23afb405 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/name/simple/SigParamNode.java @@ -0,0 +1,102 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast.name.simple; + +import org.antlr.runtime.Token; +import org.scribble.ast.MsgNode; +import org.scribble.core.type.kind.SigKind; +import org.scribble.core.type.name.SigName; +import org.scribble.del.DelFactory; + +public class SigParamNode extends NonRoleParamNode + implements MsgNode +{ + // Scribble.g, IDENTIFIER<...Node>[$IDENTIFIER] + // N.B. ttype (an "imaginary node" type) is discarded, t is a ScribbleParser.ID token type + public SigParamNode(int ttype, Token t) + { + super(t, SigKind.KIND); + } + + // Tree#dupNode constructor + protected SigParamNode(SigParamNode node) + { + super(node); + } + + @Override + public SigParamNode dupNode() + { + return new SigParamNode(this); + } + + @Override + public void decorateDel(DelFactory df) + { + df.SigParamNode(this); + } + + // N.B. no "SigParamName" + @Override + public SigName toName() + { + return new SigName(getText()); + } + + @Override + public SigName toArg() + { + return toMsg(); + } + + @Override + public SigName toMsg() + { + return toName(); + } + + @Override + public boolean isSigParamNode() + { + return true; + } + + @Override + public int hashCode() + { + int hash = 8609; + hash = 31 * super.hashCode(); + return hash; + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof SigParamNode)) + { + return false; + } + return super.equals(o); + } + + @Override + public boolean canEquals(Object o) + { + return o instanceof SigParamNode; + } +} diff --git a/scribble-ast/src/main/java/org/scribble/ast/name/simple/SimpleNameNode.java b/scribble-ast/src/main/java/org/scribble/ast/name/simple/SimpleNameNode.java new file mode 100644 index 000000000..9495c8e02 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/ast/name/simple/SimpleNameNode.java @@ -0,0 +1,51 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast.name.simple; + +import java.util.Arrays; +import java.util.List; + +import org.antlr.runtime.Token; +import org.scribble.ast.name.NameNode; +import org.scribble.core.type.kind.Kind; + +// "ID" in Scribble.g, token type is ScribbleParser.ID, token text is the string value +// Names that are necessarily "simple", i.e., never compound qualified (cf. qualified, that may be simple or compound) +// CHECKME: refactor NameNode elem structure down the QualifiedNameNode side? -- e.g., NameNode.getChildren is misleading for SimpleNameNode (should use getElements instead) +public abstract class SimpleNameNode extends NameNode +{ + // token type is ScribbleParser.ID, token text is the string value + public SimpleNameNode(Token t) + { + super(t); + } + + // Tree#dupNode constructor + protected SimpleNameNode(SimpleNameNode node) + { + super(node); + } + + @Override + public String getText() + { + return this.token.getText(); + } + + @Override + public List getElements() + { + return Arrays.asList(getText()); + } +} diff --git a/scribble-ast/src/main/java/org/scribble/del/BasicInteractionDel.java b/scribble-ast/src/main/java/org/scribble/del/BasicInteractionDel.java new file mode 100644 index 000000000..6c30afb2d --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/del/BasicInteractionDel.java @@ -0,0 +1,19 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.del; + +public abstract class BasicInteractionDel extends SimpleSessionNodeDel +{ + +} diff --git a/scribble-ast/src/main/java/org/scribble/del/ChoiceDel.java b/scribble-ast/src/main/java/org/scribble/del/ChoiceDel.java new file mode 100644 index 000000000..c59dc1b86 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/del/ChoiceDel.java @@ -0,0 +1,22 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.del; + +public abstract class ChoiceDel extends CompoundInteractionDel +{ + public ChoiceDel() + { + + } +} diff --git a/scribble-ast/src/main/java/org/scribble/del/CompoundInteractionDel.java b/scribble-ast/src/main/java/org/scribble/del/CompoundInteractionDel.java new file mode 100644 index 000000000..692447ab7 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/del/CompoundInteractionDel.java @@ -0,0 +1,22 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.del; + +public abstract class CompoundInteractionDel extends CompoundSessionNodeDel +{ + public CompoundInteractionDel() + { + + } +} diff --git a/scribble-ast/src/main/java/org/scribble/del/CompoundSessionNodeDel.java b/scribble-ast/src/main/java/org/scribble/del/CompoundSessionNodeDel.java new file mode 100644 index 000000000..6861fd7f5 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/del/CompoundSessionNodeDel.java @@ -0,0 +1,24 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.del; + +// For CompoundInteractionNode and ProtocolBlock +public abstract class CompoundSessionNodeDel extends ScribDelBase + implements SessionNodeDel +{ + public CompoundSessionNodeDel() + { + + } +} diff --git a/scribble-ast/src/main/java/org/scribble/del/ConnectionActionDel.java b/scribble-ast/src/main/java/org/scribble/del/ConnectionActionDel.java new file mode 100644 index 000000000..74e74c398 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/del/ConnectionActionDel.java @@ -0,0 +1,22 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.del; + +public abstract class ConnectionActionDel extends DirectedInteractionDel +{ + public ConnectionActionDel() + { + + } +} diff --git a/scribble-ast/src/main/java/org/scribble/del/ContinueDel.java b/scribble-ast/src/main/java/org/scribble/del/ContinueDel.java new file mode 100644 index 000000000..e7fbb67ce --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/del/ContinueDel.java @@ -0,0 +1,22 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.del; + +public abstract class ContinueDel extends SimpleSessionNodeDel +{ + public ContinueDel() + { + + } +} diff --git a/scribble-ast/src/main/java/org/scribble/del/DefaultDel.java b/scribble-ast/src/main/java/org/scribble/del/DefaultDel.java new file mode 100644 index 000000000..eb8555c30 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/del/DefaultDel.java @@ -0,0 +1,22 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.del; + +public class DefaultDel extends ScribDelBase +{ + public DefaultDel() + { + + } +} diff --git a/scribble-ast/src/main/java/org/scribble/del/DelFactory.java b/scribble-ast/src/main/java/org/scribble/del/DelFactory.java new file mode 100644 index 000000000..e4d48ed79 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/del/DelFactory.java @@ -0,0 +1,184 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.del; + +import org.scribble.ast.AuxMod; +import org.scribble.ast.DataDecl; +import org.scribble.ast.DataParamDecl; +import org.scribble.ast.ExplicitMod; +import org.scribble.ast.ImportModule; +import org.scribble.ast.Module; +import org.scribble.ast.ModuleDecl; +import org.scribble.ast.NonRoleArg; +import org.scribble.ast.NonRoleArgList; +import org.scribble.ast.NonRoleParamDeclList; +import org.scribble.ast.PayElemList; +import org.scribble.ast.ProtoModList; +import org.scribble.ast.RoleArg; +import org.scribble.ast.RoleArgList; +import org.scribble.ast.RoleDecl; +import org.scribble.ast.RoleDeclList; +import org.scribble.ast.SigDecl; +import org.scribble.ast.SigLitNode; +import org.scribble.ast.SigParamDecl; +import org.scribble.ast.UnaryPayElem; +import org.scribble.ast.global.GChoice; +import org.scribble.ast.global.GConnect; +import org.scribble.ast.global.GContinue; +import org.scribble.ast.global.GDelegPayElem; +import org.scribble.ast.global.GDisconnect; +import org.scribble.ast.global.GDo; +import org.scribble.ast.global.GInteractionSeq; +import org.scribble.ast.global.GMsgTransfer; +import org.scribble.ast.global.GProtoBlock; +import org.scribble.ast.global.GProtoDecl; +import org.scribble.ast.global.GProtoDef; +import org.scribble.ast.global.GProtoHeader; +import org.scribble.ast.global.GRecursion; +import org.scribble.ast.global.GWrap; +import org.scribble.ast.local.LAcc; +import org.scribble.ast.local.LChoice; +import org.scribble.ast.local.LClientWrap; +import org.scribble.ast.local.LContinue; +import org.scribble.ast.local.LDisconnect; +import org.scribble.ast.local.LDo; +import org.scribble.ast.local.LInteractionSeq; +import org.scribble.ast.local.LProjectionDecl; +import org.scribble.ast.local.LProtoBlock; +import org.scribble.ast.local.LProtoDecl; +import org.scribble.ast.local.LProtoDef; +import org.scribble.ast.local.LProtoHeader; +import org.scribble.ast.local.LRecursion; +import org.scribble.ast.local.LRecv; +import org.scribble.ast.local.LReq; +import org.scribble.ast.local.LSelfDecl; +import org.scribble.ast.local.LSend; +import org.scribble.ast.local.LServerWrap; +import org.scribble.ast.name.qualified.DataNameNode; +import org.scribble.ast.name.qualified.GProtoNameNode; +import org.scribble.ast.name.qualified.LProtoNameNode; +import org.scribble.ast.name.qualified.ModuleNameNode; +import org.scribble.ast.name.qualified.SigNameNode; +import org.scribble.ast.name.simple.AmbigNameNode; +import org.scribble.ast.name.simple.DataParamNode; +import org.scribble.ast.name.simple.ExtIdNode; +import org.scribble.ast.name.simple.IdNode; +import org.scribble.ast.name.simple.OpNode; +import org.scribble.ast.name.simple.RecVarNode; +import org.scribble.ast.name.simple.RoleNode; +import org.scribble.ast.name.simple.SigParamNode; + + +// A little bit more than a "plain" factory, methods do the decoration via ScribNodeBase.setDel +// Use after ANTLR parsing (specifically, ScribTreeAdaptor) -- not needed for AstFactory constructions +// (Perhaps could integrate with ScribTreeAdaptor, but easier to do after -- AST construction technically may further create/dup nodes during the ongoing pass) +// A dec method for each AST class -- method name must be the same as target class name +// Implementations (DelDecoratorImpl) in scribble-parser, can depend on parser implementation +// E.g., DelDecoratorImpl: each method named after the class name +public interface DelFactory +{ + // Names + void IdNode(IdNode n); + void ExtIdNode(ExtIdNode n); + + void AmbigNameNode(AmbigNameNode n); + void DataParamNode(DataParamNode n); + void OpNode(OpNode n); + void RecVarNode(RecVarNode n); + void RoleNode(RoleNode n); + void SigParamNode(SigParamNode n); + + void DataNameNode(DataNameNode n); + void GProtoNameNode(GProtoNameNode n); + void LProtoNameNode(LProtoNameNode n); + void ModuleNameNode(ModuleNameNode n); + void SigNameNode(SigNameNode n); + + + // General and globals + void Module(Module m); + void ModuleDecl(ModuleDecl n); + void ImportModule(ImportModule n); + + void DataDecl(DataDecl n); + void SigDecl(SigDecl n); + void GProtoDecl(GProtoDecl n); + + void ProtoModList(ProtoModList n); + void AuxMod(AuxMod n); + void ExplicitMod(ExplicitMod n); + + void GProtoHeader(GProtoHeader n); + void RoleDeclList(RoleDeclList n); + void RoleDecl(RoleDecl n); + void NonRoleParamDeclList(NonRoleParamDeclList n); + void DataParamDecl(DataParamDecl n); + void SigParamDecl(SigParamDecl n); + + void GProtoDef(GProtoDef n); + void GProtoBlock(GProtoBlock n); + void GInteractionSeq(GInteractionSeq n); + + void SigLitNode(SigLitNode n); + void PayElemList(PayElemList n); + void UnaryPayElem(UnaryPayElem n); + void GDelegPayElem(GDelegPayElem n); + + void GMsgTransfer(GMsgTransfer n); + void GConnect(GConnect n); + void GDisconnect(GDisconnect n); + void GWrap(GWrap n); + + void GContinue(GContinue n); + void GDo(GDo n); + + void RoleArgList(RoleArgList n); + void RoleArg(RoleArg r); + void NonRoleArgList(NonRoleArgList n); + void NonRoleArg(NonRoleArg n); + + void GChoice(GChoice n); + void GRecursion(GRecursion n); + + + // Locals + void LProtoDecl(LProtoDecl n); + void LProjectionDecl(LProjectionDecl n); + + void LProtoHeader(LProtoHeader n); + + void LSelfDecl(LSelfDecl n); + + void LProtoDef(LProtoDef n); + void LProtoBlock(LProtoBlock n); + void LInteractionSeq(LInteractionSeq n); + + //void LDelegElem(LDelegElem n); + + void LSend(LSend n); + void LRecv(LRecv n); + void LAcc(LAcc n); + void LReq(LReq n); + void LDisconnect(LDisconnect n); + void LClientWrap(LClientWrap n); + void LServerWrap(LServerWrap n); + + void LContinue(LContinue n); + void LDo(LDo n); + + void LChoice(LChoice n); + void LRecursion(LRecursion n); +} + + diff --git a/scribble-ast/src/main/java/org/scribble/del/DirectedInteractionDel.java b/scribble-ast/src/main/java/org/scribble/del/DirectedInteractionDel.java new file mode 100644 index 000000000..2831692b7 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/del/DirectedInteractionDel.java @@ -0,0 +1,19 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.del; + +public abstract class DirectedInteractionDel extends BasicInteractionDel +{ + +} diff --git a/scribble-ast/src/main/java/org/scribble/del/DisconnectDel.java b/scribble-ast/src/main/java/org/scribble/del/DisconnectDel.java new file mode 100644 index 000000000..7001d7a12 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/del/DisconnectDel.java @@ -0,0 +1,19 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.del; + +public abstract class DisconnectDel extends BasicInteractionDel +{ + +} diff --git a/scribble-ast/src/main/java/org/scribble/del/DoArgListDel.java b/scribble-ast/src/main/java/org/scribble/del/DoArgListDel.java new file mode 100644 index 000000000..08d172767 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/del/DoArgListDel.java @@ -0,0 +1,84 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.del; + +import java.util.List; +import java.util.stream.Collectors; + +import org.scribble.ast.Do; +import org.scribble.ast.DoArgList; +import org.scribble.ast.ParamDeclList; +import org.scribble.ast.Module; +import org.scribble.ast.ProtoDecl; +import org.scribble.ast.ScribNode; +import org.scribble.core.lang.context.ModuleContext; +import org.scribble.core.type.name.ProtoName; +import org.scribble.job.JobContext; +import org.scribble.util.ScribException; +import org.scribble.visit.NameDisambiguator; + +public abstract class DoArgListDel extends ScribDelBase +{ + public DoArgListDel() + { + + } + + // Doing in leave allows the arguments to be individually checked first + @Override + public DoArgList leaveDisambiguation(ScribNode child, + NameDisambiguator disamb, ScribNode visited) throws ScribException + { + ScribNode parent = child.getParent(); + DoArgList dal = (DoArgList) visited; + List args = dal.getArgChildren(); + ProtoDecl pd = getTargetProtocolDecl((Do) parent, disamb); + if (args.size() != getDeclList(pd).getDeclChildren().size()) + { + throw new ScribException(child.getSource(), + "Do arity mismatch for " + pd.getHeaderChild() + ": " + args); + } + + return dal; + } + + // Not using Do#getTargetProtocolDecl, because that currently relies on namedisamb pass to convert targets to fullnames (because it just gets the full name dependency, it doesn't do visible name resolution) + protected ProtoDecl getTargetProtocolDecl(Do parent, + NameDisambiguator disamb) throws ScribException + { + ModuleContext mc = disamb.getModuleContext(); + JobContext jc = disamb.job.getContext(); + Do doo = (Do) parent; + ProtoName pn = doo.getProtocolNameNode().toName(); + /*if (!mc.isVisibleProtocolDeclName(simpname)) // FIXME: should be checked somewhere else? earlier (do-entry?) -- done + { + throw new ScribbleException("Protocol decl not visible: " + simpname); + }*/ + ProtoName fullname = mc.getVisibleProtocolDeclFullName(pn); // Lookup in visible names -- not deps, because do target name not disambiguated yet (will be done later this pass) + Module mod = jc.getModule(fullname.getPrefix()); + //return mod.getProtocolDeclChild(pn.getSimpleName()); + List> pd = mod.getProtoDeclChildren().stream() + .filter( // cf. Module::hasProtocolDecl + x -> x.getHeaderChild().getDeclName().equals(pn.getSimpleName())) + .collect(Collectors.toList()); + if (pd.size() != 1) + { + throw new ScribException("[disamb] Target protocol ambiguous or not found: " + pn); + } + return pd.get(0); + } + + protected abstract ParamDeclList getDeclList( + ProtoDecl pd); +} diff --git a/scribble-ast/src/main/java/org/scribble/del/DoDel.java b/scribble-ast/src/main/java/org/scribble/del/DoDel.java new file mode 100644 index 000000000..ff23cc22f --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/del/DoDel.java @@ -0,0 +1,94 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.del; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import org.scribble.ast.Do; +import org.scribble.ast.ScribNode; +import org.scribble.ast.name.qualified.ProtoNameNode; +import org.scribble.ast.name.simple.IdNode; +import org.scribble.core.lang.context.ModuleContext; +import org.scribble.core.type.kind.ProtoKind; +import org.scribble.core.type.name.GProtoName; +import org.scribble.core.type.name.ProtoName; +import org.scribble.util.ScribException; +import org.scribble.visit.NameDisambiguator; + +public abstract class DoDel extends SimpleSessionNodeDel +{ + public DoDel() + { + + } + + @Override + public void enterDisambiguation(ScribNode child, NameDisambiguator disamb) + throws ScribException + { + ModuleContext mc = disamb.getModuleContext(); + Do doo = (Do) child; + ProtoNameNode proto = doo.getProtocolNameNode(); + ProtoName simpname = proto.toName(); + if (!mc.isVisibleProtocolDeclName(simpname)) // CHECKME: do on entry here, before visiting DoArgListDel + { + throw new ScribException(proto.getSource(), + "Protocol decl not visible: " + simpname); + } + } + + @Override + public ScribNode leaveDisambiguation(ScribNode child, + NameDisambiguator disamb, ScribNode visited) throws ScribException + { + return leaveDisambiguationAux((Do) visited, disamb); + // To introduce type parameter + } + + // Convert all visible names to full names for protocol inlining: otherwise could get clashes if directly inlining external visible names under the root modulecontext + // Not done in G/LProtocolNameNodeDel because it's only for do-targets that this is needed (cf. ProtocolHeader) + private ScribNode leaveDisambiguationAux( + Do visited, NameDisambiguator disamb) throws ScribException + { + ProtoNameNode proto = visited.getProtocolNameNode(); + + // CHECKME: do full name expansion in disamb? or leave to imed translation? -- FIXME: sort out full name expansion between here and GDoDel.translate + ProtoNameNode n = makeProtoNameNode(disamb, proto); + + // Didn't keep original namenode del -- ? + return visited.reconstruct(n, + visited.getNonRoleListChild(), visited.getRoleListChild()); + } + + private ProtoNameNode makeProtoNameNode( + NameDisambiguator disamb, ProtoNameNode proto) + { + ModuleContext modc = disamb.getModuleContext(); + ProtoName fullname = modc + .getVisibleProtocolDeclFullName(proto.toName()); + if (fullname instanceof GProtoName) + { + List elems = Arrays.asList(fullname.getElements()).stream() + .map(x -> disamb.job.config.af.IdNode(null, x)) + .collect(Collectors.toList()); + @SuppressWarnings("unchecked") // FIXME + ProtoNameNode cast = (ProtoNameNode) disamb.job.config.af + .GProtoNameNode(proto.token, elems); + return cast; + } + throw new RuntimeException("[TODO] " + fullname.getKind() + ": " + fullname); + } +} diff --git a/scribble-ast/src/main/java/org/scribble/del/HeaderParamDeclListDel.java b/scribble-ast/src/main/java/org/scribble/del/HeaderParamDeclListDel.java new file mode 100644 index 000000000..d679f2e42 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/del/HeaderParamDeclListDel.java @@ -0,0 +1,47 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.del; + +import java.util.List; + +import org.scribble.ast.ParamDecl; +import org.scribble.ast.ParamDeclList; +import org.scribble.ast.ScribNode; +import org.scribble.util.ScribException; +import org.scribble.visit.NameDisambiguator; + +public abstract class HeaderParamDeclListDel extends ScribDelBase +{ + public HeaderParamDeclListDel() + { + + } + + // Doing in leave allows the arguments to be individually checked first + @Override + public ParamDeclList leaveDisambiguation(ScribNode child, + NameDisambiguator disamb, ScribNode visited) throws ScribException + { + ParamDeclList pdl = (ParamDeclList) visited; + List> decls = pdl.getDeclChildren(); + // grammar enforces RoleDeclList size > 0 + if (decls.size() != decls.stream().map(d -> d.getDeclName()).distinct() + .count()) + { + throw new ScribException(pdl.getSource(), + "Duplicate header decls: " + pdl); + } + return pdl; + } +} diff --git a/scribble-ast/src/main/java/org/scribble/del/ImportModuleDel.java b/scribble-ast/src/main/java/org/scribble/del/ImportModuleDel.java new file mode 100644 index 000000000..a92d2ebf6 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/del/ImportModuleDel.java @@ -0,0 +1,22 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.del; + +public class ImportModuleDel extends ScribDelBase +{ + public ImportModuleDel() + { + + } +} diff --git a/scribble-ast/src/main/java/org/scribble/del/InteractionSeqDel.java b/scribble-ast/src/main/java/org/scribble/del/InteractionSeqDel.java new file mode 100644 index 000000000..23cd02548 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/del/InteractionSeqDel.java @@ -0,0 +1,19 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.del; + +public abstract class InteractionSeqDel extends ScribDelBase +{ + +} diff --git a/scribble-ast/src/main/java/org/scribble/del/ModuleDel.java b/scribble-ast/src/main/java/org/scribble/del/ModuleDel.java new file mode 100644 index 000000000..28e26125a --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/del/ModuleDel.java @@ -0,0 +1,92 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.del; + +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; + +import org.scribble.ast.Module; +import org.scribble.ast.NonProtoDecl; +import org.scribble.ast.ProtoDecl; +import org.scribble.ast.ScribNode; +import org.scribble.util.ScribException; +import org.scribble.visit.NameDisambiguator; + +public class ModuleDel extends ScribDelBase +{ + public ModuleDel() + { + + } + + @Override + public Module leaveDisambiguation(ScribNode child, NameDisambiguator disamb, + ScribNode visited) throws ScribException + { + Module mod = (Module) visited; + // Imports checked in ModuleContext -- that is built before disamb is run + List> npds = mod.getNonProtoDeclChildren(); + List npdnames = npds.stream() + .map(x -> x.getDeclName().toString()) + .collect(Collectors.toList()); + // Have to use Strings, as can be different kinds (datatype, sig) + final Set dups1 = getDuplicates(npdnames); + if (!dups1.isEmpty()) + { + NonProtoDecl first = + npds.stream() + .filter(x -> dups1.contains(x.getDeclName().toString())) + .collect(Collectors.toList()).get(0); + throw new ScribException(first.getSource(), + "Duplicate non-protocol decls: " + first.getDeclName()); + } + List> pds = mod.getProtoDeclChildren(); + List pdnames = pds.stream() + .map(pd -> pd.getHeaderChild().getDeclName().toString()) + .collect(Collectors.toList()); + // Have to use Strings, as can be different kinds (global, local) + final Set dups2 = getDuplicates(pdnames); + if (pds.size() != pdnames.stream().distinct().count()) + if (!dups2.isEmpty()) + { + ProtoDecl first = + pds.stream() + .filter(x -> dups2 + .contains(x.getHeaderChild().getDeclName().toString())) + .collect(Collectors.toList()).get(0); + throw new ScribException(first.getSource(), + "Duplicate protocol decls: " + + first.getHeaderChild().getDeclName()); + // Global and locals also required to be distinct + } + return mod; + } + + private static Set getDuplicates(Collection ss) + { + Set uniques = new HashSet<>(); + Set dups = new HashSet<>(); + for (String npd : ss) + { + if (!uniques.add(npd)) + { + dups.add(npd); + } + } + return dups; + } +} diff --git a/scribble-ast/src/main/java/org/scribble/del/MsgTransferDel.java b/scribble-ast/src/main/java/org/scribble/del/MsgTransferDel.java new file mode 100644 index 000000000..8f1351206 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/del/MsgTransferDel.java @@ -0,0 +1,22 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.del; + +public abstract class MsgTransferDel extends DirectedInteractionDel +{ + public MsgTransferDel() + { + + } +} diff --git a/scribble-ast/src/main/java/org/scribble/del/NonRoleArgListDel.java b/scribble-ast/src/main/java/org/scribble/del/NonRoleArgListDel.java new file mode 100644 index 000000000..3e92d4647 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/del/NonRoleArgListDel.java @@ -0,0 +1,96 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.del; + +import java.util.Iterator; + +import org.scribble.ast.Do; +import org.scribble.ast.NonRoleArg; +import org.scribble.ast.NonRoleArgList; +import org.scribble.ast.NonRoleArgNode; +import org.scribble.ast.NonRoleParamDecl; +import org.scribble.ast.NonRoleParamDeclList; +import org.scribble.ast.ProtoDecl; +import org.scribble.ast.ScribNode; +import org.scribble.ast.name.simple.NonRoleParamNode; +import org.scribble.core.type.kind.DataKind; +import org.scribble.core.type.kind.NonRoleParamKind; +import org.scribble.core.type.kind.SigKind; +import org.scribble.util.ScribException; +import org.scribble.visit.NameDisambiguator; + +public class NonRoleArgListDel extends DoArgListDel +{ + public NonRoleArgListDel() + { + + } + + // Doing in leave allows the arguments to be individually checked first + @Override + public NonRoleArgList leaveDisambiguation(ScribNode child, + NameDisambiguator disamb, ScribNode visited) throws ScribException + { + NonRoleArgList nral = (NonRoleArgList) super.leaveDisambiguation(child, + disamb, visited); + // Checks matching arity + + Do parent = (Do) child.getParent(); + ProtoDecl pd = getTargetProtocolDecl((Do) parent, disamb); + Iterator args = nral.getArgChildren().iterator(); + for (NonRoleParamDecl param : pd.getHeaderChild().getParamDeclListChild() + .getDeclChildren()) + { + NonRoleParamKind pkind = param.kind; + NonRoleArg arg = args.next(); + NonRoleArgNode val = arg.getArgNodeChild(); + if (val.isDataParamNode() || val.isSigParamNode()) + { + if (!((NonRoleParamNode) val).kind.equals(pkind)) + { + throw new ScribException(arg.getSource(), + "Invalid arg " + arg + " for param kind: " + pkind); + } + } + else if (pkind.equals(SigKind.KIND)) + { + if (!val.isSigLitNode() && !val.isSigNameNode()) + { + throw new ScribException(arg.getSource(), + "Invalid arg " + arg + " for param kind: " + pkind); + } + } + else if (pkind.equals(DataKind.KIND)) + { + if (!val.isDataNameNode()) + { + throw new ScribException(arg.getSource(), + "Invalid arg " + arg + " for param kind: " + pkind); + } + } + else + { + throw new RuntimeException("Shouldn't get in here: " + pkind); + } + } + + return nral; + } + + @Override + protected NonRoleParamDeclList getDeclList(ProtoDecl pd) + { + return pd.getHeaderChild().getParamDeclListChild(); + } +} diff --git a/scribble-ast/src/main/java/org/scribble/del/NonRoleParamDeclDel.java b/scribble-ast/src/main/java/org/scribble/del/NonRoleParamDeclDel.java new file mode 100644 index 000000000..6ff5c68a1 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/del/NonRoleParamDeclDel.java @@ -0,0 +1,30 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.del; + +import org.scribble.ast.NonRoleParamDecl; +import org.scribble.ast.ScribNode; +import org.scribble.util.ScribException; +import org.scribble.visit.NameDisambiguator; + +public class NonRoleParamDeclDel extends ScribDelBase +{ + @Override + public void enterDisambiguation(ScribNode child, NameDisambiguator disamb) + throws ScribException + { + NonRoleParamDecl pd = (NonRoleParamDecl) child; + disamb.addParam(pd.getDeclName(), pd.kind); + } +} diff --git a/scribble-ast/src/main/java/org/scribble/del/NonRoleParamDeclListDel.java b/scribble-ast/src/main/java/org/scribble/del/NonRoleParamDeclListDel.java new file mode 100644 index 000000000..42ad66f37 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/del/NonRoleParamDeclListDel.java @@ -0,0 +1,23 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.del; + + +public class NonRoleParamDeclListDel extends HeaderParamDeclListDel +{ + public NonRoleParamDeclListDel() + { + + } +} diff --git a/scribble-ast/src/main/java/org/scribble/del/ProtoBlockDel.java b/scribble-ast/src/main/java/org/scribble/del/ProtoBlockDel.java new file mode 100644 index 000000000..a2cad9876 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/del/ProtoBlockDel.java @@ -0,0 +1,22 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.del; + + +// Not a CompoundSessionNodeDel -- corresponds to ProtocolBlock, not a CompoundSessionNode +// A ProtocolBlock is not a "direct" session type constructor (cf. SessionNode) +public abstract class ProtoBlockDel extends ScribDelBase +{ + +} diff --git a/scribble-ast/src/main/java/org/scribble/del/ProtoDeclDel.java b/scribble-ast/src/main/java/org/scribble/del/ProtoDeclDel.java new file mode 100644 index 000000000..a7bf069bf --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/del/ProtoDeclDel.java @@ -0,0 +1,36 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.del; + +import org.scribble.ast.ScribNode; +import org.scribble.core.type.kind.ProtoKind; +import org.scribble.util.ScribException; +import org.scribble.visit.NameDisambiguator; + +public abstract class ProtoDeclDel + extends ScribDelBase +{ + protected ProtoDeclDel() + { + + } + + @Override + public ScribNode leaveDisambiguation(ScribNode child, + NameDisambiguator disamb, ScribNode visited) throws ScribException + { + disamb.clear(); + return visited; + } +} diff --git a/scribble-ast/src/main/java/org/scribble/del/ProtoDefDel.java b/scribble-ast/src/main/java/org/scribble/del/ProtoDefDel.java new file mode 100644 index 000000000..7990d1628 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/del/ProtoDefDel.java @@ -0,0 +1,19 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.del; + +public abstract class ProtoDefDel extends ScribDelBase +{ + +} diff --git a/scribble-ast/src/main/java/org/scribble/del/RecursionDel.java b/scribble-ast/src/main/java/org/scribble/del/RecursionDel.java new file mode 100644 index 000000000..1a0d3d34e --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/del/RecursionDel.java @@ -0,0 +1,48 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.del; + +import org.scribble.ast.Recursion; +import org.scribble.ast.ScribNode; +import org.scribble.core.type.name.RecVar; +import org.scribble.util.ScribException; +import org.scribble.visit.NameDisambiguator; + +public abstract class RecursionDel extends CompoundInteractionDel +{ + public RecursionDel() + { + + } + + @Override + public void enterDisambiguation(ScribNode child, + NameDisambiguator disamb) throws ScribException + { + Recursion rec = (Recursion) child; + RecVar rv = rec.getRecVarChild().toName(); + disamb.pushRecVar(rv); + } + + @Override + public ScribNode leaveDisambiguation(ScribNode child, + NameDisambiguator disamb, ScribNode visited) throws ScribException + { + Recursion rec = (Recursion) visited; + RecVar rv = ((Recursion) child).getRecVarChild().toName(); + // visited may be already name mangled // Not any more (refactored to inlining) + disamb.popRecVar(rv); + return rec; + } +} diff --git a/scribble-ast/src/main/java/org/scribble/del/RoleArgListDel.java b/scribble-ast/src/main/java/org/scribble/del/RoleArgListDel.java new file mode 100644 index 000000000..aa2513fec --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/del/RoleArgListDel.java @@ -0,0 +1,55 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.del; + +import java.util.List; + +import org.scribble.ast.ProtoDecl; +import org.scribble.ast.RoleArgList; +import org.scribble.ast.RoleDeclList; +import org.scribble.ast.ScribNode; +import org.scribble.core.type.name.Role; +import org.scribble.util.ScribException; +import org.scribble.visit.NameDisambiguator; + +public class RoleArgListDel extends DoArgListDel +{ + public RoleArgListDel() + { + + } + + @Override + public RoleArgList leaveDisambiguation(ScribNode child, + NameDisambiguator disamb, ScribNode visited) throws ScribException + { + visited = super.leaveDisambiguation(child, disamb, visited); // Checks matching arity + + // Duplicate check not needed for NonRoleArgList + RoleArgList ral = (RoleArgList) visited; + List roles = ral.getRoles(); + if (roles.size() != roles.stream().distinct().count()) + { + throw new ScribException(ral.getSource(), + "Duplicate role args: " + roles); + } + return ral; + } + + @Override + protected RoleDeclList getDeclList(ProtoDecl pd) + { + return pd.getHeaderChild().getRoleDeclListChild(); + } +} diff --git a/scribble-ast/src/main/java/org/scribble/del/RoleDeclDel.java b/scribble-ast/src/main/java/org/scribble/del/RoleDeclDel.java new file mode 100644 index 000000000..55eaefdd5 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/del/RoleDeclDel.java @@ -0,0 +1,30 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.del; + +import org.scribble.ast.RoleDecl; +import org.scribble.ast.ScribNode; +import org.scribble.util.ScribException; +import org.scribble.visit.NameDisambiguator; + +public class RoleDeclDel extends ScribDelBase +{ + @Override + public void enterDisambiguation(ScribNode child, NameDisambiguator disamb) + throws ScribException + { + RoleDecl rd = (RoleDecl) child; + disamb.addRole(rd.getDeclName()); // Could check distinct here, but doing it uniformly in HeaderParamDeclListDel + } +} diff --git a/scribble-ast/src/main/java/org/scribble/del/RoleDeclListDel.java b/scribble-ast/src/main/java/org/scribble/del/RoleDeclListDel.java new file mode 100644 index 000000000..748777204 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/del/RoleDeclListDel.java @@ -0,0 +1,23 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.del; + + +public class RoleDeclListDel extends HeaderParamDeclListDel +{ + public RoleDeclListDel() + { + + } +} diff --git a/scribble-ast/src/main/java/org/scribble/del/ScribDel.java b/scribble-ast/src/main/java/org/scribble/del/ScribDel.java new file mode 100644 index 000000000..0d5a82b6e --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/del/ScribDel.java @@ -0,0 +1,34 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.del; + +import org.scribble.ast.ScribNode; +import org.scribble.util.ScribException; +import org.scribble.visit.NameDisambiguator; + +// Parameterise by AstNode type? Would inhibit del sharing between types (but that's not currently needed) +public interface ScribDel +{ + default void enterDisambiguation(ScribNode child, NameDisambiguator disamb) + throws ScribException + { + + } + + default ScribNode leaveDisambiguation(ScribNode child, + NameDisambiguator disamb, ScribNode visited) throws ScribException + { + return visited; + } +} diff --git a/scribble-ast/src/main/java/org/scribble/del/ScribDelBase.java b/scribble-ast/src/main/java/org/scribble/del/ScribDelBase.java new file mode 100644 index 000000000..d8a3a4db6 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/del/ScribDelBase.java @@ -0,0 +1,22 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.del; + +public abstract class ScribDelBase implements ScribDel +{ + public ScribDelBase() + { + + } +} diff --git a/scribble-ast/src/main/java/org/scribble/del/SessionNodeDel.java b/scribble-ast/src/main/java/org/scribble/del/SessionNodeDel.java new file mode 100644 index 000000000..bd264b2bd --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/del/SessionNodeDel.java @@ -0,0 +1,19 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.del; + +public interface SessionNodeDel extends ScribDel +{ + +} diff --git a/scribble-ast/src/main/java/org/scribble/del/SimpleSessionNodeDel.java b/scribble-ast/src/main/java/org/scribble/del/SimpleSessionNodeDel.java new file mode 100644 index 000000000..2b41b09f4 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/del/SimpleSessionNodeDel.java @@ -0,0 +1,20 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.del; + +public abstract class SimpleSessionNodeDel extends ScribDelBase + implements SessionNodeDel +{ + +} diff --git a/scribble-ast/src/main/java/org/scribble/del/global/GChoiceDel.java b/scribble-ast/src/main/java/org/scribble/del/global/GChoiceDel.java new file mode 100644 index 000000000..f8376b491 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/del/global/GChoiceDel.java @@ -0,0 +1,43 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.del.global; + +import java.util.LinkedList; +import java.util.List; + +import org.scribble.ast.ScribNode; +import org.scribble.ast.global.GChoice; +import org.scribble.ast.global.GProtoBlock; +import org.scribble.core.type.name.Role; +import org.scribble.core.type.session.global.GSeq; +import org.scribble.del.ChoiceDel; +import org.scribble.visit.GTypeTranslator; + +public class GChoiceDel extends ChoiceDel implements GCompoundSessionNodeDel +{ + + @Override + public org.scribble.core.type.session.global.GChoice translate(ScribNode n, + GTypeTranslator t) + { + GChoice source = (GChoice) n; + Role subj = source.getSubjectChild().toName(); + List blocks = new LinkedList<>(); + for (GProtoBlock b : source.getBlockChildren()) + { + blocks.add((GSeq) b.visitWith(t)); + } + return t.tf.global.GChoice(source, subj, blocks); + } +} diff --git a/scribble-ast/src/main/java/org/scribble/del/global/GCompoundSessionNodeDel.java b/scribble-ast/src/main/java/org/scribble/del/global/GCompoundSessionNodeDel.java new file mode 100644 index 000000000..5f6e4f35c --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/del/global/GCompoundSessionNodeDel.java @@ -0,0 +1,19 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.del.global; + +public interface GCompoundSessionNodeDel extends GSessionNodeDel +{ + +} diff --git a/scribble-ast/src/main/java/org/scribble/del/global/GConnectDel.java b/scribble-ast/src/main/java/org/scribble/del/global/GConnectDel.java new file mode 100644 index 000000000..ddf77d05c --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/del/global/GConnectDel.java @@ -0,0 +1,59 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.del.global; + +import java.util.List; + +import org.scribble.ast.ScribNode; +import org.scribble.ast.global.GConnect; +import org.scribble.ast.name.simple.RoleNode; +import org.scribble.core.type.name.Role; +import org.scribble.core.type.session.Msg; +import org.scribble.del.ConnectionActionDel; +import org.scribble.util.ScribException; +import org.scribble.visit.GTypeTranslator; +import org.scribble.visit.NameDisambiguator; + +public class GConnectDel extends ConnectionActionDel + implements GSimpleSessionNodeDel +{ + public GConnectDel() + { + + } + + @Override + public ScribNode leaveDisambiguation(ScribNode child, + NameDisambiguator disamb, ScribNode visited) throws ScribException + { + GConnect gc = (GConnect) visited; + return gc; + } + + @Override + public org.scribble.core.type.session.global.GConnect translate(ScribNode n, + GTypeTranslator t) + { + GConnect source = (GConnect) n; + Role src = source.getSourceChild().toName(); + List ds = source.getDestinationChildren(); + if (ds.size() > 1) + { + throw new RuntimeException("TODO: multiple destination roles: " + source); + } + Role dst = ds.get(0).toName(); + Msg msg = source.getMessageNodeChild().toMsg(); + return t.tf.global.GConnect(source, src, msg, dst); + } +} diff --git a/scribble-ast/src/main/java/org/scribble/del/global/GContinueDel.java b/scribble-ast/src/main/java/org/scribble/del/global/GContinueDel.java new file mode 100644 index 000000000..1f37b1fca --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/del/global/GContinueDel.java @@ -0,0 +1,34 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.del.global; + +import org.scribble.ast.ScribNode; +import org.scribble.ast.global.GContinue; +import org.scribble.core.type.name.RecVar; +import org.scribble.del.ContinueDel; +import org.scribble.visit.GTypeTranslator; + +public class GContinueDel extends ContinueDel + implements GSimpleSessionNodeDel +{ + + @Override + public org.scribble.core.type.session.global.GContinue translate(ScribNode n, + GTypeTranslator t) + { + GContinue source = (GContinue) n; + RecVar recvar = source.getRecVarChild().toName(); + return t.tf.global.GContinue(source, recvar); + } +} diff --git a/scribble-ast/src/main/java/org/scribble/del/global/GDel.java b/scribble-ast/src/main/java/org/scribble/del/global/GDel.java new file mode 100644 index 000000000..8da532de3 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/del/global/GDel.java @@ -0,0 +1,24 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.del.global; + +import org.scribble.ast.ScribNode; +import org.scribble.core.lang.global.GNode; +import org.scribble.del.ScribDel; +import org.scribble.visit.GTypeTranslator; + +public interface GDel extends ScribDel +{ + GNode translate(ScribNode n, GTypeTranslator t); +} diff --git a/scribble-ast/src/main/java/org/scribble/del/global/GDelegationElemDel.java b/scribble-ast/src/main/java/org/scribble/del/global/GDelegationElemDel.java new file mode 100644 index 000000000..e9a36b49b --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/del/global/GDelegationElemDel.java @@ -0,0 +1,83 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.del.global; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import org.scribble.ast.ProtoDecl; +import org.scribble.ast.ScribNode; +import org.scribble.ast.global.GDelegPayElem; +import org.scribble.ast.name.qualified.GProtoNameNode; +import org.scribble.ast.name.simple.IdNode; +import org.scribble.ast.name.simple.RoleNode; +import org.scribble.core.lang.context.ModuleContext; +import org.scribble.core.type.kind.Global; +import org.scribble.core.type.name.GProtoName; +import org.scribble.core.type.name.Role; +import org.scribble.del.ScribDelBase; +import org.scribble.util.ScribException; +import org.scribble.visit.NameDisambiguator; + +public class GDelegationElemDel extends ScribDelBase +{ + public GDelegationElemDel() + { + + } + + // Duplicated from DoDel + @Override + public void enterDisambiguation(ScribNode child, + NameDisambiguator disamb) throws ScribException + { + ModuleContext mc = disamb.getModuleContext(); + GDelegPayElem de = (GDelegPayElem) child; + GProtoNameNode proto = de.getProtocolChild(); + GProtoName gpn = proto.toName(); + if (!mc.isVisibleProtocolDeclName(gpn)) + { + throw new ScribException(proto.getSource(), + "Protocol decl not visible: " + gpn); + } + } + + // Duplicated from DoDel + //@Override + public GDelegPayElem visitForNameDisambiguation(NameDisambiguator disamb, // CHECKME: why "visitFor" pattern? + GDelegPayElem deleg) throws ScribException + { + ModuleContext mc = disamb.getModuleContext(); + GProtoNameNode proto = deleg.getProtocolChild(); + GProtoName fullname = (GProtoName) mc + .getVisibleProtocolDeclFullName(proto.toName()); + RoleNode r = deleg.getRoleChild(); + + Role rn = r.toName(); + ProtoDecl gpd = disamb.job.getContext() + .getModule(fullname.getPrefix()) + .getGProtocolDeclChild(fullname.getSimpleName()); + if (!gpd.getHeaderChild().getRoleDeclListChild().getRoles().contains(rn)) + { + throw new ScribException(r.getSource(), "Invalid delegation role: " + deleg); + } + List elems = Arrays.asList(fullname.getElements()).stream() + .map(x -> disamb.job.config.af.IdNode(null, x)).collect(Collectors.toList()); + GProtoNameNode pnn = (GProtoNameNode) disamb.job.config.af + .GProtoNameNode(proto.token, elems); + // Not keeping original namenode del + return deleg.reconstruct(pnn, r); + } +} diff --git a/scribble-ast/src/main/java/org/scribble/del/global/GDisconnectDel.java b/scribble-ast/src/main/java/org/scribble/del/global/GDisconnectDel.java new file mode 100644 index 000000000..ed3ad5a36 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/del/global/GDisconnectDel.java @@ -0,0 +1,50 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.del.global; + +import org.scribble.ast.ScribNode; +import org.scribble.ast.global.GDisconnect; +import org.scribble.core.type.name.Role; +import org.scribble.del.ConnectionActionDel; +import org.scribble.util.ScribException; +import org.scribble.visit.GTypeTranslator; +import org.scribble.visit.NameDisambiguator; + +// TODO: make DisconnectDel (cf., G/LMessageTransferDel) +public class GDisconnectDel extends ConnectionActionDel + implements GSimpleSessionNodeDel +{ + public GDisconnectDel() + { + + } + + @Override + public ScribNode leaveDisambiguation(ScribNode child, + NameDisambiguator disamb, ScribNode visited) throws ScribException + { + GDisconnect gc = (GDisconnect) visited; + return gc; + } + + @Override + public org.scribble.core.type.session.global.GDisconnect translate(ScribNode n, + GTypeTranslator t) + { + GDisconnect source = (GDisconnect) n; + Role left = source.getLeftChild().toName(); + Role right = source.getRightChild().toName(); + return t.tf.global.GDisconnect(source, left, right); + } +} diff --git a/scribble-ast/src/main/java/org/scribble/del/global/GDoDel.java b/scribble-ast/src/main/java/org/scribble/del/global/GDoDel.java new file mode 100644 index 000000000..804d8185c --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/del/global/GDoDel.java @@ -0,0 +1,52 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.del.global; + +import java.util.List; + +import org.scribble.ast.ScribNode; +import org.scribble.ast.global.GDo; +import org.scribble.core.lang.context.ModuleContext; +import org.scribble.core.type.kind.NonRoleParamKind; +import org.scribble.core.type.name.GProtoName; +import org.scribble.core.type.name.Role; +import org.scribble.core.type.session.Arg; +import org.scribble.del.DoDel; +import org.scribble.util.RuntimeScribException; +import org.scribble.visit.GTypeTranslator; + +public class GDoDel extends DoDel implements GSimpleSessionNodeDel +{ + @Override + public org.scribble.core.type.session.global.GDo translate(ScribNode n, + GTypeTranslator t) + { + GDo source = (GDo) n; + + // Resolve full name -- CHECKME: factor out? cf., NameDisambiguator, DoDel::enter/leaveDisambiguation + GProtoName proto = source.getProtocolNameNode().toName(); + ModuleContext modc = t.getModuleContext(); + if (!modc.isVisibleProtocolDeclName(proto)) // CHECKME: should be already checked by NameDisamb? + { + throw new RuntimeScribException(source, + "Protocol decl not visible: " + proto); + } + GProtoName fullname = (GProtoName) modc // FIXME: sort out full name expansion between here and DoDel.leaveDisambiguation + .getVisibleProtocolDeclFullName(proto); + List roles = source.getRoleListChild().getRoles(); + List> params = source.getNonRoleListChild() + .getParamKindArgs(); + return t.tf.global.GDo(source, fullname, roles, params); + } +} diff --git a/scribble-ast/src/main/java/org/scribble/del/global/GInteractionSeqDel.java b/scribble-ast/src/main/java/org/scribble/del/global/GInteractionSeqDel.java new file mode 100644 index 000000000..d8357b925 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/del/global/GInteractionSeqDel.java @@ -0,0 +1,41 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.del.global; + +import java.util.LinkedList; +import java.util.List; + +import org.scribble.ast.ScribNode; +import org.scribble.ast.global.GInteractionSeq; +import org.scribble.ast.global.GSessionNode; +import org.scribble.core.type.session.global.GSeq; +import org.scribble.core.type.session.global.GType; +import org.scribble.del.InteractionSeqDel; +import org.scribble.visit.GTypeTranslator; + +public class GInteractionSeqDel extends InteractionSeqDel implements GDel +{ + + @Override + public GSeq translate(ScribNode n, GTypeTranslator t) + { + GInteractionSeq source = (GInteractionSeq) n; + List elems = new LinkedList<>(); + for (GSessionNode c : source.getInteractionChildren()) + { + elems.add((GType) c.visitWith(t)); // throws ScribbleException + } + return t.tf.global.GSeq(source, elems); + } +} diff --git a/scribble-ast/src/main/java/org/scribble/del/global/GMessageTransferDel.java b/scribble-ast/src/main/java/org/scribble/del/global/GMessageTransferDel.java new file mode 100644 index 000000000..4027352e7 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/del/global/GMessageTransferDel.java @@ -0,0 +1,67 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.del.global; + +import java.util.List; + +import org.scribble.ast.ScribNode; +import org.scribble.ast.global.GMsgTransfer; +import org.scribble.ast.name.simple.RoleNode; +import org.scribble.core.type.name.Role; +import org.scribble.core.type.session.Msg; +import org.scribble.del.MsgTransferDel; +import org.scribble.util.ScribException; +import org.scribble.visit.GTypeTranslator; +import org.scribble.visit.NameDisambiguator; + +public class GMessageTransferDel extends MsgTransferDel + implements GSimpleSessionNodeDel +{ + public GMessageTransferDel() + { + + } + + @Override + public ScribNode leaveDisambiguation(ScribNode child, + NameDisambiguator disamb, ScribNode visited) throws ScribException + { + GMsgTransfer gmt = (GMsgTransfer) visited; + Role src = gmt.getSourceChild().toName(); + List dests = gmt.getDestinationRoles(); + if (dests.contains(src)) + { + throw new ScribException(gmt.getSource(), + "[TODO] Self connections not supported: " + gmt); // TODO: refactor to Job validation pass + // CHECKME: subsumed by unconnected check ? + } + return gmt; + } + + @Override + public org.scribble.core.type.session.global.GMessageTransfer translate(ScribNode n, + GTypeTranslator t) + { + GMsgTransfer source = (GMsgTransfer) n; + Role src = source.getSourceChild().toName(); + List ds = source.getDestinationChildren(); + if (ds.size() > 1) + { + throw new RuntimeException("[TODO] multiple destination roles: " + source); + } + Role dst = ds.get(0).toName(); + Msg msg = source.getMessageNodeChild().toMsg(); + return t.tf.global.GMessageTransfer(source, src, msg, dst); + } +} diff --git a/scribble-ast/src/main/java/org/scribble/del/global/GProtoBlockDel.java b/scribble-ast/src/main/java/org/scribble/del/global/GProtoBlockDel.java new file mode 100644 index 000000000..2e1e63635 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/del/global/GProtoBlockDel.java @@ -0,0 +1,29 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.del.global; + +import org.scribble.ast.ScribNode; +import org.scribble.ast.global.GProtoBlock; +import org.scribble.core.type.session.global.GSeq; +import org.scribble.del.ProtoBlockDel; +import org.scribble.visit.GTypeTranslator; + +public class GProtoBlockDel extends ProtoBlockDel implements GDel +{ + @Override + public GSeq translate(ScribNode n, GTypeTranslator t) + { + return (GSeq) ((GProtoBlock) n).getInteractSeqChild().visitWith(t); + } +} diff --git a/scribble-ast/src/main/java/org/scribble/del/global/GProtoDeclDel.java b/scribble-ast/src/main/java/org/scribble/del/global/GProtoDeclDel.java new file mode 100644 index 000000000..9f49389b3 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/del/global/GProtoDeclDel.java @@ -0,0 +1,55 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.del.global; + +import java.util.List; +import java.util.stream.Collectors; + +import org.scribble.ast.Module; +import org.scribble.ast.ScribNode; +import org.scribble.ast.global.GProtoDecl; +import org.scribble.core.lang.ProtoMod; +import org.scribble.core.lang.global.GProtocol; +import org.scribble.core.type.kind.Global; +import org.scribble.core.type.kind.NonRoleParamKind; +import org.scribble.core.type.name.GProtoName; +import org.scribble.core.type.name.MemberName; +import org.scribble.core.type.name.Role; +import org.scribble.core.type.session.global.GSeq; +import org.scribble.del.ProtoDeclDel; +import org.scribble.visit.GTypeTranslator; + +public class GProtoDeclDel extends ProtoDeclDel implements GDel +{ + public GProtoDeclDel() + { + + } + + @Override + public GProtocol translate(ScribNode n, GTypeTranslator t) + { + GProtoDecl source = (GProtoDecl) n; + Module m = (Module) n.getParent(); + List mods = source.getModifierListChild().getModList().stream() + .map(x -> x.toProtoMod()).collect(Collectors.toList()); + GProtoName fullname = new GProtoName(m.getFullModuleName(), + source.getHeaderChild().getDeclName()); + List rs = source.getRoles(); + List> ps = source.getHeaderChild() + .getParamDeclListChild().getParams(); // CHECKME: make more uniform with source::getRoles ? + GSeq body = (GSeq) source.getDefChild().getBlockChild().visitWith(t); + return new GProtocol(source, mods, fullname, rs, ps, body); + } +} diff --git a/scribble-ast/src/main/java/org/scribble/del/global/GProtoDefDel.java b/scribble-ast/src/main/java/org/scribble/del/global/GProtoDefDel.java new file mode 100644 index 000000000..fe0e0cc3a --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/del/global/GProtoDefDel.java @@ -0,0 +1,24 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.del.global; + +import org.scribble.del.ProtoDefDel; + +public class GProtoDefDel extends ProtoDefDel +{ + public GProtoDefDel() + { + + } +} diff --git a/scribble-ast/src/main/java/org/scribble/del/global/GRecursionDel.java b/scribble-ast/src/main/java/org/scribble/del/global/GRecursionDel.java new file mode 100644 index 000000000..caf874371 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/del/global/GRecursionDel.java @@ -0,0 +1,36 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.del.global; + +import org.scribble.ast.ScribNode; +import org.scribble.ast.global.GRecursion; +import org.scribble.core.type.name.RecVar; +import org.scribble.core.type.session.global.GSeq; +import org.scribble.del.RecursionDel; +import org.scribble.visit.GTypeTranslator; + +public class GRecursionDel extends RecursionDel + implements GCompoundSessionNodeDel +{ + + @Override + public org.scribble.core.type.session.global.GRecursion translate(ScribNode n, + GTypeTranslator t) + { + GRecursion source = (GRecursion) n; + RecVar recvar = source.getRecVarChild().toName(); + GSeq block = (GSeq) source.getBlockChild().visitWith(t); + return t.tf.global.GRecursion(source, recvar, block); + } +} diff --git a/scribble-ast/src/main/java/org/scribble/del/global/GSessionNodeDel.java b/scribble-ast/src/main/java/org/scribble/del/global/GSessionNodeDel.java new file mode 100644 index 000000000..91556ec47 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/del/global/GSessionNodeDel.java @@ -0,0 +1,21 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.del.global; + +import org.scribble.del.SessionNodeDel; + +public interface GSessionNodeDel extends SessionNodeDel, GDel +{ + +} diff --git a/scribble-ast/src/main/java/org/scribble/del/global/GSimpleSessionNodeDel.java b/scribble-ast/src/main/java/org/scribble/del/global/GSimpleSessionNodeDel.java new file mode 100644 index 000000000..56098bbbd --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/del/global/GSimpleSessionNodeDel.java @@ -0,0 +1,19 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.del.global; + +public interface GSimpleSessionNodeDel extends GSessionNodeDel +{ + +} diff --git a/scribble-ast/src/main/java/org/scribble/del/global/GWrapDel.java b/scribble-ast/src/main/java/org/scribble/del/global/GWrapDel.java new file mode 100644 index 000000000..59b541314 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/del/global/GWrapDel.java @@ -0,0 +1,46 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.del.global; + +import org.scribble.ast.ScribNode; +import org.scribble.ast.global.GWrap; +import org.scribble.core.lang.global.GNode; +import org.scribble.del.BasicInteractionDel; +import org.scribble.util.ScribException; +import org.scribble.visit.GTypeTranslator; +import org.scribble.visit.NameDisambiguator; + +// TODO: make WrapDel (cf., G/LMessageTransferDel) +public class GWrapDel extends BasicInteractionDel //ConnectionActionDel + implements GSimpleSessionNodeDel +{ + public GWrapDel() + { + + } + + @Override + public ScribNode leaveDisambiguation(ScribNode child, + NameDisambiguator disamb, ScribNode visited) throws ScribException + { + GWrap gw = (GWrap) visited; + return gw; + } + + @Override + public GNode translate(ScribNode n, GTypeTranslator t) + { + throw new RuntimeException("[TODO] :" + n); + } +} diff --git a/scribble-ast/src/main/java/org/scribble/del/local/LAccDel.java b/scribble-ast/src/main/java/org/scribble/del/local/LAccDel.java new file mode 100644 index 000000000..898ec5f11 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/del/local/LAccDel.java @@ -0,0 +1,36 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.del.local; + +public class LAccDel extends LConnectionActionDel +{ + /*@Override + public void enterProjectedChoiceSubjectFixing(ScribNode parent, + ScribNode child, ProjectedChoiceSubjectFixer fixer) + { + fixer.setChoiceSubject(((LAcc) child).src.toName()); + } + + @Override + public void enterUnguardedChoiceDoProjectionCheck(ScribNode parent, + ScribNode child, UnguardedChoiceDoProjectionChecker checker) + throws ScribException + { + super.enterUnguardedChoiceDoProjectionCheck(parent, child, checker); + LAcc la = (LAcc) child; + UnguardedChoiceDoEnv env = checker.popEnv(); + env = env.setChoiceSubject(la.getSourceChild().toName()); + checker.pushEnv(env); + }*/ +} diff --git a/scribble-ast/src/main/java/org/scribble/del/local/LChoiceDel.java b/scribble-ast/src/main/java/org/scribble/del/local/LChoiceDel.java new file mode 100644 index 000000000..e9649fd4b --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/del/local/LChoiceDel.java @@ -0,0 +1,93 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.del.local; + +import org.scribble.del.ChoiceDel; + +public class LChoiceDel extends ChoiceDel implements LCompoundSessionNodeDel +{ + /*@Override + public ScribNode leaveUnguardedChoiceDoProjectionCheck(ScribNode parent, + ScribNode child, UnguardedChoiceDoProjectionChecker checker, + ScribNode visited) throws ScribException + { + Choice cho = (Choice) visited; + List benvs = cho.getBlocks().stream() + .map((b) -> (UnguardedChoiceDoEnv) b.del().env()) + .collect(Collectors.toList()); + UnguardedChoiceDoEnv merged = checker.popEnv().mergeContexts(benvs); + checker.pushEnv(merged); + return (Choice) super.leaveUnguardedChoiceDoProjectionCheck(parent, + child, checker, cho); + // Done merge of children here, super does merge into parent + } + + @Override + public ScribNode leaveProjectedChoiceDoPruning(ScribNode parent, + ScribNode child, ProjectedChoiceDoPruner pruner, ScribNode visited) + throws ScribException + { + LChoice lc = (LChoice) visited; + List blocks = lc.getBlocks().stream() + .filter(b -> !b.isEmpty()).collect(Collectors.toList()); + if (blocks.isEmpty()) + { + return null; + } + return lc.reconstruct(lc.subj, blocks); + } + + @Override + public ScribNode leaveProjectedChoiceSubjectFixing(ScribNode parent, + ScribNode child, ProjectedChoiceSubjectFixer fixer, ScribNode visited) + throws ScribException + { + LChoice lc = (LChoice) visited; + List blocks = lc.getBlocks(); + + Set subjs = blocks.stream() + .map((b) -> b.getInteractionSeq().getInteractions().get(0).inferLocalChoiceSubject(fixer)) + //.filter((r) -> !r.toString().equals(DummyProjectionRoleNode.DUMMY_PROJECTION_ROLE)) + .collect(Collectors.toSet()); + if (subjs.size() == 0) + { + //throw new RuntimeScribException("TODO: unable to infer projection subject: " + parent); + throw new RuntimeException("Shouldn't get in here: " + subjs); // FIXME: should be OK now by model-based WF + } + else + { + subjs = subjs.stream() + .map((r) -> fixer.isRecVarRole(r) + ? fixer.getChoiceSubject(new RecVar(r.toString())) : r) // Never needed? + .collect(Collectors.toSet()); + } + + // HACK? (for non- role-balanced choice cases) + subjs = subjs.stream().filter((s) -> s != null).collect(Collectors.toSet()); + + if (subjs.size() > 1) // Unnecessary: due to WF check in GChoiceDel.leaveInlinedPathCollection -- would be better as a check on locals than in projection anyway + { + String self = fixer.getModuleContext().root.getSimpleName().toString(); // HACK + self = self.substring(self.lastIndexOf('_')+1, self.length()); // FIXME: not sound (if role names include "_") + throw new ScribException(lc.getSource(), "Cannot project onto " + self + " due to inconsistent local choice subjects: " + subjs); // self not recorded -- can derive from LProtocolDecl RoleDeclList + //throw new RuntimeException("Shouldn't get in here: " + subjs); + } + RoleNode subj = (RoleNode) fixer.job.af.SimpleNameNode(null, RoleKind.KIND, // FIXME? null source OK? + //blocks.get(0).getInteractionSeq().getInteractions().get(0).inferLocalChoiceSubject(fixer).toString()); + subjs.iterator().next().toString()); + fixer.setChoiceSubject(subj.toName()); + LChoice projection = fixer.job.af.LChoice(lc.getSource(), subj, blocks); + return projection; + }*/ +} diff --git a/scribble-ast/src/main/java/org/scribble/del/local/LClientWrapDel.java b/scribble-ast/src/main/java/org/scribble/del/local/LClientWrapDel.java new file mode 100644 index 000000000..2caa1fa05 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/del/local/LClientWrapDel.java @@ -0,0 +1,27 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.del.local; + +import org.scribble.del.BasicInteractionDel; + +public class LClientWrapDel extends BasicInteractionDel // LWrapDel + implements LSimpleSessionNodeDel +{ + /*@Override + public void enterProjectedChoiceSubjectFixing(ScribNode parent, + ScribNode child, ProjectedChoiceSubjectFixer fixer) + { + fixer.setChoiceSubject(((LClientWrap) child).getClientChild().toName()); + }*/ +} diff --git a/scribble-ast/src/main/java/org/scribble/del/local/LCompoundSessionNodeDel.java b/scribble-ast/src/main/java/org/scribble/del/local/LCompoundSessionNodeDel.java new file mode 100644 index 000000000..842703aa7 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/del/local/LCompoundSessionNodeDel.java @@ -0,0 +1,19 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.del.local; + +public interface LCompoundSessionNodeDel extends LSessionNodeDel +{ + +} diff --git a/scribble-ast/src/main/java/org/scribble/del/local/LConnectionActionDel.java b/scribble-ast/src/main/java/org/scribble/del/local/LConnectionActionDel.java new file mode 100644 index 000000000..2d78eebc1 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/del/local/LConnectionActionDel.java @@ -0,0 +1,22 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.del.local; + +import org.scribble.del.ConnectionActionDel; + +public abstract class LConnectionActionDel extends ConnectionActionDel + implements LSimpleSessionNodeDel +{ + +} diff --git a/scribble-ast/src/main/java/org/scribble/del/local/LContinueDel.java b/scribble-ast/src/main/java/org/scribble/del/local/LContinueDel.java new file mode 100644 index 000000000..b278e2893 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/del/local/LContinueDel.java @@ -0,0 +1,21 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.del.local; + +import org.scribble.del.ContinueDel; + +public class LContinueDel extends ContinueDel implements LSimpleSessionNodeDel +{ + +} diff --git a/scribble-ast/src/main/java/org/scribble/del/local/LDel.java b/scribble-ast/src/main/java/org/scribble/del/local/LDel.java new file mode 100644 index 000000000..596e1937f --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/del/local/LDel.java @@ -0,0 +1,21 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.del.local; + +import org.scribble.del.ScribDel; + +public interface LDel extends ScribDel +{ + +} diff --git a/scribble-ast/src/main/java/org/scribble/del/local/LDisconnectDel.java b/scribble-ast/src/main/java/org/scribble/del/local/LDisconnectDel.java new file mode 100644 index 000000000..1f7236070 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/del/local/LDisconnectDel.java @@ -0,0 +1,35 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.del.local; + +import org.scribble.del.ConnectionActionDel; + +public class LDisconnectDel extends ConnectionActionDel + implements LSimpleSessionNodeDel +{ + /*@Override + public LDisconnect leaveEGraphBuilding(ScribNode parent, ScribNode child, EGraphBuilder builder, ScribNode visited) throws ScribbleException + { + LDisconnect ld = (LDisconnect) visited; + Role peer = ld.peer.toName(); + builder.util.addEdge(builder.util.getEntry(), builder.job.ef.newEDisconnect(peer), builder.util.getExit()); + return (LDisconnect) super.leaveEGraphBuilding(parent, child, builder, ld); + } + + @Override + public void enterProjectedChoiceSubjectFixing(ScribNode parent, ScribNode child, ProjectedChoiceSubjectFixer fixer) + { + fixer.setChoiceSubject(((LDisconnect) child).src.toName()); + }*/ +} diff --git a/scribble-ast/src/main/java/org/scribble/del/local/LDoDel.java b/scribble-ast/src/main/java/org/scribble/del/local/LDoDel.java new file mode 100644 index 000000000..124f30c30 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/del/local/LDoDel.java @@ -0,0 +1,85 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.del.local; + +import org.scribble.del.DoDel; + +public class LDoDel extends DoDel implements LSimpleSessionNodeDel +{ + /*// Pre: this pass is only run on projections (LProjectionDeclDel has source global protocol info) + @Override + public ScribNode leaveProjectedRoleDeclFixing(ScribNode parent, + ScribNode child, ProjectedRoleDeclFixer fixer, ScribNode visited) + throws ScribException + { + JobContext jc = fixer.job.getContext(); + LDo ld = (LDo) visited; + LProtoDecl lpd = ld.getTargetProtoDecl(jc, fixer.getModuleContext()); + + // do role args are currently as inherited from the global type -- so need to derive role map against the global protocol header + // Doing it off the global roledecls allows this to be done in one pass, but would probably be easier to split into two (e.g. 1st cache the proposed changes, 2nd write all changes -- the problem with a single pass is e.g. looking up the localdecl info while localdecls are being rewritten during the pass) + // Could possibly factor out rolemap making with SubprotocolVisitor a bit, but there it maps to RoleNode and works off a root map + GProtoName source = ((LProjectionDeclDel) lpd.del()).getSourceProto(); + GProtoDecl gpd = (GProtoDecl) jc.getModule(source.getPrefix()).getProtoDecl(source.getSimpleName()); + Iterator roleargs = ld.roles.getDoArgs().iterator(); + Map rolemap = gpd.header.roledecls.getRoles().stream().collect( + Collectors.toMap(r -> r, r -> roleargs.next().val.toName())); + Set occs = ((LProtoDeclDel) lpd.del()).getProtoDeclContext().getRoleOccurrences().stream().map(r -> + rolemap.get(r)).collect(Collectors.toSet()); + + List ras = ld.roles.getDoArgs().stream().filter(ra -> occs.contains(ra.val.toName())).collect(Collectors.toList()); + RoleArgList roles = ld.roles.reconstruct(ras); + return super.leaveProjectedRoleDeclFixing(parent, child, fixer, ld.reconstruct(roles, ld.args, ld.getProtoNameNode())); + } + + @Override + public ScribNode leaveUnguardedChoiceDoProjectionCheck(ScribNode parent, ScribNode child, UnguardedChoiceDoProjectionChecker checker, ScribNode visited) throws ScribException + { + /* //if (checker.isCycle()) + if (checker.isRootedCycle()) // ChoiceUnguardedSubprotocolChecker is a (regular) SubprotocolVisitor which pushes a subprotosig on root decl entry (ProjectedSubprotocolPruner.visit) + // Check for "rooted" cycle to ensure it's specifically the cycle from the root proto decl (back) to the target do + // FIXME: but cycle to specific "target do" is not ensured: could be another instance of a do with the same subprotosig... an inherent issue of the current subprotocolvisitor framework + + // FIXME: this algorithm works for some use cases for is still wrong (prunes some that it shouldn't -- e.g. mutually pruneable choice-unguarded do's) + // *** what we really need is to check for 0 inferred choice subjects up to recursion back (if any) to to the parent choice -- problem is current framework doesn't make identifying (e.g. ==) the original choice easy *** + // the issue is arising since WF was relaxed to allow unbalanced choice case roles: with balanced, subject inference is always fine as long as roles are used? (and prev assumed no choice-unguarded do's?) + { + //System.out.println("ABC: " + checker.peekEnv().subjs + ", " + checker.SHOULD_PRUNE); + + //if (checker.peekEnv().shouldPrune()) + if (checker.peekEnv().subjs.isEmpty()) + { + /*ChoiceUnguardedSubprotocolEnv env = checker.popEnv(); + checker.pushEnv(env.disablePrune());* / + //checker.enablePrune(); + } + }* / + return super.leaveUnguardedChoiceDoProjectionCheck(parent, child, checker, visited); + + + // for each do: check shouldPrune condition by following the control flow: if terminates or cycles with no actions then prune + // Let the main pruning visitor be a regular visitor, and use the subprotocol visitor to follow the calls for pruning analysis + + //FIXME: maybe similar to project roledecl fixing? use role occurrences saved in protocoldecl? + // role occurrences collected by RoleCollector which is indeed subprotocol visitor + // problem is RoleCollector currently comes after subject fixing... but maybe it doesn't need to collect subject roles in the end? due to WF enabling checks? + + //..not role collection, that's a "may" usage of roles + //..should be: start from a candidate unguarded-do inside a choice: want to know if this choice case should be removed + //......follow protocol flow through do until either end or return to this choice, looking for actions + // ... but look only on direct path or across all branches? + + //...or else it should be: start from the target protocoldecl and go through to the candidate do (cf grecursion.prune) + }*/ +} diff --git a/scribble-ast/src/main/java/org/scribble/del/local/LInteractionSeqDel.java b/scribble-ast/src/main/java/org/scribble/del/local/LInteractionSeqDel.java new file mode 100644 index 000000000..0a63dc5b3 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/del/local/LInteractionSeqDel.java @@ -0,0 +1,44 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.del.local; + +import org.scribble.del.InteractionSeqDel; + +public class LInteractionSeqDel extends InteractionSeqDel implements LDel +{ + /*@Override + public ScribNode leaveProjectedChoiceDoPruning(ScribNode parent, + ScribNode child, ProjectedChoiceDoPruner pruner, ScribNode visited) + throws ScribException + { + LInteractionSeq lc = (LInteractionSeq) visited; + List actions = lc.getInteractionChildren().stream() + .filter(li -> li != null).collect(Collectors.toList()); + return lc.reconstruct(actions); + }*/ + + /*// Duplicated from GInteractionSeq + @Override + public LInteractionSeq leaveRecRemoval(ScribNode parent, ScribNode child, RecRemover rem, ScribNode visited) + throws ScribException + { + LInteractionSeq lis = (LInteractionSeq) visited; + List lins = lis.getInteractions().stream().flatMap((li) -> + (li instanceof LRecursion && rem.toRemove(((LRecursion) li).recvar.toName())) + ? ((LRecursion) li).getBlock().getInteractionSeq().getInteractions().stream() + : Stream.of(li) + ).collect(Collectors.toList()); + return rem.job.af.LInteractionSeq(lis.getSource(), lins); + }*/ +} diff --git a/scribble-ast/src/main/java/org/scribble/del/local/LMsgTransferDel.java b/scribble-ast/src/main/java/org/scribble/del/local/LMsgTransferDel.java new file mode 100644 index 000000000..cc94f4a02 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/del/local/LMsgTransferDel.java @@ -0,0 +1,22 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.del.local; + +import org.scribble.del.MsgTransferDel; + +public abstract class LMsgTransferDel extends MsgTransferDel + implements LSimpleSessionNodeDel +{ + +} diff --git a/scribble-ast/src/main/java/org/scribble/del/local/LProjectionDeclDel.java b/scribble-ast/src/main/java/org/scribble/del/local/LProjectionDeclDel.java new file mode 100644 index 000000000..7e7aac52b --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/del/local/LProjectionDeclDel.java @@ -0,0 +1,47 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.del.local; + +public class LProjectionDeclDel extends LProtoDeclDel +{ + public LProjectionDeclDel() + { + + } + + /*@Override + public ScribNode leaveProjectedRoleDeclFixing(ScribNode parent, + ScribNode child, ProjectedRoleDeclFixer fixer, ScribNode visited) + throws ScribException + { + LProjectionDecl lpd = (LProjectionDecl) visited; + LProtoHeader hdrtmp = lpd.getHeaderChild(); + // FIXME: ensure all role params are used, to avoid empty roledecllist + Set occs = ((LProtoDeclDel) lpd.del()).getProtoDeclContext() + .getRoleOccurrences(); + List rds = hdrtmp.getRoleDeclListChild().getDeclChildren() + .stream().filter(rd -> occs.contains(rd.getDeclName())) + .collect(Collectors.toList()); + RoleDeclList rdl = fixer.job.af + .RoleDeclList(hdrtmp.getRoleDeclListChild().getSource(), rds); + LProtoHeader hdr = (LProtoHeader) hdrtmp.reconstruct(hdrtmp.getNameNodeChild(), + hdrtmp.getParamDeclListChild(), rdl); + LProjectionDecl fixed = (LProjectionDecl) lpd.reconstruct(lpd.getModifierListChild(), hdr, lpd.getDefChild()); + + fixer.job.debugPrintln("\n[DEBUG] Projected " + lpd//.getParentChild() + + " for " + lpd.getSelfRole() + ":\n" + fixed); + + return super.leaveProjectedRoleDeclFixing(parent, child, fixer, fixed); + }*/ +} diff --git a/scribble-ast/src/main/java/org/scribble/del/local/LProtoBlockDel.java b/scribble-ast/src/main/java/org/scribble/del/local/LProtoBlockDel.java new file mode 100644 index 000000000..e4481aaaf --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/del/local/LProtoBlockDel.java @@ -0,0 +1,21 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.del.local; + +import org.scribble.del.ProtoBlockDel; + +public class LProtoBlockDel extends ProtoBlockDel implements LDel +{ + +} diff --git a/scribble-ast/src/main/java/org/scribble/del/local/LProtoDeclDel.java b/scribble-ast/src/main/java/org/scribble/del/local/LProtoDeclDel.java new file mode 100644 index 000000000..f6240f0fe --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/del/local/LProtoDeclDel.java @@ -0,0 +1,25 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.del.local; + +import org.scribble.core.type.kind.Local; +import org.scribble.del.ProtoDeclDel; + +public class LProtoDeclDel extends ProtoDeclDel +{ + public LProtoDeclDel() + { + + } +} diff --git a/scribble-ast/src/main/java/org/scribble/del/local/LProtoDefDel.java b/scribble-ast/src/main/java/org/scribble/del/local/LProtoDefDel.java new file mode 100644 index 000000000..3fe77f1a2 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/del/local/LProtoDefDel.java @@ -0,0 +1,24 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.del.local; + +import org.scribble.del.ProtoDefDel; + +public class LProtoDefDel extends ProtoDefDel +{ + public LProtoDefDel() + { + + } +} diff --git a/scribble-ast/src/main/java/org/scribble/del/local/LRecursionDel.java b/scribble-ast/src/main/java/org/scribble/del/local/LRecursionDel.java new file mode 100644 index 000000000..0ca64ccd7 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/del/local/LRecursionDel.java @@ -0,0 +1,48 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.del.local; + +import org.scribble.del.RecursionDel; + +public class LRecursionDel extends RecursionDel + implements LCompoundSessionNodeDel +{ + /*@Override + public ScribNode leaveUnguardedChoiceDoProjectionCheck(ScribNode parent, + ScribNode child, UnguardedChoiceDoProjectionChecker checker, + ScribNode visited) throws ScribException + { + Recursion rec = (Recursion) visited; + UnguardedChoiceDoEnv merged = checker.popEnv() + .mergeContext((UnguardedChoiceDoEnv) rec.getBlockChild().del().env()); + checker.pushEnv(merged); + return (Recursion) super.leaveUnguardedChoiceDoProjectionCheck(parent, + child, checker, rec); + } + + @Override + public void enterProjectedChoiceSubjectFixing(ScribNode parent, + ScribNode child, ProjectedChoiceSubjectFixer fixer) + { + fixer.pushRec(((LRecursion) child).getRecVarChild.toName()); + } + + @Override + public ScribNode leaveProjectedChoiceSubjectFixing(ScribNode parent, + ScribNode child, ProjectedChoiceSubjectFixer fixer, ScribNode visited) + { + fixer.popRec(((LRecursion) child).getRecVarChild().toName()); + return visited; + }*/ +} diff --git a/scribble-ast/src/main/java/org/scribble/del/local/LRecvDel.java b/scribble-ast/src/main/java/org/scribble/del/local/LRecvDel.java new file mode 100644 index 000000000..cd6b6786d --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/del/local/LRecvDel.java @@ -0,0 +1,36 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.del.local; + +public class LRecvDel extends LMsgTransferDel +{ + /*@Override + public void enterProjectedChoiceSubjectFixing(ScribNode parent, + ScribNode child, ProjectedChoiceSubjectFixer fixer) + { + fixer.setChoiceSubject(((LRecv) child).src.toName()); + } + + @Override + public void enterUnguardedChoiceDoProjectionCheck(ScribNode parent, + ScribNode child, UnguardedChoiceDoProjectionChecker checker) + throws ScribException + { + super.enterUnguardedChoiceDoProjectionCheck(parent, child, checker); + LRecv lr = (LRecv) child; + UnguardedChoiceDoEnv env = checker.popEnv(); + env = env.setChoiceSubject(lr.getSourceChild().toName()); + checker.pushEnv(env); + }*/ +} diff --git a/scribble-ast/src/main/java/org/scribble/del/local/LReqDel.java b/scribble-ast/src/main/java/org/scribble/del/local/LReqDel.java new file mode 100644 index 000000000..6980bf896 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/del/local/LReqDel.java @@ -0,0 +1,24 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.del.local; + +public class LReqDel extends LConnectionActionDel +{ + /*@Override + public void enterProjectedChoiceSubjectFixing(ScribNode parent, + ScribNode child, ProjectedChoiceSubjectFixer fixer) + { + fixer.setChoiceSubject(((LReq) child).getSourceChild().toName()); + }*/ +} diff --git a/scribble-ast/src/main/java/org/scribble/del/local/LSendDel.java b/scribble-ast/src/main/java/org/scribble/del/local/LSendDel.java new file mode 100644 index 000000000..072411970 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/del/local/LSendDel.java @@ -0,0 +1,35 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.del.local; + +public class LSendDel extends LMsgTransferDel +{ + /*// Could make a LMsgTransferDel to factor this out with LReceiveDel + @Override + public void enterProjectedChoiceSubjectFixing(ScribNode parent, + ScribNode child, ProjectedChoiceSubjectFixer fixer) + { + fixer.setChoiceSubject(((LSend) child).src.toName()); + } + + @Override + public LMsgTransfer leaveExplicitCorrelationCheck(ScribNode parent, + ScribNode child, ExplicitCorrelationChecker checker, ScribNode visited) + throws ScribException + { + LMsgTransfer lmt = (LMsgTransfer) visited; + checker.pushEnv(checker.popEnv().disableAccept()); + return lmt; + }*/ +} diff --git a/scribble-ast/src/main/java/org/scribble/del/local/LServerWrapDel.java b/scribble-ast/src/main/java/org/scribble/del/local/LServerWrapDel.java new file mode 100644 index 000000000..51cd0ca95 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/del/local/LServerWrapDel.java @@ -0,0 +1,40 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.del.local; + +import org.scribble.del.BasicInteractionDel; + +public class LServerWrapDel extends BasicInteractionDel // LWrapDel + implements LSimpleSessionNodeDel +{ + + /*@Override + public void enterProjectedChoiceSubjectFixing(ScribNode parent, + ScribNode child, ProjectedChoiceSubjectFixer fixer) + { + fixer.setChoiceSubject(((LServerWrap) child).getClientChild().toName()); + } + + @Override + public void enterUnguardedChoiceDoProjectionCheck(ScribNode parent, + ScribNode child, UnguardedChoiceDoProjectionChecker checker) + throws ScribException + { + super.enterUnguardedChoiceDoProjectionCheck(parent, child, checker); + LServerWrap la = (LServerWrap) child; + UnguardedChoiceDoEnv env = checker.popEnv(); + env = env.setChoiceSubject(la.getClientChild().toName()); + checker.pushEnv(env); + }*/ +} diff --git a/scribble-ast/src/main/java/org/scribble/del/local/LSessionNodeDel.java b/scribble-ast/src/main/java/org/scribble/del/local/LSessionNodeDel.java new file mode 100644 index 000000000..1c379a4d3 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/del/local/LSessionNodeDel.java @@ -0,0 +1,21 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.del.local; + +import org.scribble.del.SessionNodeDel; + +public interface LSessionNodeDel extends SessionNodeDel, LDel +{ + +} diff --git a/scribble-ast/src/main/java/org/scribble/del/local/LSimpleSessionNodeDel.java b/scribble-ast/src/main/java/org/scribble/del/local/LSimpleSessionNodeDel.java new file mode 100644 index 000000000..df94d5c19 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/del/local/LSimpleSessionNodeDel.java @@ -0,0 +1,19 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.del.local; + +public interface LSimpleSessionNodeDel extends LSessionNodeDel +{ + +} diff --git a/scribble-ast/src/main/java/org/scribble/del/name/qualified/DataNameNodeDel.java b/scribble-ast/src/main/java/org/scribble/del/name/qualified/DataNameNodeDel.java new file mode 100644 index 000000000..d70a3f467 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/del/name/qualified/DataNameNodeDel.java @@ -0,0 +1,64 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.del.name.qualified; + +import org.antlr.runtime.CommonToken; +import org.scribble.ast.DataDecl; +import org.scribble.ast.ScribNode; +import org.scribble.ast.name.qualified.DataNameNode; +import org.scribble.ast.name.simple.IdNode; +import org.scribble.core.lang.context.ModuleContext; +import org.scribble.core.type.name.DataName; +import org.scribble.del.ScribDelBase; +import org.scribble.util.ScribException; +import org.scribble.visit.NameDisambiguator; + +public class DataNameNodeDel extends ScribDelBase +{ + public DataNameNodeDel() + { + + } + + // Is this needed? Or DataTypeNodes always created from AmbigNameNode? (in this same pass) + @Override + public ScribNode leaveDisambiguation(ScribNode child, + NameDisambiguator disamb, ScribNode visited) throws ScribException + { + ScribNode parent = child.getParent(); + if (parent instanceof DataDecl) // Hacky? don't want to do for decl simplenames (generally, don't do if parent is namedeclnode) + { + return visited; + } + ModuleContext mc = disamb.getModuleContext(); + DataNameNode dtn = (DataNameNode) visited; + DataName dt = dtn.toName(); + if (!mc.isVisibleDataType(dt)) + { + throw new ScribException(dtn.getSource(), + "Data type not visible: " + dt); + } + DataName fullname = mc.getVisibleDataTypeFullName(dt); + /*return (DataTypeNode) disamb.job.config.af.QualifiedNameNode( + dtn.getSource(), DataTypeKind.KIND, fullname.getElements());*/ + DataNameNode res = new DataNameNode(dtn.token); + for (String e : fullname.getElements()) + { + IdNode n = new IdNode(new CommonToken(23, e)); // FIXME TODO: refactor ast into parser module to access token type constants + res.addChild(n); + } + return res; + // Don't keep original del (so not using clone) + } +} diff --git a/scribble-ast/src/main/java/org/scribble/del/name/qualified/SigNameNodeDel.java b/scribble-ast/src/main/java/org/scribble/del/name/qualified/SigNameNodeDel.java new file mode 100644 index 000000000..a2d73456c --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/del/name/qualified/SigNameNodeDel.java @@ -0,0 +1,59 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.del.name.qualified; + +import org.antlr.runtime.CommonToken; +import org.scribble.ast.SigDecl; +import org.scribble.ast.ScribNode; +import org.scribble.ast.name.qualified.SigNameNode; +import org.scribble.ast.name.simple.IdNode; +import org.scribble.core.lang.context.ModuleContext; +import org.scribble.core.type.name.SigName; +import org.scribble.del.ScribDelBase; +import org.scribble.util.ScribException; +import org.scribble.visit.NameDisambiguator; + +public class SigNameNodeDel extends ScribDelBase +{ + public SigNameNodeDel() + { + + } + + // Is this needed? Or DataTypeNodes always created from AmbigNameNode? (in this same pass) + @Override + public ScribNode leaveDisambiguation(ScribNode child, + NameDisambiguator disamb, ScribNode visited) throws ScribException + { + ScribNode parent = child.getParent(); + if (parent instanceof SigDecl) // Hacky? don't want to do for decl simplenames (generally, don't do if parent is namedeclnode) + { + return visited; + } + ModuleContext mc = disamb.getModuleContext(); + SigNameNode msnn = (SigNameNode) visited; + SigName fullname = + mc.getVisibleMessageSigNameFullName(msnn.toName()); + /*return (MessageSigNameNode) disamb.job.config.af.QualifiedNameNode( + msnn.getSource(), SigKind.KIND, fullname.getElements());*/ + SigNameNode res = new SigNameNode(msnn.token); + for (String e : fullname.getElements()) + { + IdNode n = new IdNode(new CommonToken(23, e)); // FIXME TODO: refactor ast into parser module to access token type constants + res.addChild(n); + } + return res; + // Don't keep original del (so not using clone) + } +} diff --git a/scribble-ast/src/main/java/org/scribble/del/name/simple/AmbigNameNodeDel.java b/scribble-ast/src/main/java/org/scribble/del/name/simple/AmbigNameNodeDel.java new file mode 100644 index 000000000..180ac5bc4 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/del/name/simple/AmbigNameNodeDel.java @@ -0,0 +1,86 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.del.name.simple; + +import java.util.List; +import java.util.stream.Collectors; + +import org.scribble.ast.MsgTransfer; +import org.scribble.ast.PayElem; +import org.scribble.ast.ScribNode; +import org.scribble.ast.name.simple.AmbigNameNode; +import org.scribble.ast.name.simple.IdNode; +import org.scribble.core.lang.context.ModuleContext; +import org.scribble.core.type.kind.DataKind; +import org.scribble.core.type.kind.NonRoleParamKind; +import org.scribble.core.type.name.AmbigName; +import org.scribble.del.ScribDelBase; +import org.scribble.util.ScribException; +import org.scribble.visit.NameDisambiguator; + +public class AmbigNameNodeDel extends ScribDelBase +{ + public AmbigNameNodeDel() + { + + } + + @Override + public ScribNode leaveDisambiguation(ScribNode child, + NameDisambiguator disamb, ScribNode visited) throws ScribException + { + ScribNode parent = child.getParent(); + ModuleContext modc = disamb.getModuleContext(); + AmbigNameNode a = (AmbigNameNode) visited; + AmbigName name = a.toName(); + // By well-formedness (checked later), payload type and parameter names are distinct + // CHECKME: are conflicts checked elsewhere? -- ? + if (modc.isDataTypeVisible(name.toDataName())) + { + // CHECKME HACK: MsgTransfer assumes MessageNode (cast in visitChildren), so this needs to be caught here + // CHECKME: any other similar cases? + if (parent instanceof MsgTransfer) + { + throw new ScribException(a.getSource(), + "Invalid occurrence of data name: " + parent); + } + List elems = a.getElements().stream() + .map(x -> disamb.job.config.af.IdNode(null, x)) + .collect(Collectors.toList()); + return disamb.job.config.af.DataNameNode(a.token, elems); + } + else if (modc.isMessageSigNameVisible(name.toSigName())) + { + if (parent instanceof PayElem) // FIXME HACK + { + throw new ScribException(a.getSource(), + "Invalid occurrence of message signature name: " + parent); + } + List elems = a.getElements().stream() + .map(x -> disamb.job.config.af.IdNode(null, x)) + .collect(Collectors.toList()); + return disamb.job.config.af.SigNameNode(a.token, elems); + } + else if (disamb.isBoundParam(name)) + { + NonRoleParamKind kind = disamb.getParamKind(name); + return kind.equals(DataKind.KIND) + ? disamb.job.config.af.DataParamNode(a.token, a.getText()) + // else if(kind.equals(SigKind.KIND)) + : disamb.job.config.af.SigParamNode(a.token, a.getText()); + } + throw new ScribException(a.getSource(), + "Cannot disambiguate name: " + name); + } +} diff --git a/scribble-ast/src/main/java/org/scribble/del/name/simple/NonRoleParamNodeDel.java b/scribble-ast/src/main/java/org/scribble/del/name/simple/NonRoleParamNodeDel.java new file mode 100644 index 000000000..e644452b5 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/del/name/simple/NonRoleParamNodeDel.java @@ -0,0 +1,24 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.del.name.simple; + +import org.scribble.del.ScribDelBase; + +public class NonRoleParamNodeDel extends ScribDelBase +{ + public NonRoleParamNodeDel() + { + + } +} diff --git a/scribble-ast/src/main/java/org/scribble/del/name/simple/RecVarNodeDel.java b/scribble-ast/src/main/java/org/scribble/del/name/simple/RecVarNodeDel.java new file mode 100644 index 000000000..8cbad895f --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/del/name/simple/RecVarNodeDel.java @@ -0,0 +1,44 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.del.name.simple; + +import org.scribble.ast.ScribNode; +import org.scribble.ast.name.simple.RecVarNode; +import org.scribble.core.type.name.RecVar; +import org.scribble.del.ScribDelBase; +import org.scribble.util.ScribException; +import org.scribble.visit.NameDisambiguator; + +public class RecVarNodeDel extends ScribDelBase +{ + public RecVarNodeDel() + { + + } + + @Override + public RecVarNode leaveDisambiguation(ScribNode child, + NameDisambiguator disamb, ScribNode visited) throws ScribException + { + // Consistent with bound RoleNode checking + RecVarNode rn = (RecVarNode) visited; + RecVar rv = rn.toName(); + if (!disamb.isBoundRecVar(rv)) + { + throw new ScribException(rn.getSource(), + "Rec variable not bound: " + rn); + } + return (RecVarNode) super.leaveDisambiguation(child, disamb, rn); + } +} diff --git a/scribble-ast/src/main/java/org/scribble/del/name/simple/RoleNodeDel.java b/scribble-ast/src/main/java/org/scribble/del/name/simple/RoleNodeDel.java new file mode 100644 index 000000000..e96b27f1e --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/del/name/simple/RoleNodeDel.java @@ -0,0 +1,40 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.del.name.simple; + +import org.scribble.ast.ScribNode; +import org.scribble.ast.name.simple.RoleNode; +import org.scribble.del.ScribDelBase; +import org.scribble.util.ScribException; +import org.scribble.visit.NameDisambiguator; + +public class RoleNodeDel extends ScribDelBase +{ + public RoleNodeDel() + { + + } + + @Override + public RoleNode leaveDisambiguation(ScribNode child, NameDisambiguator disamb, + ScribNode visited) throws ScribException + { + RoleNode rn = (RoleNode) visited; + if (!disamb.isBoundRole(rn.toName())) // Added on RoleDecl entry + { + throw new ScribException(rn.getSource(), "Role not bound: " + rn); + } + return rn; + } +} diff --git a/scribble-ast/src/main/java/org/scribble/job/Job.java b/scribble-ast/src/main/java/org/scribble/job/Job.java new file mode 100644 index 000000000..153b7fbcc --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/job/Job.java @@ -0,0 +1,293 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.job; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +import org.scribble.ast.AstFactory; +import org.scribble.ast.ImportDecl; +import org.scribble.ast.Module; +import org.scribble.ast.ModuleDecl; +import org.scribble.ast.NonProtoDecl; +import org.scribble.ast.global.GProtoDecl; +import org.scribble.ast.local.LProjectionDecl; +import org.scribble.ast.name.qualified.ModuleNameNode; +import org.scribble.ast.name.simple.IdNode; +import org.scribble.core.job.Core; +import org.scribble.core.job.CoreArgs; +import org.scribble.core.lang.global.GProtocol; +import org.scribble.core.lang.local.LProjection; +import org.scribble.core.type.kind.DataKind; +import org.scribble.core.type.kind.Kind; +import org.scribble.core.type.kind.Local; +import org.scribble.core.type.kind.SigKind; +import org.scribble.core.type.name.DataName; +import org.scribble.core.type.name.GProtoName; +import org.scribble.core.type.name.MemberName; +import org.scribble.core.type.name.ModuleName; +import org.scribble.core.type.name.ProtoName; +import org.scribble.core.type.name.Role; +import org.scribble.core.type.name.SigName; +import org.scribble.core.type.session.STypeFactory; +import org.scribble.core.type.session.global.GTypeFactoryImpl; +import org.scribble.core.type.session.local.LSeq; +import org.scribble.core.type.session.local.LTypeFactoryImpl; +import org.scribble.core.visit.gather.NonProtoDepsGatherer; +import org.scribble.core.visit.gather.ProtoDepsCollector; +import org.scribble.del.DelFactory; +import org.scribble.util.LProjectionTranslator; +import org.scribble.util.ScribException; +import org.scribble.visit.AstVisitor; +import org.scribble.visit.GTypeTranslator; +import org.scribble.visit.VisitorFactory; +import org.scribble.visit.VisitorFactoryImpl; + +// A "compiler job" front-end that supports operations comprising visitor passes over the AST and/or local/global models +public class Job +{ + public final JobConfig config; // Immutable + + private final JobContext context; // Mutable: Visitor passes update modules + + private Core core; + + public Job(ModuleName mainFullname, Map args, + Map parsed, AstFactory af, DelFactory df) + throws ScribException + { + // CHECKME(?): main modname comes from the inlined mod decl -- check for issues if this clashes with an existing file system resource + VisitorFactory vf = newVisitorFactory(); + STypeFactory tf = newSTypeFactory(); + this.config = newJobConfig(mainFullname, args, af, df, vf, tf); + this.context = newJobContext(this, parsed); // Single instance per Job, should not be shared between Jobs + } + + protected VisitorFactory newVisitorFactory() + { + return new VisitorFactoryImpl(); + } + + // Used by GTypeTranslator (cf. getCore) + protected STypeFactory newSTypeFactory() + { + return new STypeFactory(new GTypeFactoryImpl(), + new LTypeFactoryImpl()); + } + + // A Scribble extension should override newJobConfig/Context/Core as appropriate + protected JobConfig newJobConfig(ModuleName mainFullname, + Map args, AstFactory af, DelFactory df, + VisitorFactory vf, STypeFactory tf) + { + return new JobConfig(mainFullname, args, af, df, vf, tf); + } + + // A Scribble extension should override newJobConfig/Context/Core as appropriate + protected JobContext newJobContext(Job job, + Map parsed) throws ScribException + { + return new JobContext(this, parsed); + } + + // First run Visitor passes, then call toJob + // Base implementation: ambigname disamb pass only + public void runPasses() throws ScribException + { + verbosePrintPass("Starting Job passes on:"); + for (ModuleName fullname : this.context.getFullModuleNames()) + { + verbosePrintln(this.context.getModule(fullname).toString()); + } + + // Disamb is a "leftover" aspect of parsing -- so not in core + // N.B. disamb is mainly w.r.t. ambignames -- e.g., doesn't fully qualify names (currently mainly done by imed translation) + // CHECKME: disamb also currently does checks like do-arg kind and arity -- refactor into core? -- also does, e.g., distinct roledecls, protodecls, etc. + runVisitorPassOnAllModules(this.config.vf.DelDecorator(this)); + // Currently, only for the simple name nodes "constructed directly" by parser, e.g., t=ID -> ID<...Node>[$t] + // CHECKME: refactor to construct (and set del) all uniformly via ScribTreeAdaptor, to deprecate DelDecorator? + + runVisitorPassOnAllModules(this.config.vf.NameDisambiguator(this)); // Includes validating names used in subprotocol calls.. + } + + // "Finalises" this Job -- initialises the Job at this point, and cannot run futher Visitor passes on Job + // So, typically, Job passes should be finished before calling this + // Core passes may subsequently mutate Core(Context) though + // CHECKME: revise this pattern? -- maybe fork Core for a snapshot of current Job(Context) -- and, possibly, convert Core back to Job + public final Core getCore() + { + if (this.core == null) + { + Map parsed = this.context.getParsed(); + Set imeds = new HashSet<>(); + for (ModuleName fullname : parsed.keySet()) + { + GTypeTranslator t = this.config.vf.GTypeTranslator(this, fullname, + this.config.tf); + // CHECKME: factor out STypeTranslator, for future local parsing + Module m = parsed.get(fullname); + for (GProtoDecl ast : m.getGProtoDeclChildren()) + { + GProtocol imed = (GProtocol) ast.visitWith(t); + imeds.add(imed); + verbosePrintPass( + //"\nParsed:\n" + gpd + + "Translated Scribble intermediate: " + ast.getFullMemberName(m) + + "\n" + imed); + } + } + this.core = newCore(this.config.main, this.config.args, + //this.context.getModuleContexts(), + imeds, this.config.tf); + } + return this.core; + } + + // A Scribble extension should override newJobConfig/Context/Core as appropriate + protected Core newCore(ModuleName mainFullname, Map args, + //Map modcs, + Set imeds, STypeFactory tf) + { + return new Core(mainFullname, args, //modcs, + imeds, tf); + } + + // Returns: fullname -> Module -- CHECKME TODO: refactor local Module creation to Job? + // CHECKME: generate projection Modules for an *inline* main? + public Map, Module> getProjections(GProtoName fullname, + Role self) throws ScribException + { + AstFactory af = this.config.af; + LProjectionTranslator t = new LProjectionTranslator(this); + Map, Module> res = new HashMap<>(); + + Map, LProjection> projs = getCore() + .getProjections(fullname, self); + for (ProtoName pfullname : projs.keySet()) + { + LProjection proj = projs.get(pfullname); + + List> imports = new LinkedList<>(); + List> pdeps = proj.def + .gather(new ProtoDepsCollector()::visit).distinct() + .collect(Collectors.toList()); // Gathering only from this proto decl (no subproto visiting) // Overlaps with Core::getProjections + pdeps.remove(pfullname); + for (ProtoName imp : pdeps) + { + ModuleNameNode modnn = af.ModuleNameNode(null, + IdNode.from(af, imp.getElements())); + imports.add(af.ImportModule(null, modnn, null)); + } + + LinkedHashSet> npdeps = new LinkedHashSet<>(); + proj.def.gather(new NonProtoDepsGatherer()::visit) // Gathering only from this proto decl (no subproto visiting) + .forEachOrdered(x -> npdeps.add(x)); // set-ify while preserving order + List> nonprods = new LinkedList<>(); + for (MemberName nonpro : npdeps) + { + Kind kind = nonpro.getKind(); + ModuleName pref = nonpro.getPrefix(); + Module m = this.context + .getModule(pref.isEmpty() ? fullname.getPrefix() : pref); + // CHECKME: currently just "copying" decl from source (global) Module, how about importing the Module instead? (and re-qualifying names as needed) + if (kind.equals(DataKind.KIND)) + { + nonprods.add(m.getTypeDeclChild(((DataName) nonpro).getSimpleName())); + } + else if (kind.equals(SigKind.KIND)) + { + nonprods.add(m.getSigDeclChild(((SigName) nonpro).getSimpleName())); + } + else + { + throw new RuntimeException("Unhandled: " + kind + "\n\t" + nonpro); + } + } + + ModuleNameNode modn = af.ModuleNameNode(null, + IdNode.from(af, pfullname.getPrefix().getElements())); + ModuleDecl modd = af.ModuleDecl(null, modn); + List protos = Arrays.asList(t.translate(proj)); + Module mod = af.Module(null, modd, imports, nonprods, protos); + res.put(pfullname, mod); + } + + // CHECKME: nonprotos should refer to source global module? i.e., projection modules should import globals? maybe consistent with "projects" clause + return res; + // CHECKME: (interleaved) ordering between proto and nonproto (Module) imports -- order by original Global import order? + } + + public void runVisitorPassOnAllModules(AstVisitor v) throws ScribException + { + verbosePrintPass("Running " + v.getClass() + " on all modules..."); + runVisitorPass(v, this.context.getFullModuleNames()); + } + + private void runVisitorPass(AstVisitor v, Set fullnames) + throws ScribException + { + for (ModuleName fullname : fullnames) + { + runVisitorOnModule(fullname, v); + } + } + + private void runVisitorOnModule(ModuleName modname, AstVisitor v) + throws ScribException + { + if (this.core != null) + { + throw new RuntimeException("toJob already finalised: "); + } + verbosePrintPass("Running " + v.getClass() + " on: " + modname); + Module visited = (Module) this.context.getModule(modname).accept(v); + verbosePrintln(visited.toString()); + this.context.replaceModule(visited); + } + + public JobContext getContext() + { + return this.context; + } + + public boolean isVerbose() + { + return this.config.args.get(CoreArgs.VERBOSE); + } + + public void verbosePrintln(String s) + { + if (isVerbose()) + { + System.out.println(s); + } + } + + private void verbosePrintPass(String s) + { + verbosePrintln("\n[Job] " + s); + } + + public void warningPrintln(String s) + { + System.err.println("[Warning] " + s); + } +} diff --git a/scribble-ast/src/main/java/org/scribble/job/JobConfig.java b/scribble-ast/src/main/java/org/scribble/job/JobConfig.java new file mode 100644 index 000000000..373864478 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/job/JobConfig.java @@ -0,0 +1,49 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.job; + +import java.util.Collections; +import java.util.Map; + +import org.scribble.ast.AstFactory; +import org.scribble.core.job.CoreArgs; +import org.scribble.core.type.name.ModuleName; +import org.scribble.core.type.session.STypeFactory; +import org.scribble.del.DelFactory; +import org.scribble.visit.VisitorFactory; + +// The "static" (constant) info for Lang -- cf. LangContext "dynamic" state +public class JobConfig +{ + public final ModuleName main; // Full name + + public final Map args; // CHECKME: Set ? + + public final AstFactory af; + public final DelFactory df; + public final VisitorFactory vf; + public final STypeFactory tf; + + // N.B. MainContext is in a different non-visible (by Maven) package + public JobConfig(ModuleName mainFullname, Map args, + AstFactory af, DelFactory df, VisitorFactory vf, STypeFactory tf) + { + this.main = mainFullname; + this.args = Collections.unmodifiableMap(args); + this.af = af; + this.df = df; + this.vf = vf; + this.tf = tf; + } +} diff --git a/scribble-ast/src/main/java/org/scribble/job/JobContext.java b/scribble-ast/src/main/java/org/scribble/job/JobContext.java new file mode 100644 index 000000000..6f3553d45 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/job/JobContext.java @@ -0,0 +1,159 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.job; + +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import org.scribble.ast.Module; +import org.scribble.ast.global.GProtoDecl; +import org.scribble.core.lang.context.ModuleContext; +import org.scribble.core.type.name.GProtoName; +import org.scribble.core.type.name.ModuleName; +import org.scribble.util.ScribException; + +// Global "static" context information for a Job -- single instance per Job, should not be shared between Jobs +// Mutable: projections, graphs, etc are added mutably later -- replaceModule also mutable setter -- "users" get this from the Job and expect to setter mutate "in place" +public class JobContext +{ + public final Job job; + + //public final ModuleName main; // The "main" root module from MainContext + + // Modules that were originally parsed (obtained from MainContext), but may be modified during the Job + // ModuleName keys are full module names -- currently the modules read from file, distinguished from the generated projection modules + // CHECKME: separate original parsed from "working set"? -- store parsed constants in config? + private final Map parsed;// = new HashMap<>(); + + // Used by, e.g., SimpleAstVisitor (cf. getModuleContext) + // Keys are full names + // Currently assuming ModuleContexts are constant, and considering parsed Modules only (i.e., not generated) -- CHECKME + private final Map modcs; + // CHECKME: constant? depends on adding projections? + + protected JobContext(Job job, Map parsed) + throws ScribException + { + this.job = job; + this.parsed = new HashMap(parsed); + this.modcs = Collections.unmodifiableMap(buildModuleContexts(parsed)); + } + + // Currently assuming ModuleContexts are constant, and considering parsed Modules only (i.e., not generated) -- CHECKME + protected Map buildModuleContexts( + Map parsed) throws ScribException + { + // CHECKME: how does this relate to the ModuleContextBuilder pass? + // Job.modcs seems unused? Lang.modcs is used though, by old AST visitors -- basically old ModuleContextVisitor is redundant? + // Job.modcs could be used, but disamb already done by Lang + // Lang/Job modcs should be moved to config/context though + ModuleContextBuilder b = new ModuleContextBuilder(); // TODO: factor out newModuleContextBuilder + Map modcs = new HashMap<>(); + for (ModuleName fullname : parsed.keySet()) + { + modcs.put(fullname, b.build(parsed, parsed.get(fullname))); + // Throws ScribException + } + return modcs; + } + + public Module getMainModule() + { + return getModule(this.job.config.main); + } + + // HACK -- CHECKME: separate original parsed from "working set"? + public Map getParsed() + { + return Collections.unmodifiableMap(this.parsed); + } + + public GProtoDecl getParsed(GProtoName fullname) + { + return this.parsed.get(fullname.getPrefix()) + .getGProtoDeclChildren().stream().filter(x -> x.getHeaderChild() + .getDeclName().equals(fullname.getSimpleName())) + .findAny().get(); + } + + public Map getModuleContexts() + { + return this.modcs; + } + + public ModuleContext getModuleContext(ModuleName fullname) + { + return this.modcs.get(fullname); + } + + + // The following are used for Visitor pass running + + // Safer to get module names and require user to re-fetch the module by the getter each time (after replacing), to make sure the latest is used + public Set getFullModuleNames() + { + Set modnames = new HashSet<>(); + modnames.addAll(getParsedFullModuleNames()); + //modnames.addAll(getProjectedFullModuleNames()); + return modnames; + } + + public Set getParsedFullModuleNames() + { + return Collections.unmodifiableSet(this.parsed.keySet()); + } + + private boolean isParsedModule(ModuleName fullname) + { + return this.parsed.containsKey(fullname); + } + + public Module getModule(ModuleName fullname) + { + if (isParsedModule(fullname)) + { + return this.parsed.get(fullname); + } + /*else if (isProjectedModule(fullname)) + { + return this.projected.get(this.projected.keySet().stream() + .filter(lpn -> lpn.getPrefix().equals(fullname)) + .collect(Collectors.toList()).get(0)); + }*/ + else + { + throw new RuntimeException("Unknown module: " + fullname); + } + } + + protected void replaceModule(Module module) + { + ModuleName fullname = module.getFullModuleName(); + if (isParsedModule(fullname)) + { + this.parsed.put(fullname, module); + } + /*else if (isProjectedModule(fullname)) + { + addProjection(module); + }*/ + else + { + throw new RuntimeException("Unknown module: " + fullname); + } + } +} diff --git a/scribble-ast/src/main/java/org/scribble/job/ModuleContextBuilder.java b/scribble-ast/src/main/java/org/scribble/job/ModuleContextBuilder.java new file mode 100644 index 000000000..ec76818f8 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/job/ModuleContextBuilder.java @@ -0,0 +1,207 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.job; + +import java.util.Map; + +import org.scribble.ast.DataDecl; +import org.scribble.ast.ImportDecl; +import org.scribble.ast.ImportModule; +import org.scribble.ast.SigDecl; +import org.scribble.ast.Module; +import org.scribble.ast.NonProtoDecl; +import org.scribble.ast.global.GProtoDecl; +import org.scribble.core.lang.context.ModuleContext; +import org.scribble.core.lang.context.ScribNames; +import org.scribble.core.type.name.DataName; +import org.scribble.core.type.name.GProtoName; +import org.scribble.core.type.name.SigName; +import org.scribble.core.type.name.ModuleName; +import org.scribble.util.ScribException; +// TODO: rename and refactor -- also factor out newModuleContextBuilder in Lang +public class ModuleContextBuilder +{ + private Module root; // full name // The root Module for this ModuleContext (cf. the "main" root module from CLI) + + // All transitive name dependencies of this module: all names fully qualified + // The ScribNames maps are basically just used as sets (identity map) + // Cf. ProtocolDeclContext protocol dependencies from protocoldecl as root + private ScribNames deps;// = new ScribNames(); + + // The modules and member names that are visible from this Module -- mapped to "cannonical" (fully qualified) names + // visible names -> fully qualified names + // Directly visible names from this module + private ScribNames visible;// = new ScribNames(); + + // Made by ModuleContextBuilder + // ModuleContext is the root context + public ModuleContextBuilder() //JobContext jcontext, + { + + } + + public ModuleContext build( + Map parsed, // From MainContext (N.B., in a different non-visible package) + Module root) throws ScribException + { + this.root = root; + this.deps = new ScribNames(); + this.visible = new ScribNames(); + + ModuleName fullname = this.root.getFullModuleName(); + ModuleName simpname = this.root.getModuleDeclChild().getDeclName(); + + // All transitive dependencies (for inlined and subprotocol visiting) + addModule(this.deps, this.root, fullname); + addImportDependencies(parsed, this.root); + + // Names directly visible from this module + addModule(this.visible, this.root, fullname); + if (!fullname.equals(simpname)) + { + addModule(this.visible, this.root, simpname); + // Adds simple name of root as visible, and members qualified by simple name + } + addVisible(parsed, root); + // Adds imports and members by their "direct" names (unqualified, except for no-alias imports) + + return new ModuleContext(root.getFullModuleName(), deps, visible); + } + + // Register mod under name modname, modname could be the full module name or an import alias + // Adds member names qualified by mod + private static void addModule(ScribNames names, Module mod, + ModuleName modname) throws ScribException + { + names.modules.put(modname, mod.getFullModuleName()); + for (NonProtoDecl npd : mod.getNonProtoDeclChildren()) + { + if (npd.isDataDecl()) + { + DataDecl dtd = (DataDecl) npd; + DataName qualif = new DataName(modname, dtd.getDeclName()); + names.data.put(qualif, dtd.getFullMemberName(mod)); + } + else //if (npd.isMessageSigNameDecl()) + { + SigDecl msnd = (SigDecl) npd; + SigName qualif = new SigName(modname, msnd.getDeclName()); + names.sigs.put(qualif, msnd.getFullMemberName(mod)); + } + } + for (GProtoDecl gpd : mod.getGProtoDeclChildren()) + { + GProtoName qualif = new GProtoName(modname, + gpd.getHeaderChild().getDeclName()); + names.globals.put(qualif, gpd.getFullMemberName(mod)); + } + } + + // Could move to ImportModule but would need a defensive copy setter, or cache info in builder and create on leave + private void addImportDependencies(Map parsed, Module mod) + throws ScribException + { + for (ImportDecl id : mod.getImportDeclChildren()) + { + if (id.isImportModule()) + { + ImportModule im = (ImportModule) id; + ModuleName fullmodname = im.getModuleNameNodeChild().toName(); + if (!this.deps.modules.containsKey(fullmodname)) + { + Module imported = parsed.get(fullmodname); // TODO: Can get from MainContext instead of JobContext? + addModule(this.deps, imported, fullmodname); // Unlike for visible, only doing full names here + addImportDependencies(parsed, imported); + + // FIXME: also do for npds -- factor out with below + for (GProtoDecl gpd : imported.getGProtoDeclChildren()) + { + GProtoName fullname = gpd.getFullMemberName(root); + this.visible.globals.put(fullname, fullname); + } + } + } + else + { + throw new RuntimeException("TODO: " + id); + } + } + } + + // Adds "local" imports by alias or full name + // Adds "local" members by simple names + private void addVisible(Map parsed, Module root) + throws ScribException + { + // Unlike for deps, visible is not done transitively + for (ImportDecl id : root.getImportDeclChildren()) + { + if (id.isImportModule()) + { + ImportModule im = (ImportModule) id; + ModuleName fullname = im.getModuleNameNodeChild().toName(); + ModuleName visname = (im.hasAlias()) ? im.getAlias() : fullname; + // getVisibleName doesn't use fullname + if (this.visible.modules.containsKey(visname)) + { + throw new ScribException(id.getSource(), + "Duplicate visible module name: " + visname); + } + Module imported = parsed.get(fullname); // TODO: Can get from MainContext instead of JobContext? + addModule(this.visible, imported, visname); + + } + else + { + throw new RuntimeException("TODO: " + id); + } + } + + for (NonProtoDecl npd : root.getNonProtoDeclChildren()) + { + if (npd.isDataDecl()) + { + DataDecl dtd = (DataDecl) npd; + DataName visname = new DataName(dtd.getDeclName().toString()); + DataName fullname = dtd.getFullMemberName(root); + this.visible.data.put(fullname, fullname); + this.visible.data.put(visname, fullname); + } + else // if (npd.isMessageSigNameDecl()) + { + SigDecl msnd = (SigDecl) npd; + SigName fullname = msnd.getFullMemberName(root); + SigName visname = new SigName( + msnd.getDeclName().toString()); + this.visible.sigs.put(fullname, fullname); + this.visible.sigs.put(visname, fullname); + } + } + + for (GProtoDecl gpd : root.getGProtoDeclChildren()) + { + GProtoName visname = new GProtoName( + gpd.getHeaderChild().getDeclName().toString()); + GProtoName fullname = gpd.getFullMemberName(root); + this.visible.globals.put(fullname, fullname); + this.visible.globals.put(visname, fullname); + } + } + + /*@Override + public String toString() + { + return "Maker[deps=" + this.deps + ", visible=" + this.visible + "]"; + }*/ +} diff --git a/scribble-ast/src/main/java/org/scribble/util/LProjectionTranslator.java b/scribble-ast/src/main/java/org/scribble/util/LProjectionTranslator.java new file mode 100644 index 000000000..99c3e2a21 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/util/LProjectionTranslator.java @@ -0,0 +1,347 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.util; + +import java.util.Arrays; +import java.util.LinkedList; +import java.util.List; +import java.util.stream.Collectors; + +import org.scribble.ast.AstFactory; +import org.scribble.ast.MsgNode; +import org.scribble.ast.NonRoleArg; +import org.scribble.ast.NonRoleArgList; +import org.scribble.ast.NonRoleArgNode; +import org.scribble.ast.NonRoleParamDecl; +import org.scribble.ast.NonRoleParamDeclList; +import org.scribble.ast.PayElem; +import org.scribble.ast.PayElemList; +import org.scribble.ast.ProtoModNode; +import org.scribble.ast.ProtoModList; +import org.scribble.ast.RoleArgList; +import org.scribble.ast.RoleDeclList; +import org.scribble.ast.local.LProjectionDecl; +import org.scribble.ast.local.LProtoBlock; +import org.scribble.ast.local.LProtoDef; +import org.scribble.ast.local.LProtoHeader; +import org.scribble.ast.local.LSessionNode; +import org.scribble.ast.name.qualified.DataNameNode; +import org.scribble.ast.name.qualified.GProtoNameNode; +import org.scribble.ast.name.qualified.LProtoNameNode; +import org.scribble.ast.name.simple.DataParamNode; +import org.scribble.ast.name.simple.IdNode; +import org.scribble.ast.name.simple.OpNode; +import org.scribble.ast.name.simple.RecVarNode; +import org.scribble.ast.name.simple.RoleNode; +import org.scribble.ast.name.simple.SigParamNode; +import org.scribble.core.lang.ProtoMod; +import org.scribble.core.lang.local.LProjection; +import org.scribble.core.type.kind.DataKind; +import org.scribble.core.type.kind.NonRoleArgKind; +import org.scribble.core.type.kind.NonRoleParamKind; +import org.scribble.core.type.kind.SigKind; +import org.scribble.core.type.name.DataName; +import org.scribble.core.type.name.MemberName; +import org.scribble.core.type.name.PayElemType; +import org.scribble.core.type.name.Role; +import org.scribble.core.type.name.SigName; +import org.scribble.core.type.session.Arg; +import org.scribble.core.type.session.Msg; +import org.scribble.core.type.session.SigLit; +import org.scribble.core.type.session.local.LAcc; +import org.scribble.core.type.session.local.LChoice; +import org.scribble.core.type.session.local.LContinue; +import org.scribble.core.type.session.local.LDisconnect; +import org.scribble.core.type.session.local.LDo; +import org.scribble.core.type.session.local.LRecursion; +import org.scribble.core.type.session.local.LRecv; +import org.scribble.core.type.session.local.LReq; +import org.scribble.core.type.session.local.LSend; +import org.scribble.core.type.session.local.LSeq; +import org.scribble.core.type.session.local.LType; +import org.scribble.job.Job; + +// Cannot refactor into LType hierarchy, due to Maven module dependencies (scribble-core cannot see scribble-ast) +// Actually, this is a quite general LScribNode translator +public class LProjectionTranslator +{ + public final Job job; + private final AstFactory af; + + private final RoleNode SELF_NODE; // translate LChoice/LDo currently make their own self RoleNodes (convenience) + + public LProjectionTranslator(Job job) + { + this.job = job; + this.af = job.config.af; + SELF_NODE = this.af.RoleNode(null, Role.SELF.toString()); + } + + public LProjectionDecl translate(LProjection proj) + { + RoleDeclList rs = this.af.RoleDeclList(null, proj.roles.stream().map(x -> + { + RoleNode r = this.af.RoleNode(null, x.toString()); + return x.equals(proj.self) + ? this.af.LSelfDecl(null, r) + : this.af.RoleDecl(null, r); + }).collect(Collectors.toList())); + List> pds = new LinkedList<>(); + for (MemberName p : proj.params) + { + if (p instanceof SigName) + { + SigParamNode n = this.af.SigParamNode(null, p.toString()); + pds.add(this.af.SigParamDecl(null, n)); + } + else if (p instanceof DataName) + { + DataParamNode n = this.af.DataParamNode(null, p.toString()); + pds.add(this.af.DataParamDecl(null, n)); + } + else + { + throw new RuntimeException( + "[TODO] Unsupported kind: " + p.getClass() + "\n\t" + p); + } + } + NonRoleParamDeclList ps = this.af.NonRoleParamDeclList(null, pds); + + ProtoModList mods = this.af.ProtoModList(null, proj.mods.stream() + .map(x -> translate(x)).collect(Collectors.toList())); + GProtoNameNode global = this.af.GProtoNameNode(null, + IdNode.from(this.af, proj.global.getElements())); + RoleNode self1 = this.af.RoleNode(null, proj.self.toString()); // FIXME: special "self" node? + LProtoNameNode projFullname = this.af.LProtoNameNode(null, + IdNode.from(this.af, proj.fullname.getElements())); + LProtoHeader header = this.af.LProtoHeader(null, projFullname, rs, ps); + LProtoDef def = this.af.LProtoDef(null, translate(proj.def)); + return this.af.LProjectionDecl(null, mods, header, def, global, self1); + } + + // Cf. IdNode.from + protected ProtoModNode translate(ProtoMod mod) + { + switch (mod) + { + case AUX: return af.AuxMod(null); + case EXPLICIT: return af.ExplicitMod(null); + default: throw new RuntimeException("Unknown modifier: " + mod); + } + } + + protected MsgNode translate(Msg msg) + { + if (msg.isSigLit()) + { + SigLit cast = (SigLit) msg; + OpNode op = this.af.OpNode(null, cast.op.toString()); + PayElemList pay = this.af.PayElemList(null, cast.payload.elems.stream() + .map(x -> translate(x)).collect(Collectors.toList())); + return this.af.SigLitNode(null, op, pay); + } + else + { + SigName cast = (SigName) msg; + List elems = Arrays.asList(cast.getElements()).stream() + .map(x -> this.af.IdNode(null, x)).collect(Collectors.toList()); + return this.af.SigNameNode(null, elems); + } + } + + protected PayElem translate(PayElemType e) + { + if (e instanceof DataName) + { + DataNameNode res = this.af.DataNameNode(null, + IdNode.from(af, ((DataName) e).getElements())); + return this.af.UnaryPayElem(null, res); + } + else + { + throw new RuntimeException( + "[TODO] Unsupported PayElemType: " + e.getClass() + "\n\t" + e); + } + } + + // N.B. in the following, "self" are just regular Role names, and translated to regular RoleNode (cf. LSelfDecl) + + protected org.scribble.ast.local.LSend translate(LSend t) + { + RoleNode dst = this.af.RoleNode(null, t.dst.toString()); + MsgNode msg = translate(t.msg); + return this.af.LSend(null, SELF_NODE, msg, dst); // Ignoring t.src, but it's "self" + } + + protected org.scribble.ast.local.LRecv translate(LRecv t) + { + RoleNode src = this.af.RoleNode(null, t.src.toString()); + MsgNode msg = translate(t.msg); + return this.af.LRecv(null, src, msg, SELF_NODE); // Ignoring t.src, but it's "self" + } + + protected org.scribble.ast.local.LAcc translate(LAcc t) + { + RoleNode src = this.af.RoleNode(null, t.src.toString()); + MsgNode msg = translate(t.msg); + return this.af.LAcc(null, src, msg, SELF_NODE); // Ignoring t.src, but it's "self" + } + + protected org.scribble.ast.local.LReq translate(LReq t) + { + RoleNode dst = this.af.RoleNode(null, t.dst.toString()); + MsgNode msg = translate(t.msg); + return this.af.LReq(null, SELF_NODE, msg, dst); // Ignoring t.src, but it's "self" + } + + protected org.scribble.ast.local.LDisconnect translate(LDisconnect t) + { + RoleNode peer = this.af.RoleNode(null, t.getPeer().toString()); + return this.af.LDisconnect(null, SELF_NODE, peer); // Ignoring t.src, but it's "self" + } + + protected org.scribble.ast.local.LContinue translate(LContinue t) + { + RecVarNode rv = this.af.RecVarNode(null, t.recvar.toString()); + return this.af.LContinue(null, rv); + } + + protected org.scribble.ast.local.LDo translate(LDo t) + { + List args = new LinkedList<>(); + for (Arg p : t.args) + { + NonRoleArgKind k = p.getKind(); + NonRoleArgNode a; + if (k.equals(SigKind.KIND)) + { + if (p instanceof SigLit) + { + SigLit cast = (SigLit) p; + OpNode op = this.af.OpNode(null, cast.op.toString()); + PayElemList pay = this.af.PayElemList(null, cast.payload.elems + .stream().map(x -> translate(x)).collect(Collectors.toList())); + a = this.af.SigLitNode(null, op, pay); // FIXME: could need to be SigParamNode + } + else if (p instanceof SigName) + { + a = this.af.SigNameNode(null, + IdNode.from(this.af, ((SigName) p).getElements())); + // FIXME: could need to be SigParamNode + } + else + { + throw new RuntimeException( + "Shouldn't get in here: " + p.getClass() + "\n\t" + p); + } + } + else if (k.equals(DataKind.KIND)) + { + if (p instanceof DataName) + { + a = this.af.DataNameNode(null, + IdNode.from(this.af, ((SigName) p).getElements())); + // FIXME: could need to be DataParamNode + } + else + { + throw new RuntimeException( + "[TODO] : " + p.getClass() + "\n\t" + p); + } + } + else + { + throw new RuntimeException( + "[TODO] Unsupported kind: " + p.getClass() + "\n\t" + p); + } + args.add(this.af.NonRoleArg(null, a)); + } + NonRoleArgList as = this.af.NonRoleArgList(null, args); + + LProtoNameNode proto = this.af.LProtoNameNode(null, + IdNode.from(this.af, t.proto.getElements())); + RoleArgList rs = this.af.RoleArgList(null, // Cf. translate(LProjectionDecl) + t.roles.stream().map( + x -> this.af.RoleArg(null, this.af.RoleNode(null, x.toString()))) // Includes "self" + .collect(Collectors.toList())); + return this.af.LDo(null, proto, as, rs); + } + + protected org.scribble.ast.local.LChoice translate(LChoice t) + { + RoleNode subj = this.af.RoleNode(null, t.subj.toString()); // Includes "self" + List blocks = t.blocks.stream().map(x -> translate(x)) + .collect(Collectors.toList()); + return this.af.LChoice(null, subj, blocks); + } + + protected org.scribble.ast.local.LRecursion translate(LRecursion t) + { + RecVarNode rv = this.af.RecVarNode(null, t.recvar.toString()); + return this.af.LRecursion(null, rv, translate(t.body)); + } + + protected org.scribble.ast.local.LProtoBlock translate(LSeq t) + { + List elems = t.getElements().stream().map(x -> translate(x)) + .collect(Collectors.toList()); + return this.af.LProtoBlock(null, this.af.LInteractionSeq(null, elems)); + } + + // Cannot refactor into LType hierarchy, due to Maven module dependencies (scribble-core cannot see scribble-ast) + // Only LSeq not done, return is not an LSessionNode + protected LSessionNode translate(LType t) + { + if (t instanceof LAcc) + { + return translate((LAcc) t); + } + else if (t instanceof LChoice) + { + return translate((LChoice) t); + } + else if (t instanceof LContinue) + { + return translate((LContinue) t); + } + else if (t instanceof LDisconnect) + { + return translate((LDisconnect) t); + } + else if (t instanceof LDo) + { + return translate((LDo) t); + } + else if (t instanceof LRecursion) + { + return translate((LRecursion) t); + } + else if (t instanceof LRecv) + { + return translate((LRecv) t); + } + else if (t instanceof LReq) + { + return translate((LReq) t); + } + else if (t instanceof LSend) + { + return translate((LSend) t); + } + else + { + throw new RuntimeException("[TODO] Unhandled LType: " + t.getClass() + "\n" + t); + } + } +} diff --git a/scribble-ast/src/main/java/org/scribble/util/ScribNodeUtil.java b/scribble-ast/src/main/java/org/scribble/util/ScribNodeUtil.java new file mode 100644 index 000000000..4cca8d937 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/util/ScribNodeUtil.java @@ -0,0 +1,58 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.util; + +import java.util.List; +import java.util.stream.Collectors; + +import org.scribble.ast.AstFactory; +import org.scribble.ast.ScribNode; + +public class ScribNodeUtil +{ + // Strict class equality, cf. ScribNodeBase#visitChildWithClassCheck + // C is expected to be of a ground class type + // Maybe pointless (in terms of formal guarantees) to use equality instead of assignable + public static C checkNodeClassEquality(C c, ScribNode n) + { + if (!c.getClass().equals(n.getClass())) + { + throw new RuntimeException( + "Node class not equal: " + c.getClass() + ", " + n.getClass()); + } + @SuppressWarnings("unchecked") + C tmp = (C) n; + return tmp; + } + + // C is expected to be of a ground class type + public static C castNodeByClass(C cast, ScribNode n) + { + if (!cast.getClass().isAssignableFrom(n.getClass())) + { + throw new RuntimeException( + "Node class cast error: " + cast.getClass() + ", " + n.getClass()); + } + @SuppressWarnings("unchecked") + C tmp = (C) n; + return tmp; + } + + public static List cloneList(AstFactory af, + List ns) + { + return ns.stream().map(n -> checkNodeClassEquality(n, // n.clone(af))) + n.clone())).collect(Collectors.toList()); + } +} diff --git a/scribble-ast/src/main/java/org/scribble/visit/AstVisitor.java b/scribble-ast/src/main/java/org/scribble/visit/AstVisitor.java new file mode 100644 index 000000000..74b8d9a0f --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/visit/AstVisitor.java @@ -0,0 +1,50 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.visit; + +import org.scribble.ast.ScribNode; +import org.scribble.job.Job; +import org.scribble.util.ScribException; + +// Pattern: node accepts visitor and calls visitor back (standard visitor pattern -- adding a new operation doesn't affect the Ast classes), but then visitor delegates back to node delegate (so routines for handling each node type not centralised in visitor, but decentralised to delegates) +// More general than SimpleAstVisitor, retrieves ModuleContext on entry and offers enter/leave around visitChildren +public abstract class AstVisitor +{ + public final Job job; // Immutable except for JobContext internals + + protected AstVisitor(Job job) + { + this.job = job; + } + + // Used by ScribNodeBase::accept + public ScribNode visit(ScribNode child) throws ScribException + { + enter(child); + ScribNode visited = child.visitChildren(this); // visited means "children visited so far"; we're about to visit "this" now via "leave" + return leave(child, visited); + } + + protected void enter(ScribNode child) + throws ScribException + { + + } + + protected ScribNode leave(ScribNode child, ScribNode visited) + throws ScribException + { + return visited; + } +} diff --git a/scribble-ast/src/main/java/org/scribble/visit/DelDecorator.java b/scribble-ast/src/main/java/org/scribble/visit/DelDecorator.java new file mode 100644 index 000000000..57de4723c --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/visit/DelDecorator.java @@ -0,0 +1,76 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.visit; + +import org.scribble.ast.ScribNode; +import org.scribble.ast.ScribNodeBase; +import org.scribble.del.DelFactory; +import org.scribble.job.Job; +import org.scribble.util.ScribException; + +// A visitor that caches the ModuleContext from the *entered* Module, for later access +// N.B. may be a different Module than the "root" Module of the job +// Looking up the "entered" Module context is otherwise inconvenient +public class DelDecorator extends AstVisitor +{ + protected final DelFactory df; + + protected DelDecorator(Job job) + { + super(job); + this.df = job.config.df; + } + + // AstVisitor enter/leave typically delegates to dels -- DelDecorator is a "proto-visitor", no del to delegate to (yet) + @Override + protected ScribNode leave(ScribNode child, ScribNode visited) + throws ScribException + { + decorate(visited); // Mutating setter + return visited; + } + + protected void decorate(ScribNode n) + { + if (n.del() != null) // Currently, only the simple name nodes "constructed directly" by parser, e.g., t=ID -> ID<...Node>[$t] + { + return; + } + ((ScribNodeBase) n).decorateDel(this.df); + + /*try + { + String cname = n.getClass().getName(); + String mname = cname.substring(cname.lastIndexOf('.')+1, cname.length()); + Class param = Class.forName(cname); + Method m = DelFactory.class.getMethod(mname, param); + m.invoke(this.df, n); + } + catch (NoSuchMethodException | SecurityException | ClassNotFoundException + | IllegalAccessException | IllegalArgumentException + | InvocationTargetException e) + { + throw new RuntimeException(e); + }*/ + } + + /*protected void decorateChildren(ScribNode n) + { + n.getChildren().stream().forEach(x -> decorate(x)); + }*/ +} + + + + diff --git a/scribble-ast/src/main/java/org/scribble/visit/GTypeTranslator.java b/scribble-ast/src/main/java/org/scribble/visit/GTypeTranslator.java new file mode 100644 index 000000000..d2f50e7b8 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/visit/GTypeTranslator.java @@ -0,0 +1,38 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.visit; + +import org.scribble.ast.ScribNode; +import org.scribble.core.lang.global.GNode; +import org.scribble.core.type.name.ModuleName; +import org.scribble.core.type.session.STypeFactory; +import org.scribble.del.global.GDel; +import org.scribble.job.Job; + +public class GTypeTranslator extends SimpleAstVisitorNoThrows +{ + public final STypeFactory tf; + + public GTypeTranslator(Job job, ModuleName rootFullname, STypeFactory tf) + { + super(job, rootFullname); + this.tf = tf; + } + + @Override + public GNode visit(ScribNode n) + { + return ((GDel) n.del()).translate(n, this); + } +} diff --git a/scribble-ast/src/main/java/org/scribble/visit/ModuleContextVisitor.java b/scribble-ast/src/main/java/org/scribble/visit/ModuleContextVisitor.java new file mode 100644 index 000000000..29e04b315 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/visit/ModuleContextVisitor.java @@ -0,0 +1,57 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.visit; + +import org.scribble.ast.Module; +import org.scribble.ast.ScribNode; +import org.scribble.core.lang.context.ModuleContext; +import org.scribble.core.type.name.ModuleName; +import org.scribble.job.Job; +import org.scribble.util.ScribException; + +// A visitor that caches the ModuleContext from the *entered* Module, for later access +// N.B. may be a different Module than the "root" Module of the job +// Looking up the "entered" Module context is otherwise inconvenient +public abstract class ModuleContextVisitor extends AstVisitor +{ + private ModuleContext mcon; // The "current" module context, gathered on entry -- different than the front-end "main" module + + public ModuleContextVisitor(Job job) + { + super(job); + } + + @Override + protected void enter(ScribNode child) + throws ScribException + { + super.enter(child); + if (child instanceof Module) // Factor out? (e.g., Module?) + { + ModuleName fullname = ((Module) child).getFullModuleName(); + setModuleContext(this.job.getContext().getModuleContext(fullname)); + } + } + + public ModuleContext getModuleContext() + { + return this.mcon; + } + + // Factor out -- e.g. some Visitors want to root on ProtocolDecl, not Module + protected void setModuleContext(ModuleContext mcontext) + { + this.mcon = mcontext; + } +} diff --git a/scribble-ast/src/main/java/org/scribble/visit/NameDisambiguator.java b/scribble-ast/src/main/java/org/scribble/visit/NameDisambiguator.java new file mode 100644 index 000000000..fc700401f --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/visit/NameDisambiguator.java @@ -0,0 +1,206 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.visit; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import org.scribble.ast.ScribNode; +import org.scribble.ast.global.GDelegPayElem; +import org.scribble.core.type.kind.NonRoleArgKind; +import org.scribble.core.type.kind.NonRoleParamKind; +import org.scribble.core.type.name.Name; +import org.scribble.core.type.name.RecVar; +import org.scribble.core.type.name.Role; +import org.scribble.del.global.GDelegationElemDel; +import org.scribble.job.Job; +import org.scribble.util.ScribException; + +// Disambiguates ambiguous PayloadTypeOrParameter names and inserts implicit Scope names +// Also canonicalises recvars -- CHECKME ? +public class NameDisambiguator extends ModuleContextVisitor +{ + // For implicit scope generation: reset per ProtocolDecl + //private int counter = 1; + + private Set roles = new HashSet<>(); + private Map params = new HashMap<>(); + //private Set recvars = new HashSet<>(); + //private Map> recvars = new HashMap<>(); + private Map recvars = new HashMap<>(); // Nesting count integer now unused (recvar renaming refactored to inlining -- don't want to mangle source AST) + + //private ProtocolDecl root; // FIXME: factor out // Now unused (recvar renaming refactored to inlining -- don't want to mangle source AST) + + protected NameDisambiguator(Job job) + { + super(job); + } + + /*public ScopeNode getFreshScope() + { + return new ScopeNode(null, Scope.IMPLICIT_SCOPE_PREFIX + "." + counter++); + }*/ + + // Most subclasses will override visitForSubprotocols (e.g. ReachabilityChecker, FsmConstructor), but sometimes still want to change whole visit pattern (e.g. Projector) + @Override + public ScribNode visit(ScribNode child) throws ScribException + { + /*if (child instanceof ProtocolDecl) // FIXME: factor out + { + this.root = (ProtocolDecl) child; + }*/ + enter(child); + ScribNode visited = visitForDisamb(child); + return leave(child, visited); + } + + // CHECKME: why "visitFor" pattern? + protected ScribNode visitForDisamb(ScribNode child) throws ScribException + { + if (child instanceof GDelegPayElem) + { + return ((GDelegationElemDel) child.del()).visitForNameDisambiguation(this, + (GDelegPayElem) child); + } + else + { + return child.visitChildren(this); + } + } + + @Override + //public NameDisambiguator enter(ModelNode parent, ModelNode child) throws ScribbleException + public void enter(ScribNode child) throws ScribException + { + super.enter(child); + child.del().enterDisambiguation(child, this); + } + + @Override + public ScribNode leave(ScribNode child, ScribNode visited) + throws ScribException + { + visited = visited.del().leaveDisambiguation(child, this, visited); + return super.leave(child, visited); + } + + public void clear() + { + //this.counter = 1; + this.roles.clear(); + this.params.clear(); + this.recvars.clear(); // Should be unnecessary + + //this.pds.clear(); // No: called by ProtocolDecl leaveDisambiguation (i.e. before the above leave override) -- should be unnecessary anyway + } + + public void addRole(Role role) + { + this.roles.add(role); + } + + public boolean isBoundRole(Role role) + { + return this.roles.contains(role); + } + + public void addParam(Name param, + NonRoleParamKind kind) + { + this.params.put(param.toString(), kind); + } + + // name is a simple name (compound names are not ambiguous) + public boolean isBoundParam(Name name) // ArgKind allows AmbigNames + { + return this.params.containsKey(name.toString()); + } + + public NonRoleParamKind getParamKind(Name name) // ArgKind allows AmbigNames + { + return this.params.get(name.toString()); + } + + //public void addRecVar(RecVar rv) + public void pushRecVar(RecVar rv) + { + //this.recvars.add(rv); + /*Deque deque = this.recvars.get(rv); + if (deque.isEmpty()) + { + deque = new LinkedList(); + this.recvars.put(rv, deque); + } + deque.push(..canonicalised name..);*/ + if (!this.recvars.containsKey(rv)) + { + this.recvars.put(rv, 0); + } + else + { + this.recvars.put(rv, this.recvars.get(rv) + 1); + } + } + + public boolean isBoundRecVar(RecVar rv) + { + //return this.recvars.contains(rv); + return this.recvars.containsKey(rv); + } + + //public void removeRecVar(RecVar rv) + public void popRecVar(RecVar rv) + { + //this.recvars.remove(rv); + /*Deque deque = this.recvars.get(rv); + deque.pop(); + if (deque.isEmpty()) + { + this.recvars.remove(rv); + }*/ + Integer i = this.recvars.get(rv); + if (i == 0) + { + this.recvars.remove(rv); // Cf. isBoundRecVar, uses containsKey + } + else + { + this.recvars.put(rv, i - 1); + } + } +} + + + + + + + + + + + + /*public String getCanonicalRecVarName(RecVar rv) + { + return getCanonicalRecVarName(this.getModuleContext().root, this.root.header.getDeclName(), rv.toString() + "_" + this.recvars.get(rv)); + } + + // Cf. ProtocolDefInliner.newRecVarId + public static String getCanonicalRecVarName(ModuleName fullmodname, ProtocolName simpprotoname, String rv) + { + //return rv.toString(); + return ("__" + fullmodname + "_" + simpprotoname + "_" + rv).replace('.', '_'); + }*/ diff --git a/scribble-ast/src/main/java/org/scribble/visit/SimpleAstVisitor.java b/scribble-ast/src/main/java/org/scribble/visit/SimpleAstVisitor.java new file mode 100644 index 000000000..e2602b8ba --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/visit/SimpleAstVisitor.java @@ -0,0 +1,45 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.visit; + +import org.scribble.ast.ScribNode; +import org.scribble.core.lang.context.ModuleContext; +import org.scribble.core.type.name.ModuleName; +import org.scribble.job.Job; +import org.scribble.util.ScribException; + +// A SimpleVisitor visits a Module (or some part of one) for a given Job +// Apart from delegating to del-specific visiting methods, SimpleVisitors are mainly for holding data and collecting common operations +// A SimpleVisitor must be given the root ModuleContext, cf. ModuleContextVisitor that retrieves the "current" ModuleContext on entry +// TODO CHECKME: refactor AstVisitor as a SimpleVisitor? i.e., T=ScribNode ? +public abstract class SimpleAstVisitor +{ + public final Job job; + public final ModuleName root; // Root module, full name -- used to get ModuleContext + + public SimpleAstVisitor(Job job, ModuleName rootFullname) + { + this.job = job; + this.root = rootFullname; + } + + // Override to delegate to del-specific method, e.g., n.del().visit(n, this) + // N.B. ScribNode has getParent + public abstract T visit(ScribNode n) throws ScribException; + + public ModuleContext getModuleContext() + { + return this.job.getContext().getModuleContext(this.root); + } +} diff --git a/scribble-ast/src/main/java/org/scribble/visit/SimpleAstVisitorNoThrows.java b/scribble-ast/src/main/java/org/scribble/visit/SimpleAstVisitorNoThrows.java new file mode 100644 index 000000000..ed03cb814 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/visit/SimpleAstVisitorNoThrows.java @@ -0,0 +1,29 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.visit; + +import org.scribble.ast.ScribNode; +import org.scribble.core.type.name.ModuleName; +import org.scribble.job.Job; + +public abstract class SimpleAstVisitorNoThrows extends SimpleAstVisitor +{ + public SimpleAstVisitorNoThrows(Job job, ModuleName rootFullname) + { + super(job, rootFullname); + } + + @Override + public abstract T visit(ScribNode n); +} diff --git a/scribble-ast/src/main/java/org/scribble/visit/VisitorFactory.java b/scribble-ast/src/main/java/org/scribble/visit/VisitorFactory.java new file mode 100644 index 000000000..e7030320b --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/visit/VisitorFactory.java @@ -0,0 +1,31 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.visit; + +import org.scribble.core.type.name.ModuleName; +import org.scribble.core.type.session.STypeFactory; +import org.scribble.job.Job; + +// Both Ast and SimpleVisitor +public interface VisitorFactory +{ + // SimpleVisitor + GTypeTranslator GTypeTranslator(Job job, ModuleName rootFullname, + STypeFactory tf); + + // AstVisitor + DelDecorator DelDecorator(Job job); + + NameDisambiguator NameDisambiguator(Job job); +} diff --git a/scribble-ast/src/main/java/org/scribble/visit/VisitorFactoryImpl.java b/scribble-ast/src/main/java/org/scribble/visit/VisitorFactoryImpl.java new file mode 100644 index 000000000..b0ce8d460 --- /dev/null +++ b/scribble-ast/src/main/java/org/scribble/visit/VisitorFactoryImpl.java @@ -0,0 +1,46 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.visit; + +import org.scribble.core.type.name.ModuleName; +import org.scribble.core.type.session.STypeFactory; +import org.scribble.job.Job; + +// Both Ast and SimpleVisitor +public class VisitorFactoryImpl implements VisitorFactory +{ + // SimpleVisitors + + @Override + public GTypeTranslator GTypeTranslator(Job job, ModuleName rootFullname, + STypeFactory tf) + { + return new GTypeTranslator(job, rootFullname, tf); + } + + + // AstVisitors + + @Override + public DelDecorator DelDecorator(Job job) + { + return new DelDecorator(job); + } + + @Override + public NameDisambiguator NameDisambiguator(Job job) + { + return new NameDisambiguator(job); + } +} diff --git a/bundles/org.scribble.command/LICENSE.txt b/scribble-cli/LICENSE.txt similarity index 100% rename from bundles/org.scribble.command/LICENSE.txt rename to scribble-cli/LICENSE.txt diff --git a/scribble-cli/build.properties b/scribble-cli/build.properties new file mode 100644 index 000000000..c987bb752 --- /dev/null +++ b/scribble-cli/build.properties @@ -0,0 +1,33 @@ +# +# Copyright 2008 The Scribble 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 +# +# http://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. +# + +source.. = src/main/java/,\ + target/generated-sources/antlr3/ +output.. = bin/ +bin.includes = META-INF/,\ + .,\ + src/main/resources/lib/antlr-3.2.jar,\ + OSGI-INF/,\ + LICENSE.txt +src.includes = target/generated-sources/,\ + src/,\ + pom.xml,\ + build.properties,\ + META-INF/,\ + .project,\ + .classpath,\ + OSGI-INF/,\ + LICENSE.txt +jars.compile.order = .,\ + lib/antlr-3.2.jar diff --git a/scribble-cli/lib/commons-io-2.4.jar b/scribble-cli/lib/commons-io-2.4.jar new file mode 100644 index 000000000..90035a4fe Binary files /dev/null and b/scribble-cli/lib/commons-io-2.4.jar differ diff --git a/scribble-cli/pom.xml b/scribble-cli/pom.xml new file mode 100644 index 000000000..a8b6028f1 --- /dev/null +++ b/scribble-cli/pom.xml @@ -0,0 +1,47 @@ + + 4.0.0 + + + scribble-cli + jar + + + + org.scribble + scribble-core + + + org.scribble + scribble-parser + + + org.scribble + scribble-ast + + + org.scribble + scribble-codegen + + + org.scribble + scribble-main + + + + commons-io + commons-io + + + + + org.scribble + parent + 0.5.1-SNAPSHOT + ../pom.xml + + + + scribble-cli + + diff --git a/scribble-cli/src/main/java/org/scribble/cli/CLArgParser.java b/scribble-cli/src/main/java/org/scribble/cli/CLArgParser.java new file mode 100644 index 000000000..fc77b1158 --- /dev/null +++ b/scribble-cli/src/main/java/org/scribble/cli/CLArgParser.java @@ -0,0 +1,177 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.cli; + +import java.io.File; +import java.util.LinkedList; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; + +import org.scribble.util.Pair; + +// A Scribble extension should call the super constructor, then add any additional flags to this.info -- FIXME: do in CLFlags, not here +// String[] -> Map -- Map array values are the arguments associated to each CommandLine.Arg +public class CLArgParser +{ + private final CLFlags flags; + private final String[] raw; // Raw args from main method + + // Flag String constants from CLFlags -> flag arguments (possibly none) + private final List> parsed = new LinkedList<>(); + + public CLArgParser(CLFlags flags, String[] raw) + { + this.flags = flags; + this.raw = raw; + } + + // Return: left = CLFlags String constant, right = flag args (if any) + public List> getParsed() throws CommandLineException + { + parseArgs(); + List labs = getParsedKeys(); + if (!(labs.contains(CLFlags.MAIN_MOD_FLAG) + ^ labs.contains(CLFlags.INLINE_MAIN_MOD_FLAG))) + { + throw new CommandLineException("No/multiple main module specified\n"); + } + if (labs.contains(CLFlags.MAIN_MOD_FLAG)) + { + String main = getParsedUnique(CLFlags.MAIN_MOD_FLAG)[0]; + if (!validateModuleArg(main)) + { + throw new CommandLineException("Bad module arg: " + main); + } + } + if (labs.contains(CLFlags.IMPORT_PATH_FLAG)) + { + validatePaths(getParsedUnique(CLFlags.IMPORT_PATH_FLAG)[0]); + } + return this.parsed; + } + + private void parseArgs() throws CommandLineException + { + for (int i = 0; i < this.raw.length; ) // Parse args in order + { + String arg = this.raw[i]; + if (this.flags.explicit.containsKey(arg)) + { + List labs = getParsedKeys(); + List clashes = this.flags.explicit.get(arg).clashes.stream() + .filter(x -> labs.contains(x)).collect(Collectors.toList()); + if (!clashes.isEmpty()) + { + throw new CommandLineException( + "Flag clash for " + arg + ": " + clashes); + } + i = this.parseFlag(i); // Returns index of next arg to parse + } + else + { + if (isMainModuleParsed()) + { + if (arg.startsWith("-")) + { + throw new CommandLineException( + "Unknown flag or bad main module arg: " + arg); + } + // Could actually be the second "bad argument" -- we didn't validate the value of the (supposed) "main arg" + throw new CommandLineException( + "Bad/multiple main module arg: " + arg); + } + i = parseMain(i); + } + } + } + + // Pre: i = (the index of the current flag to parse) + // Puts into this.parsed + // Post: i = 1 + (the index of the last argument parsed) + // N.B. currently allows repeat flag decls: last overwrites previous + protected int parseFlag(int i) throws CommandLineException + { + String lab = this.raw[i]; + if (this.flags.explicit.get(lab).unique) + { + if (getParsedKeys().contains(lab)) + { + throw new CommandLineException("duplicate: " + lab); + } + } + int num = this.flags.explicit.get(lab).numArgs; + if ((i + num) >= this.raw.length) + { + throw new CommandLineException(this.flags.explicit.get(lab).err); + } + String[] flagArgs = new String[num]; + if (num > 0) + { + System.arraycopy(this.raw, i+1, flagArgs, 0, num); + } + this.parsed.add(new Pair<>(lab, flagArgs)); + return i+1 + num; + } + + // Puts into this.parsed + protected int parseMain(int i) throws CommandLineException + { + String main = this.raw[i]; + this.parsed.add(new Pair<>(CLFlags.MAIN_MOD_FLAG, new String[]{main})); + return i+1; + } + + private boolean isMainModuleParsed() + { + List labs = getParsedKeys(); + return labs.contains(CLFlags.MAIN_MOD_FLAG) + || labs.contains(CLFlags.INLINE_MAIN_MOD_FLAG); + } + + // This check guards the subsequent file open attempt? + private boolean validateModuleArg(String arg) + { + return arg.chars() + .noneMatch(i -> !Character.isLetterOrDigit(i) && i != '.' + && i != File.separatorChar && i != ':' && i != '-' && i != '_' + && i != '/'); // Hack? (cygwin) + } + + private boolean validatePaths(String paths) + { + for (String path : paths.split(File.pathSeparator)) + { + if (!new File(path).isDirectory()) + { + return false; + } + } + return true; + } + + private List getParsedKeys() + { + return this.parsed.stream().map(x -> x.left).collect(Collectors.toList()); + } + + // Hardcoded to find any one, so applies to uniques only + private String[] getParsedUnique(String flag) + { + Optional> res = this.parsed.stream() + .filter(x -> x.left.equals(flag)).findAny(); + return res.isPresent() ? res.get().right : null; + } +} + diff --git a/scribble-cli/src/main/java/org/scribble/cli/CLFlag.java b/scribble-cli/src/main/java/org/scribble/cli/CLFlag.java new file mode 100644 index 000000000..c2e21db1b --- /dev/null +++ b/scribble-cli/src/main/java/org/scribble/cli/CLFlag.java @@ -0,0 +1,64 @@ +package org.scribble.cli; + +import java.util.Arrays; +import java.util.List; + + +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +public class CLFlag +{ + final String lab; // ID field: CLFlags String constant -- N.B. includes "-" prefix + final int numArgs; + final boolean unique; + final boolean enact; + final boolean barrier; // TODO: rename, barrier misleading (sounds like a sync) + final String err; + final List clashes; + + public CLFlag(String lab, int numArgs, boolean unique, boolean enact, + boolean barrier, String err, String... clashes) + { + this.lab = lab; + this.numArgs = numArgs; + this.unique = unique; + this.enact = enact; + this.barrier = barrier; + this.err = err; + this.clashes = Arrays.asList(clashes); + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof CLFlag)) + { + return false; + } + CLFlag them = (CLFlag) o; + return this.lab.equals(them.lab); + } + + @Override + public int hashCode() + { + int hash = 14411; + hash = 31 * this.lab.hashCode(); + return hash; + } +} \ No newline at end of file diff --git a/scribble-cli/src/main/java/org/scribble/cli/CLFlags.java b/scribble-cli/src/main/java/org/scribble/cli/CLFlags.java new file mode 100644 index 000000000..f44ca67ad --- /dev/null +++ b/scribble-cli/src/main/java/org/scribble/cli/CLFlags.java @@ -0,0 +1,178 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.cli; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + + +// Flag Strings must start with "-", e.g., "-project" +// A Scribble extension should override getFlags +public class CLFlags +{ + // Maps flag String constant to CLFlag object + // N.B. does not include MAIN_MOD_FLAG + public final Map explicit; + + // Unique flags + public static final String JUNIT_FLAG = "-junit"; // For internal use (JUnit test harness) + public static final String IMPORT_PATH_FLAG = "-ip"; + public static final String API_OUTPUT_DIR_FLAG = "-d"; + public static final String VERBOSE_FLAG = "-v"; + public static final String STATECHAN_SUBTYPES_FLAG = "-subtypes"; + public static final String OLD_WF_FLAG = "-oldwf"; + public static final String NO_PROGRESS_FLAG = "-noprogress"; + public static final String LTSCONVERT_MIN_FLAG = "-minlts"; // Currently only affects EFSM output (i.e. -fsm..) and API gen -- doesn't affect validation + public static final String FAIR_FLAG = "-fair"; + public static final String NO_LOCAL_CHOICE_SUBJECT_CHECK_FLAG = "-nolocalchoicecheck"; + public static final String NO_ACCEPT_CORRELATION_CHECK_FLAG = "-nocorrelation"; + public static final String DOT_FLAG = "-dot"; + public static final String AUT_FLAG = "-aut"; + public static final String NO_VALIDATION_FLAG = "-novalid"; + public static final String INLINE_MAIN_MOD_FLAG = "-inline"; + + // Non-unique flags + public static final String PROJECT_FLAG = "-project"; + public static final String EFSM_FLAG = "-fsm"; + public static final String VALIDATION_EFSM_FLAG = "-vfsm"; + public static final String UNFAIR_EFSM_FLAG = "-ufsm"; + public static final String UNFAIR_EFSM_PNG_FLAG = "-ufsmpng"; + public static final String EFSM_PNG_FLAG = "-fsmpng"; + public static final String VALIDATION_EFSM_PNG_FLAG = "-vfsmpng"; + public static final String SGRAPH_FLAG = "-model"; + public static final String UNFAIR_SGRAPH_FLAG = "-umodel"; + public static final String SGRAPH_PNG_FLAG = "-modelpng"; + public static final String UNFAIR_SGRAPH_PNG_FLAG = "-umodelpng"; + public static final String API_GEN_FLAG = "-api"; + public static final String SESSION_API_GEN_FLAG = "-sessapi"; + public static final String STATECHAN_API_GEN_FLAG = "-chanapi"; + public static final String EVENTDRIVEN_API_GEN_FLAG = "-cbapi"; + + // Implicit (and unique) -- N.B. not added to this.flags, because implicit + public static final String MAIN_MOD_FLAG = "__main"; + + public CLFlags() + { + this.explicit = Collections.unmodifiableMap(getFlags()); + } + + // Return a map of flag Strings to flag objects + // A Scribble extension should override getFlags -- e.g., call super, then put any additional + protected Map getFlags() + { + Map flags = new HashMap<>(); + + // Unique; barrier irrelevant + flags.put(IMPORT_PATH_FLAG, + new CLFlag(IMPORT_PATH_FLAG, 1, true, false, false, + "Missing path argument: ")); + flags.put(API_OUTPUT_DIR_FLAG, + new CLFlag(API_OUTPUT_DIR_FLAG, 1, true, false, false, + "Missing directory argument: ")); + flags.put(INLINE_MAIN_MOD_FLAG, + new CLFlag(INLINE_MAIN_MOD_FLAG, 1, true, false, false, + "Missing inline module: ")); + + flags.put(JUNIT_FLAG, + new CLFlag(JUNIT_FLAG, 0, true, false, false, "Duplicate flag: ")); + flags.put(VERBOSE_FLAG, + new CLFlag(VERBOSE_FLAG, 0, true, false, false, "Duplicate flag: ")); + flags.put(STATECHAN_SUBTYPES_FLAG, + new CLFlag(STATECHAN_SUBTYPES_FLAG, 0, true, false, false, + "Duplicate flag: ")); + flags.put(OLD_WF_FLAG, + new CLFlag(OLD_WF_FLAG, 0, true, false, false, "Duplicate flag: ", + SGRAPH_FLAG, UNFAIR_SGRAPH_FLAG, SGRAPH_PNG_FLAG, + UNFAIR_SGRAPH_PNG_FLAG)); + flags.put(NO_PROGRESS_FLAG, + new CLFlag(NO_PROGRESS_FLAG, 0, true, false, false, "Duplicate flag: ")); + flags.put(LTSCONVERT_MIN_FLAG, + new CLFlag(LTSCONVERT_MIN_FLAG, 0, true, false, false, + "Duplicate flag: ")); + flags.put(FAIR_FLAG, + new CLFlag(FAIR_FLAG, 0, true, false, false, "Duplicate flag: ")); + flags.put(NO_LOCAL_CHOICE_SUBJECT_CHECK_FLAG, + new CLFlag(NO_LOCAL_CHOICE_SUBJECT_CHECK_FLAG, 0, true, false, false, + "Duplicate flag: ")); + flags.put(NO_ACCEPT_CORRELATION_CHECK_FLAG, + new CLFlag(NO_ACCEPT_CORRELATION_CHECK_FLAG, 0, true, false, false, + "Duplicate flag: ")); + flags.put(NO_VALIDATION_FLAG, + new CLFlag(NO_VALIDATION_FLAG, 0, true, false, false, + "Duplicate flag: ")); + + // These two are mutually exclusive + flags.put(DOT_FLAG, + new CLFlag(DOT_FLAG, 0, true, false, false, "Duplicate flag: ", + CLFlags.AUT_FLAG)); + flags.put(AUT_FLAG, + new CLFlag(AUT_FLAG, 0, true, false, false, "Duplicate flag: ", + CLFlags.DOT_FLAG)); + + // Non-unique, no barrier + flags.put(PROJECT_FLAG, + new CLFlag(PROJECT_FLAG, 2, false, true, false, + "Missing protocol/role arguments: ")); + flags.put(EFSM_FLAG, + new CLFlag(EFSM_FLAG, 2, false, true, false, + "Missing protocol/role arguments: ")); + flags.put(VALIDATION_EFSM_FLAG, + new CLFlag(VALIDATION_EFSM_FLAG, 2, false, true, false, + "Missing protocol/role arguments: ")); + flags.put(UNFAIR_EFSM_FLAG, + new CLFlag(UNFAIR_EFSM_FLAG, 2, false, true, false, + "Missing protocol/role arguments: ")); + + flags.put(EFSM_PNG_FLAG, + new CLFlag(EFSM_PNG_FLAG, 3, false, true, false, + "Missing protocol/role/file arguments: ")); + flags.put(VALIDATION_EFSM_PNG_FLAG, + new CLFlag(VALIDATION_EFSM_PNG_FLAG, 3, false, true, false, + "Missing protocol/role/file arguments: ")); + flags.put(UNFAIR_EFSM_PNG_FLAG, + new CLFlag(UNFAIR_EFSM_PNG_FLAG, 3, false, true, false, + "Missing protocol/role/file arguments: ")); + + flags.put(SGRAPH_FLAG, + new CLFlag(SGRAPH_FLAG, 1, false, true, false, + "Missing protocol argument: ", OLD_WF_FLAG)); + flags.put(UNFAIR_SGRAPH_FLAG, + new CLFlag(UNFAIR_SGRAPH_FLAG, 1, false, true, false, + "Missing protocol argument: ", OLD_WF_FLAG)); + + flags.put(SGRAPH_PNG_FLAG, + new CLFlag(SGRAPH_PNG_FLAG, 2, false, true, false, + "Missing protocol/file arguments: ", OLD_WF_FLAG)); + flags.put(UNFAIR_SGRAPH_PNG_FLAG, + new CLFlag(UNFAIR_SGRAPH_PNG_FLAG, 2, false, true, false, + "Missing protocol/file arguments: ", OLD_WF_FLAG)); + + // // Non-unique, barrier + flags.put(SESSION_API_GEN_FLAG, + new CLFlag(SESSION_API_GEN_FLAG, 1, false, true, true, + "Missing protocol argument: ")); + flags.put(API_GEN_FLAG, + new CLFlag(API_GEN_FLAG, 2, false, true, true, + "Missing protocol/role arguments: ")); + flags.put(STATECHAN_API_GEN_FLAG, + new CLFlag(STATECHAN_API_GEN_FLAG, 2, false, true, true, + "Missing protocol/role arguments: ")); + flags.put(EVENTDRIVEN_API_GEN_FLAG, + new CLFlag(EVENTDRIVEN_API_GEN_FLAG, 2, false, true, true, + "Missing protocol/role arguments: ")); + + return flags; + } +} diff --git a/scribble-cli/src/main/java/org/scribble/cli/CommandLine.java b/scribble-cli/src/main/java/org/scribble/cli/CommandLine.java new file mode 100644 index 000000000..6b1d78698 --- /dev/null +++ b/scribble-cli/src/main/java/org/scribble/cli/CommandLine.java @@ -0,0 +1,559 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.cli; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Consumer; +import java.util.stream.Collectors; + +import org.scribble.ast.Module; +import org.scribble.ast.ProtoDecl; +import org.scribble.ast.global.GProtoDecl; +import org.scribble.codegen.java.JEndpointApiGenerator; +import org.scribble.codegen.java.callbackapi.CBEndpointApiGenerator3; +import org.scribble.core.job.CoreArgs; +import org.scribble.core.job.CoreContext; +import org.scribble.core.model.endpoint.EGraph; +import org.scribble.core.model.global.SGraph; +import org.scribble.core.type.kind.Local; +import org.scribble.core.type.name.GProtoName; +import org.scribble.core.type.name.LProtoName; +import org.scribble.core.type.name.ProtoName; +import org.scribble.core.type.name.Role; +import org.scribble.core.visit.global.InlinedProjector; +import org.scribble.job.Job; +import org.scribble.job.JobContext; +import org.scribble.main.Main; +import org.scribble.main.resource.locator.DirectoryResourceLocator; +import org.scribble.main.resource.locator.ResourceLocator; +import org.scribble.util.AntlrSourceException; +import org.scribble.util.Pair; +import org.scribble.util.RuntimeScribException; +import org.scribble.util.ScribException; +import org.scribble.util.ScribParserException; +import org.scribble.util.ScribUtil; + +/** + * A Scribble extension should override newCLFlags, newCLArgParser, newMain, + * parseJobArgs, doValidationTasks, tryNonBarrierTask and tryBarrierTask as + * appropriate + * + * @author rhu1 + */ +public class CommandLine +{ + protected final CLFlags flags; + protected final List> args; + // left = CLFlags String constant, right = flag args (if any) -- ordered by parsing order + + public CommandLine(String... args) + { + this.flags = newCLFlags(); + try + { + this.args = newCLArgParser(this.flags, args).getParsed(); + } + catch (CommandLineException e) + { + System.err.println(e.getMessage()); + System.exit(1); + throw new RuntimeException("Dummy"); // Already exited above + } + } + + private boolean hasFlag(String flag) + { + return this.args.stream().anyMatch(x -> x.left.equals(flag)); + } + + private String[] getUniqueFlagArgs(String flag) + { + return this.args.stream().filter(x -> x.left.equals(flag)).findAny() + .get().right; + } + + protected CLFlags newCLFlags() + { + return new CLFlags(); + } + + // A Scribble extension should override as appropriate + protected CLArgParser newCLArgParser(CLFlags flags, String[] args) + { + return new CLArgParser(flags, args); + } + + // A Scribble extension should override as appropriate + protected Main newMain() throws ScribParserException, ScribException + { + Map args = Collections.unmodifiableMap(parseCoreArgs()); + if (hasFlag(CLFlags.INLINE_MAIN_MOD_FLAG)) + { + String inline = getUniqueFlagArgs(CLFlags.INLINE_MAIN_MOD_FLAG)[0]; + return new Main(inline, args); + } + else + { + List impaths = hasFlag(CLFlags.IMPORT_PATH_FLAG) + ? CommandLine + .parseImportPaths(getUniqueFlagArgs(CLFlags.IMPORT_PATH_FLAG)[0]) + : Collections.emptyList(); + ResourceLocator locator = new DirectoryResourceLocator(impaths); + Path mainpath = CommandLine + .parseMainPath(getUniqueFlagArgs(CLFlags.MAIN_MOD_FLAG)[0]); + return new Main(locator, mainpath, args); + } + } + + // A Scribble extension should override as appropriate + protected Map parseCoreArgs() + { + Map args = new HashMap<>(); + args.put(CoreArgs.VERBOSE, hasFlag(CLFlags.VERBOSE_FLAG)); + args.put(CoreArgs.OLD_WF, hasFlag(CLFlags.OLD_WF_FLAG)); + args.put(CoreArgs.NO_PROGRESS, hasFlag(CLFlags.NO_PROGRESS_FLAG)); + args.put(CoreArgs.MIN_EFSM, hasFlag(CLFlags.LTSCONVERT_MIN_FLAG)); + args.put(CoreArgs.FAIR, hasFlag(CLFlags.FAIR_FLAG)); + args.put(CoreArgs.NO_LCHOICE_SUBJ_CHECK, + hasFlag(CLFlags.NO_LOCAL_CHOICE_SUBJECT_CHECK_FLAG)); + args.put(CoreArgs.NO_ACC_CORRELATION_CHECK, + hasFlag(CLFlags.NO_ACCEPT_CORRELATION_CHECK_FLAG)); + args.put(CoreArgs.NO_VALIDATION, hasFlag(CLFlags.NO_VALIDATION_FLAG)); + return args; + } + + // AntlrSourceException super of ScribbleException -- needed for, e.g., AssrtCoreSyntaxException + // A Scribble extension should override as appropriate + protected void doValidationTasks(Job job) + throws AntlrSourceException, ScribParserException, // Latter in case needed by subclasses + CommandLineException + { + job.runPasses(); + job.getCore().runPasses(); + } + + // A Scribble extension should override as appropriate + // TODO: rename, barrier misleading (sounds like a sync) + protected void tryNonBarrierTask(Job job, Pair task) + throws CommandLineException, ScribException + { + switch (task.left) // Flag lab (CLFlags String constants) + { + case CLFlags.PROJECT_FLAG: + printProjection(job, task.right); + break; + case CLFlags.EFSM_FLAG: + outputEGraph(job, task.right, true, true, false); + break; + case CLFlags.EFSM_PNG_FLAG: + outputEGraph(job, task.right, true, true, true); + break; + case CLFlags.SGRAPH_FLAG: + outputSGraph(job, task.right, true, false); + break; + case CLFlags.SGRAPH_PNG_FLAG: + outputSGraph(job, task.right, true, true); + break; + + // CHECKME: -unfair needs to be barrier-ed on syntactic WF? (o/w unfair-transform graph building may crash, e.g., bad.wfchoice.enabling.threeparty.Test02) + // Currently, "construction-on-demand" CoreContext getters will still cause these to be attempted even if syntactic WF fails + case CLFlags.VALIDATION_EFSM_FLAG: + outputEGraph(job, task.right, false, true, false); + break; + case CLFlags.VALIDATION_EFSM_PNG_FLAG: + outputEGraph(job, task.right, false, true, true); + break; + case CLFlags.UNFAIR_EFSM_FLAG: + outputEGraph(job, task.right, false, false, false); + break; + case CLFlags.UNFAIR_EFSM_PNG_FLAG: + outputEGraph(job, task.right, false, false, true); + break; + case CLFlags.UNFAIR_SGRAPH_FLAG: + outputSGraph(job, task.right, false, false); + break; + case CLFlags.UNFAIR_SGRAPH_PNG_FLAG: + outputSGraph(job, task.right, false, true); + break; + + default: + throw new RuntimeException("Shouldn't get here: " + task.left); + // Bad flag should be caught by CLArgParser + } + } + + // A Scribble extension should override as appropriate + // TODO: rename, barrier misleading (sounds like a sync) + protected void tryBarrierTask(Job job, + Pair task) throws ScribException, CommandLineException + { + switch (task.left) + { + case CLFlags.SESSION_API_GEN_FLAG: + outputEndpointApi(job, task.right, true, false, false); + break; + case CLFlags.STATECHAN_API_GEN_FLAG: + outputEndpointApi(job, task.right, false, true, false); + break; + case CLFlags.API_GEN_FLAG: + outputEndpointApi(job, task.right, true, true, false); + break; + case CLFlags.EVENTDRIVEN_API_GEN_FLAG: + outputEndpointApi(job, task.right, false, true, true); // FIXME: currently need to gen sess API separately? + break; + default: + throw new RuntimeException("Shouldn't get here: " + task.left); + // Bad flag should be caught by CLArgParser + } + } + + public static void main(String[] args) + throws CommandLineException, AntlrSourceException + { + new CommandLine(args).run(); + } + + public void run() throws CommandLineException, + AntlrSourceException // For JUnit harness (ScribException) + { + try + { + try + { + runTasks(); + } + catch (ScribException e) // Wouldn't need to do this if not Runnable (so maybe change) + { + if (hasFlag(CLFlags.JUNIT_FLAG) // JUnit harness looks for an exception + || hasFlag(CLFlags.VERBOSE_FLAG)) // Also print full trace for -V + { + throw e; + } + else + { + System.err.println(e.getMessage()); + System.exit(1); + } + } + } + catch (ScribParserException | CommandLineException e) + { + System.err.println(e.getMessage()); // No need to give full stack trace, even for debug, for command line errors + System.exit(1); + } + catch (RuntimeScribException e) + { + System.err.println(e.getMessage()); + System.exit(1); + } + } + + protected void runTasks() + throws AntlrSourceException, ScribParserException, CommandLineException + { + Main mc = newMain(); // Represents current instance of tooling for given CL args + Job job = mc.newJob(); // A Job is some series of passes performed on each Module in the MainContext (e.g., cf. Job::runVisitorPass) + ScribException err = null; + try { doValidationTasks(job); } catch (ScribException x) { err = x; } + for (Pair a : this.args) + { + CLFlag flag = this.flags.explicit.get(a.left); // null for CLFlags.MAIN_MOD_FLAG + if (a.left.equals(CLFlags.MAIN_MOD_FLAG) || !flag.enact) + { + continue; + } + if (!flag.barrier) + { + try { tryNonBarrierTask(job, a); } + catch (ScribException x) { if (err == null) { err = x; } } + } + else + { + if (err == null) + { + try { tryBarrierTask(job, a); } + catch (ScribException x) { err = x; } + } + } + } + if (err != null) + { + throw err; + } + } + + // TODO: option to write to file, like API classes + private void printProjection(Job job, String[] args) + throws CommandLineException, ScribException + { + JobContext jobc = job.getContext(); + for (int i = 0; i < args.length; i += 2) + { + GProtoName fullname = checkGlobalProtocolArg(jobc, args[i]); + Role self = checkRoleArg(jobc, fullname, args[i+1]); + Map, Module> projs = job.getProjections(fullname, self); + LProtoName rootFullname = InlinedProjector.getFullProjectionName(fullname, + self); + Module root = projs.get(rootFullname); + System.out.println( + "\nProjection modules for " + fullname + "@" + self + ":\n\n" + root); + for (ProtoName pfullname : projs.keySet()) + { + // CHECKME: projection decl name is currently *compound* full name (not simple name), OK? + if (!pfullname.equals(rootFullname)) + { + System.out.println("\n" + projs.get(pfullname)); + } + } + } + } + + // dot/aut text output + // forUser: true means for API gen and general user info (may be minimised), false means for validation (non-minimised, fair or unfair) + // (forUser && !fair) should not hold, i.e. unfair doesn't make sense if forUser + private void outputEGraph(Job job, String[] args, boolean forUser, + boolean fair, boolean draw) throws ScribException, CommandLineException + { + JobContext jobc = job.getContext(); + + GProtoName fullname = checkGlobalProtocolArg(jobc, args[0]); + Role role = checkRoleArg(jobc, fullname, args[1]); + EGraph fsm = getEGraph(job, fullname, role, forUser, fair); + if (draw) + { + String png = args[2]; + runDot(fsm.toDot(), png); + } + else // print + { + String out = hasFlag(CLFlags.AUT_FLAG) + ? fsm.toAut() + : fsm.toDot(); // default: dot + System.out.println("\n" + out); // Endpoint graphs are "inlined" (a single graph is built) + } + } + + private void outputSGraph(Job job, String[] args, boolean fair, + boolean draw) throws ScribException, CommandLineException + { + JobContext jobc = job.getContext(); + { + GProtoName fullname = checkGlobalProtocolArg(jobc, args[0]); + SGraph model = getSGraph(job, fullname, fair); + if (draw) + { + String png = args[1]; + runDot(model.toDot(), png); + } + else // print + { + String out = hasFlag(CLFlags.AUT_FLAG) + ? model.toAut() + : model.toDot(); + System.out.println("\n" + out); + } + } + } + + private void outputEndpointApi(Job job, String[] args, boolean sess, + boolean schan, boolean cb) throws ScribException, CommandLineException + { + JobContext jobc = job.getContext(); + JEndpointApiGenerator jgen = new JEndpointApiGenerator(job); // FIXME: refactor (generalise -- use new API) + { + GProtoName fullname = checkGlobalProtocolArg(jobc, args[0]); + if (sess) + { + Map out = jgen.generateSessionApi(fullname); + outputClasses(out); + } + if (schan) // CHECKME: does not implicitly generate sess API? + { + Role self = checkRoleArg(jobc, fullname, args[1]); + if (cb) + { + CBEndpointApiGenerator3 cbgen = new CBEndpointApiGenerator3(job, + fullname, self, hasFlag(CLFlags.STATECHAN_SUBTYPES_FLAG)); + Map out = cbgen.build(); + outputClasses(out); + } + else + { + Map out = jgen.generateStateChannelApi(fullname, + self, hasFlag(CLFlags.STATECHAN_SUBTYPES_FLAG)); + outputClasses(out); + } + } + } + } + + // Endpoint graphs are "inlined", so only a single graph is built (cf. projection output) + private EGraph getEGraph(Job job, GProtoName fullname, Role role, + boolean forUser, boolean fair) + throws ScribException, CommandLineException + { + JobContext jobc = job.getContext(); + CoreContext corec = job.getCore().getContext(); + GProtoDecl gpd = jobc.getMainModule() + .getGProtocolDeclChild(fullname.getSimpleName()); + if (gpd == null || !gpd.getHeaderChild().getRoleDeclListChild().getRoles() + .contains(role)) + { + throw new CommandLineException("Bad FSM construction args: " + + gpd + ", " + role); + } + EGraph graph; + if (forUser) // The (possibly minimised) user-output EFSM for API gen + { + graph = hasFlag(CLFlags.LTSCONVERT_MIN_FLAG) + ? corec.getMinimisedEGraph(fullname, role) + : corec.getEGraph(fullname, role); + } + else // The (possibly unfair-transformed) internal EFSM for validation + { + graph = //(!this.args.containsKey(ArgFlag.FAIR) && !this.args.containsKey(ArgFlag.NO_LIVENESS)) // Cf. GlobalModelChecker.getEndpointFSMs + !fair + ? corec.getUnfairEGraph(fullname, role) + : corec.getEGraph(fullname, role); + } + if (graph == null) + { + throw new RuntimeScribException("Shouldn't see this: " + fullname); + // Should be caught by some earlier failure + } + return graph; + } + + private SGraph getSGraph(Job job, GProtoName fullname, boolean fair) + throws ScribException + { + CoreContext jobc2 = job.getCore().getContext(); + SGraph model = fair + ? jobc2.getSGraph(fullname) + : jobc2.getUnfairSGraph(fullname); + if (model == null) + { + throw new RuntimeScribException("Shouldn't see this: " + fullname); + // Should be caught by some earlier failure + } + return model; + } + + // classes: filepath -> class source + protected void outputClasses(Map classes) + throws ScribException + { + Consumer f; + if (hasFlag(CLFlags.API_OUTPUT_DIR_FLAG)) + { + String dir = getUniqueFlagArgs(CLFlags.API_OUTPUT_DIR_FLAG)[0]; + f = path -> { ScribUtil.handleLambdaScribbleException(() -> + { + String tmp = dir + "/" + path; + if (hasFlag(CLFlags.VERBOSE_FLAG)) + { + System.out.println("[DEBUG] Writing to: " + tmp); + } + ScribUtil.writeToFile(tmp, classes.get(path)); + return null; + }); + }; + } + else + { + f = path -> { System.out.println(path + ":\n" + classes.get(path)); }; + } + classes.keySet().forEach(f); + } + + protected static void runDot(String dot, String png) + throws ScribException, CommandLineException + { + File tmp = null; + try + { + tmp = File.createTempFile(png, ".tmp"); + String tmpName = tmp.getAbsolutePath(); + ScribUtil.writeToFile(tmpName, dot); + String[] res = ScribUtil.runProcess("dot", "-Tpng", "-o" + png, tmpName); + System.out.print(!res[1].isEmpty() ? res[1] : res[0]); // already "\n" terminated + } + catch (IOException e) + { + throw new CommandLineException(e); + } + finally + { + if (tmp != null) + { + tmp.delete(); + } + } + } + + protected static Path parseMainPath(String path) + { + return Paths.get(path); + } + + protected static List parseImportPaths(String paths) + { + return Arrays.stream(paths.split(File.pathSeparator)).map(s -> Paths.get(s)) + .collect(Collectors.toList()); + } + + protected static GProtoName checkGlobalProtocolArg(JobContext jobc, + String simpname) throws CommandLineException + { + GProtoName simpgpn = new GProtoName(simpname); + Module main = jobc.getMainModule(); + if (!main.hasGProtocolDecl(simpgpn)) + { + throw new CommandLineException("Global protocol not found: " + simpname); + } + ProtoDecl pd = main.getGProtocolDeclChild(simpgpn); + if (pd == null || !pd.isGlobal()) + { + throw new CommandLineException("Global protocol not found: " + simpname); + } + if (pd.isAux()) // CHECKME: maybe don't check for all, e.g. -project + { + throw new CommandLineException( + "Invalid aux protocol specified as root: " + simpname); + } + return new GProtoName(jobc.job.config.main, simpgpn); // TODO: take Job param instead of Jobcontext + } + + protected static Role checkRoleArg(JobContext jobc, + GProtoName fullname, String rolename) throws CommandLineException + { + ProtoDecl pd = jobc.getMainModule() + .getGProtocolDeclChild(fullname.getSimpleName()); + Role role = new Role(rolename); + if (!pd.getHeaderChild().getRoleDeclListChild().getRoles().contains(role)) + { + throw new CommandLineException( + "Role not declared for " + fullname + ": " + role); + } + return role; + } +} diff --git a/scribble-cli/src/main/java/org/scribble/cli/CommandLineException.java b/scribble-cli/src/main/java/org/scribble/cli/CommandLineException.java new file mode 100644 index 000000000..62e594706 --- /dev/null +++ b/scribble-cli/src/main/java/org/scribble/cli/CommandLineException.java @@ -0,0 +1,48 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.cli; + +public class CommandLineException extends Exception +{ + private static final long serialVersionUID = 1L; + + public CommandLineException() + { + // TODO Auto-generated constructor stub + } + + public CommandLineException(String arg0) + { + super(arg0); + // TODO Auto-generated constructor stub + } + + public CommandLineException(Throwable arg0) + { + super(arg0); + // TODO Auto-generated constructor stub + } + + public CommandLineException(String arg0, Throwable arg1) + { + super(arg0, arg1); + // TODO Auto-generated constructor stub + } + + public CommandLineException(String arg0, Throwable arg1, boolean arg2, boolean arg3) + { + super(arg0, arg1, arg2, arg3); + // TODO Auto-generated constructor stub + } +} diff --git a/scribble-codegen/pom.xml b/scribble-codegen/pom.xml new file mode 100644 index 000000000..058edd750 --- /dev/null +++ b/scribble-codegen/pom.xml @@ -0,0 +1,30 @@ + + + 4.0.0 + + + scribble-codegen + + + + org.scribble + scribble-core + + + org.scribble + scribble-ast + + + + + org.scribble + parent + 0.5.1-SNAPSHOT + ../pom.xml + + + + scribble-codegen + + diff --git a/scribble-codegen/src/main/java/org/scribble/codegen/java/ApiGen.java b/scribble-codegen/src/main/java/org/scribble/codegen/java/ApiGen.java new file mode 100644 index 000000000..08c02557f --- /dev/null +++ b/scribble-codegen/src/main/java/org/scribble/codegen/java/ApiGen.java @@ -0,0 +1,44 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.codegen.java; + +import java.util.Map; + +import org.scribble.core.job.Core; +import org.scribble.core.type.name.GProtoName; +import org.scribble.job.Job; + +// Basic pattern: use TypeGenerators to create all necessary TypeBuilders and cache them, and generateApi should call build on all as a final step +public abstract class ApiGen +{ + public final Job job; + public final Core core; + public final GProtoName gpn; // full name + + public ApiGen(Job job, GProtoName fullname) + { + this.job = job; + this.core = job.getCore(); + this.gpn = fullname; + } + + // Return: key (package and Java class file path) -> val (Java class source) + // FIXME: Path instead of String key? + public abstract Map generateApi(); + + public Job getJob() + { + return this.job; + } +} diff --git a/scribble-codegen/src/main/java/org/scribble/codegen/java/JEndpointApiGenerator.java b/scribble-codegen/src/main/java/org/scribble/codegen/java/JEndpointApiGenerator.java new file mode 100644 index 000000000..c30ad3c7f --- /dev/null +++ b/scribble-codegen/src/main/java/org/scribble/codegen/java/JEndpointApiGenerator.java @@ -0,0 +1,80 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.codegen.java; + +import java.util.HashMap; +import java.util.Map; + +import org.scribble.codegen.java.sessionapi.SessionApiGenerator; +import org.scribble.codegen.java.statechanapi.StateChannelApiGenerator; +import org.scribble.codegen.java.statechanapi.ioifaces.IOInterfacesGenerator; +import org.scribble.core.type.name.GProtoName; +import org.scribble.core.type.name.Role; +import org.scribble.job.Job; +import org.scribble.util.RuntimeScribException; +import org.scribble.util.ScribException; + +public class JEndpointApiGenerator +{ + public final Job job; + + public JEndpointApiGenerator(Job job) + { + this.job = job; + } + + public Map generateSessionApi(GProtoName fullname) + throws ScribException + { + this.job.verbosePrintln("\n[Java API gen] Running " + + SessionApiGenerator.class + " for " + fullname); + SessionApiGenerator sg = new SessionApiGenerator(this.job, fullname); // FIXME: reuse? + Map map = sg.generateApi(); // filepath -> class source + return map; + } + + // CHECKME: refactor an EndpointApiGenerator -- ? + public Map generateStateChannelApi(GProtoName fullname, + Role self, boolean subtypes) throws ScribException + { + /*JobContext jc = this.job.getContext(); + if (jc.getEndpointGraph(fullname, self) == null) + { + buildGraph(fullname, self); + }*/ + job.verbosePrintln("\n[Java API gen] Running " + + StateChannelApiGenerator.class + " for " + fullname + "@" + self); + StateChannelApiGenerator apigen = new StateChannelApiGenerator(this.job, + fullname, self); + IOInterfacesGenerator iogen = null; + try + { + iogen = new IOInterfacesGenerator(apigen, subtypes); + } + catch (RuntimeScribException e) // FIXME: use IOInterfacesGenerator.skipIOInterfacesGeneration + { + //System.err.println("[Warning] Skipping I/O Interface generation for protocol featuring: " + fullname); + this.job.warningPrintln("Skipping I/O Interface generation for: " + + fullname + "\n Cause: " + e.getMessage()); + } + // Construct the Generators first, to build all the types -- then call generate to "compile" all Builders to text (further building changes will not be output) + Map api = new HashMap<>(); // filepath -> class source // Store results? + api.putAll(apigen.generateApi()); + if (iogen != null) + { + api.putAll(iogen.generateApi()); + } + return api; + } +} diff --git a/scribble-codegen/src/main/java/org/scribble/codegen/java/callbackapi/CBEndpointApiGenerator.java b/scribble-codegen/src/main/java/org/scribble/codegen/java/callbackapi/CBEndpointApiGenerator.java new file mode 100644 index 000000000..539b534d2 --- /dev/null +++ b/scribble-codegen/src/main/java/org/scribble/codegen/java/callbackapi/CBEndpointApiGenerator.java @@ -0,0 +1,639 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.codegen.java.callbackapi; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.IntStream; +import java.util.stream.Stream; + +import org.scribble.ast.DataDecl; +import org.scribble.ast.Module; +import org.scribble.ast.SigDecl; +import org.scribble.codegen.java.sessionapi.SessionApiGenerator; +import org.scribble.core.job.Core; +import org.scribble.core.job.CoreArgs; +import org.scribble.core.job.CoreContext; +import org.scribble.core.model.endpoint.EState; +import org.scribble.core.model.endpoint.EStateKind; +import org.scribble.core.model.endpoint.actions.EAction; +import org.scribble.core.type.name.DataName; +import org.scribble.core.type.name.GProtoName; +import org.scribble.core.type.name.PayElemType; +import org.scribble.core.type.name.Role; +import org.scribble.job.Job; +import org.scribble.util.ScribException; + +// FIXME: integrate with JEndpointApiGenerator -- this class should correspond to StateChanApiGenerator (relying on the common SessionApiGenerator) +// From ParamCoreEndpointApiGenerator +@Deprecated +public class CBEndpointApiGenerator +{ + public final Job job; + public final Core core; + public final GProtoName proto; + public final Role self; // FIXME: base endpoint API gen is role-oriented, while session API generator should be neutral + + private final boolean subtypes; + + public CBEndpointApiGenerator(Job job, GProtoName fullname, Role self, boolean subtypes) + { + this.job = job; + this.core = job.getCore(); + this.proto = fullname; + this.self = self; + + this.subtypes = subtypes; + if (this.subtypes) + { + throw new RuntimeException("TODO: -subtypes"); + } + } + + public Map build() throws ScribException + { + Map res = new HashMap<>(); // filepath -> source + res.putAll(buildSessionApi()); + return res; + } + + public Map buildSessionApi() throws ScribException // FIXME: factor out -- integrate with JEndpointApiGenerator + { + this.job.verbosePrintln("\n[param-core] Running " + CBEndpointApiGenerator.class + " for " + this.proto + "@" + this.self); + + Map res = new HashMap<>(); + res.putAll(new SessionApiGenerator(this.job, this.proto).generateApi()); + res.putAll(buildEndpointClass()); + return res; + } + + public Map buildEndpointClass() throws ScribException + { + Module main = this.job.getContext().getMainModule(); + CoreContext jobc2 = this.core.getContext(); + EState init = (this.core.config.args.get(CoreArgs.MIN_EFSM) + ? jobc2.getMinimisedEGraph(this.proto, this.self) + : jobc2.getEGraph(this.proto, this.self) + ).init; + // TODO: factor out with StateChannelApiGenerator constructor + Set states = new HashSet<>(); + states.add(init); + states.addAll(init.getReachableStates()); + + // frontend handler class + String pack = SessionApiGenerator.getEndpointApiRootPackageName(this.proto); + String name = this.proto.getSimpleName() + "_" + this.self; + String sess = pack + "." + this.proto.getSimpleName(); + String role = SessionApiGenerator.getRolesPackageName(this.proto) + "." + this.self; + String epClass = ""; + + epClass += "package " + pack + ".handlers." + this.self + ";\n"; + epClass += "\n"; + /*epClass += "import java.util.function.Function;\n"; + epClass += "import java.util.HashMap;\n"; + epClass += "import java.util.Map;\n";*/ + epClass += "\n"; + epClass += "public class " + name + " extends org.scribble.runtime.session.CBEndpoint<" + sess + ", " + role + ", D> {\n"; + + /*epClass += "private final Map> outputs = new HashMap<>();\n"; + epClass += "\n";*/ + + epClass += "public " + name + "(" + sess + " sess, " + role + + " self, org.scribble.runtime.message.ScribMessageFormatter smf, D data) throws java.io.IOException, org.scribble.main.ScribbleRuntimeException {\n"; + epClass += "super(sess, self, smf, " + pack + ".handlers.states." + this.self + "." + name + "_" + init.id + ".id" + ", data);\n"; // FIXME: factor out + for (EState s : states) + { + String tmp = (s.getStateKind() == EStateKind.TERMINAL) ? "End" : this.proto.getSimpleName() + "_" + this.self + "_" + s.id; + epClass += "this.states.put(\"" + tmp + "\", " + SessionApiGenerator.getEndpointApiRootPackageName(this.proto) + ".handlers.states." + this.self + "." + tmp + ".id);\n"; + } + epClass += "}\n"; + epClass += "\n"; + + /*epClass += "public enum State {" + states.stream().map(s -> getEDStateEnum(this.proto, this.self, s)) + "}\n"; + epClass += "\n";*/ + + epClass += states.stream().map(s -> generateRegister(this.proto, this.self, s)).collect(Collectors.joining("\n")); + /*epClass += "public void register(State s, Function h) {\n"; + epClass += "this.outputs.put(s, h)"; + epClass += "}\n"; + epClass += "\n"; + epClass += "public void register(State s, Function h) {\n"; + epClass += "this.outputs.put(s, h)"; + epClass += "}\n";*/ + + epClass += "@Override\n"; + epClass += "public java.util.concurrent.Future run() throws org.scribble.main.ScribbleRuntimeException {\n"; + epClass += "java.util.Set states = java.util.stream.Stream.of(" + + states.stream().filter(s -> s.getStateKind() != EStateKind.TERMINAL) + .map(s -> SessionApiGenerator.getEndpointApiRootPackageName(this.proto) + ".handlers.states." + this.self + "." + this.proto.getSimpleName() + "_" + this.self + "_" + s.id + ".id") + .collect(Collectors.joining(", ")) + ").collect(java.util.stream.Collectors.toSet());\n"; + epClass += "java.util.Set regd = new java.util.HashSet<>();\n"; + epClass += "regd.addAll(this.inputs.keySet());\n"; + epClass += "regd.addAll(this.outputs.keySet());\n"; + epClass += "if (!states.equals(regd)) {\n"; + epClass += "states.removeAll(regd);\n"; + epClass += "throw new org.scribble.main.ScribbleRuntimeException(\"Missing state registrations: \" + states);\n"; + epClass += "}\n"; + epClass += "return super.run();\n"; + epClass += "}\n"; + + epClass += "}\n"; + + Map res = new HashMap<>(); + String prefix = SessionApiGenerator.getEndpointApiRootPackageName(this.proto).replace('.', '/') + "/handlers/" + this.self + "/"; // StateChannelApiGenerator#generateApi + res.put(prefix + name + ".java", epClass); + + // states + String sprefix = SessionApiGenerator.getEndpointApiRootPackageName(this.proto).replace('.', '/') + "/handlers/states/" + this.self + "/"; // StateChannelApiGenerator#generateApi + for (EState s : states) + { + EStateKind kind = s.getStateKind(); + String stateId = (kind == EStateKind.TERMINAL) ? "End" : name + "_" + s.id; + String stateKind; + switch (kind) + { + case OUTPUT: stateKind = "org.scribble.runtime.handlers.states.ScribOutputState"; break; + case UNARY_RECEIVE: + case POLY_RECIEVE: stateKind = "org.scribble.runtime.handlers.states.ScribInputState"; break; + case TERMINAL: stateKind = "org.scribble.runtime.handlers.states.ScribEndState"; break; + case ACCEPT: + case SERVER_WRAP: + throw new RuntimeException("TODO"); + default: + throw new RuntimeException("TODO"); + } + String stateClass = ""; + stateClass += "package " + pack + ".handlers.states." + this.self + ";\n"; + stateClass += "\n"; + stateClass += "public final class " + stateId + " extends " + stateKind + " {\n"; + stateClass += "public static final " + stateId + " id = new " + stateId + "(" + + ((kind == EStateKind.UNARY_RECEIVE || kind == EStateKind.POLY_RECIEVE) ? SessionApiGenerator.getEndpointApiRootPackageName(this.proto) + ".roles." + s.getDetActions().get(0).peer + "." + s.getDetActions().get(0).peer : "") + + ");\n"; + stateClass += "private " + stateId + "(" + + ((kind == EStateKind.UNARY_RECEIVE || kind == EStateKind.POLY_RECIEVE) ? "org.scribble.type.name.Role peer" : "") + + ") {\n"; + stateClass += ((kind == EStateKind.UNARY_RECEIVE || kind == EStateKind.POLY_RECIEVE) ? "super(\"" + stateId + "\", peer);" : "super(\"" + stateId + "\");") + "\n"; + for (EAction a : s.getActions()) + { + stateClass += "this.succs.put(" + SessionApiGenerator.getEndpointApiRootPackageName(this.proto) + ".ops." + SessionApiGenerator.getOpClassName(a.mid) + "." + SessionApiGenerator.getOpClassName(a.mid) + + ", " + /*+ ((s.getSuccessor(a).id == s.id) + ? "this" + : ((s.getSuccessor(a).getStateKind() == EStateKind.TERMINAL) ? "End" : this.proto.getSimpleName() + "_" + this.self + "_" + s.getSuccessor(a).id) + ".id")*/ + + "\"" + ((s.getDetSuccessor(a).getStateKind() == EStateKind.TERMINAL) ? "End" : this.proto.getSimpleName() + "_" + this.self + "_" + s.getDetSuccessor(a).id) + "\"" + + ");\n"; + } + stateClass += "}\n"; + stateClass += "}\n"; + res.put(sprefix + stateId + ".java", stateClass); + + // messages + if (s.getStateKind() == EStateKind.OUTPUT) + { + String mprefix = SessionApiGenerator.getEndpointApiRootPackageName(this.proto).replace('.', '/') + "/handlers/states/" + this.self + "/messages/"; + + // FIXME: sort cases + // FIXME: generate lattice -- cf. original handler i/f's (with "subtyping") + String messageIfName = name + + //a.peer + "_" + SessionApiGenerator.getOpClassName(a.mid) + a.payload.elems.stream().map(e -> "_" + e).collect(Collectors.joining()); + s.getDetActions().stream().map(a -> "__" + a.peer + "_" + SessionApiGenerator.getOpClassName(a.mid) + a.payload.elems.stream().map(e -> "_" + e).collect(Collectors.joining())).collect(Collectors.joining()); + String messageInterface = ""; + messageInterface += "package " + pack + ".handlers.states." + this.self + ".messages.interfaces;\n"; + messageInterface += "\n"; + messageInterface += "public interface " + messageIfName + " {\n"; + messageInterface += "}\n"; + res.put(mprefix + "interfaces/" + messageIfName + ".java", messageInterface); + + String messageAbstractName = name + "_" + s.id + "_Message"; + String messageAbstract = ""; + messageAbstract += "package " + pack + ".handlers.states." + this.self + ".messages;\n"; + messageAbstract += "\n"; + messageAbstract += "public interface " + messageAbstractName + " extends org.scribble.runtime.handlers.ScribOutputEvent, " + pack + ".handlers.states." + this.self + ".messages.interfaces." + messageIfName + " {\n"; + /*messageAbstract += "private static final long serialVersionUID = 1L;\n"; + messageAbstract += "\n"; + messageAbstract += "public " + messageAbstractName + "(org.scribble.type.name.Role peer, org.scribble.type.name.Op op, Object... payload) {\n"; + messageAbstract += "super(peer, op, payload);\n"; + messageAbstract += "}\n";*/ + messageAbstract += "}\n"; + res.put(mprefix + messageAbstractName + ".java", messageAbstract); + + for (EAction a : s.getActions()) + { + /*String messageIfName = name + "__" + a.peer + "_" + SessionApiGenerator.getOpClassName(a.mid) + a.payload.elems.stream().map(e -> "_" + e).collect(Collectors.joining()); + String messageInterface = ""; + messageInterface += "package " + pack + ".handlers.states." + this.self + ".messages.interfaces;\n"; + messageInterface += "\n"; + messageInterface += "public interface " + messageIfName + " {\n"; + messageInterface += "}\n"; + res.put(mprefix + "interfaces/" + messageIfName + ".java", messageInterface);*/ + + boolean isSig = main.getNonProtoDeclChildren().stream() + .anyMatch(npd -> (npd instanceof SigDecl) + && ((SigDecl) npd).getDeclName().toString() + .equals(a.mid.toString())); + SigDecl msnd = null; + if (isSig) + { + msnd = (SigDecl) main.getNonProtoDeclChildren().stream() + .filter(npd -> (npd instanceof SigDecl) + && ((SigDecl) npd).getDeclName().toString() + .equals(a.mid.toString())) + .iterator().next(); + } + + String messageName; + if (isSig) + { + messageName = name + "_" + SessionApiGenerator.getOpClassName(a.mid); + } + else + { + messageName = name + "_" + s.id + "_" + SessionApiGenerator.getOpClassName(a.mid); + } + String messageClass = ""; + messageClass += "package " + pack + ".handlers.states." + this.self + ".messages;\n"; + messageClass += "\n"; + // extends ScribMessage just for convenience of storing payload (peer/op pre-known) -- instances of this class never "directly" sent, cf., CBEndpoint + messageClass += "public class " + messageName + " extends org.scribble.runtime.message.ScribMessage implements " + messageAbstractName; //+ " implements " + pack + ".handlers.states." + this.self + ".messages.interfaces." + messageIfName; + if (isSig) + { + messageClass += ", org.scribble.runtime.handlers.ScribSigMessage"; + } + messageClass += " {\n"; + //messageClass += "public final java.util.List pay = new java.util.LinkedList<>();\n"; + messageClass += "private static final long serialVersionUID = 1L;\n"; + if (isSig) + { + messageClass += "private final " + msnd.getExtName() + " m;\n"; + } + messageClass += "\n"; + messageClass += "public " + messageName + "(" + SessionApiGenerator.getEndpointApiRootPackageName(this.proto) + ".roles." + a.peer + " peer"; + if (isSig) + { + messageClass += ", " + msnd.getExtName() + " m"; + } + else + { + int i = 1; + for (PayElemType pet : a.payload.elems) + { + DataDecl dtd = main.getTypeDeclChild((DataName) pet); + messageClass += ", " + dtd.getExtName() + " arg" + i++; + } + } + messageClass += ") {\n"; + /*for (int j = 1; j <= a.payload.elems.size(); j++) + { + messageClass += "this.pay.add(arg" + j + ");\n"; + }*/ + messageClass += "super(" + + SessionApiGenerator.getEndpointApiRootPackageName(this.proto) + ".ops." + SessionApiGenerator.getOpClassName(a.mid) + "." + SessionApiGenerator.getOpClassName(a.mid) + + IntStream.rangeClosed(1, a.payload.elems.size()).mapToObj(j -> ", arg" + j).collect(Collectors.joining("")) + ");\n"; + if (isSig) + { + messageClass += "this.m = m;\n"; + } + messageClass += "}\n"; + messageClass += "\n"; + messageClass += "@Override\n"; + messageClass += "public org.scribble.type.name.Role getPeer() {\n"; + messageClass += "return " + + SessionApiGenerator.getEndpointApiRootPackageName(this.proto) + + ".roles." + a.peer + "." + a.peer + ";\n"; + messageClass += "}\n"; + messageClass += "\n"; + messageClass += "@Override\n"; + messageClass += "public org.scribble.type.name.Op getOp() {\n"; + messageClass += "return " + + SessionApiGenerator.getEndpointApiRootPackageName(this.proto) + + ".ops." + SessionApiGenerator.getOpClassName(a.mid) + "." + + SessionApiGenerator.getOpClassName(a.mid) + ";\n"; + messageClass += "}\n"; + messageClass += "\n"; + messageClass += "@Override\n"; + messageClass += "public Object[] getPayload() {\n"; + messageClass += "return this.payload;\n"; + messageClass += "}\n"; + if (isSig) + { + messageClass += "\n"; + messageClass += "@Override\n"; + messageClass += "public org.scribble.runtime.message.ScribMessage getSig() {\n"; + messageClass += "return this.m;\n"; + messageClass += "}\n"; + } + messageClass += "}\n"; + res.put(mprefix + messageName + ".java", messageClass); + } + } + + // branches + if (s.getStateKind() == EStateKind.UNARY_RECEIVE || s.getStateKind() == EStateKind.POLY_RECIEVE) + { + String bprefix = SessionApiGenerator + .getEndpointApiRootPackageName(this.proto).replace('.', '/') + + "/handlers/" + this.self + "/"; + String branchName = name + "_" + s.id + "_Branch"; + String branchAbstract = ""; + branchAbstract += "package " + pack + ".handlers." + this.self + ";\n"; + branchAbstract += ""; + branchAbstract += "public abstract class " + branchName + + " implements org.scribble.runtime.handlers.ScribBranch"; + branchAbstract += s.getActions().stream() + .map(a -> ", " + pack + ".handlers." + this.self + ".interfaces." + + name + "__" + a.peer + "_" + + SessionApiGenerator.getOpClassName(a.mid) + + a.payload.elems.stream().map(e -> "_" + e) + .collect(Collectors.joining()) + + "") + .collect(Collectors.joining("")); + branchAbstract += " {\n"; + /*for (EAction a : s.getAllActions()) + { + // FIXME: factor out + boolean isSig = jc.getMainModule().getNonProtocolDecls().stream() + .anyMatch(npd -> (npd instanceof MessageSigNameDecl) && ((MessageSigNameDecl) npd).getDeclName().toString().equals(a.mid.toString())); + MessageSigNameDecl msnd = null; + if (isSig) + { + msnd = (MessageSigNameDecl) jc.getMainModule().getNonProtocolDecls().stream() + .filter(npd -> (npd instanceof MessageSigNameDecl) && ((MessageSigNameDecl) npd).getDeclName().toString().equals(a.mid.toString())).iterator().next(); + } + + branchInterface += "\npublic abstract void receive(D data, " + SessionApiGenerator.getEndpointApiRootPackageName(this.proto) + ".roles." + a.peer + " peer, "; + if (isSig) + { + branchInterface += msnd.extName + " m"; + } + else + { + branchInterface += SessionApiGenerator.getEndpointApiRootPackageName(this.proto) + ".ops." + SessionApiGenerator.getOpClassName(a.mid) + " op"; + int i = 1; + for (PayloadElemType pet : a.payload.elems) + { + DataTypeDecl dtd = jc.getMainModule().getDataTypeDecl((DataType) pet); + branchInterface += ", " + dtd.extName + " arg" + i++; + } + } + branchInterface += ");\n"; + }*/ + + branchAbstract += "\n"; + branchAbstract += "@Override\n"; + branchAbstract += "public void dispatch(D data, org.scribble.runtime.message.ScribMessage m) {\n"; + branchAbstract += "switch (m.op.toString()) {\n"; + for (EAction a : s.getActions()) + { + String receiveIfName = name + "__" + a.peer + "_" + + SessionApiGenerator.getOpClassName(a.mid) + a.payload.elems + .stream().map(e -> "_" + e).collect(Collectors.joining()); + String receiveInterface = ""; + receiveInterface += "package " + pack + ".handlers." + this.self + ".interfaces;\n"; + receiveInterface += "\n"; + receiveInterface += "public interface " + receiveIfName + " {\n"; + // FIXME: factor out + boolean isSig = main.getNonProtoDeclChildren().stream() + .anyMatch(npd -> (npd instanceof SigDecl) + && ((SigDecl) npd).getDeclName().toString() + .equals(a.mid.toString())); + SigDecl msnd = null; + if (isSig) + { + msnd = (SigDecl) main.getNonProtoDeclChildren().stream() + .filter(npd -> (npd instanceof SigDecl) + && ((SigDecl) npd).getDeclName().toString() + .equals(a.mid.toString())) + .iterator().next(); + } + + receiveInterface += "\npublic void receive(D data, " + + SessionApiGenerator.getEndpointApiRootPackageName(this.proto) + + ".roles." + a.peer + " peer, "; + if (isSig) + { + receiveInterface += msnd.getExtName() + " m"; + } + else + { + receiveInterface += SessionApiGenerator + .getEndpointApiRootPackageName(this.proto) + ".ops." + + SessionApiGenerator.getOpClassName(a.mid) + " op"; + int i = 1; + for (PayElemType pet : a.payload.elems) + { + DataDecl dtd = main.getTypeDeclChild((DataName) pet); + receiveInterface += ", " + dtd.getExtName() + + " arg" + i++; + } + } + receiveInterface += ");\n"; + receiveInterface += "}\n"; + res.put(bprefix + "interfaces/" + receiveIfName + ".java", receiveInterface); + + // FIXME: factor out + /*boolean isSig = jc.getMainModule().getNonProtocolDecls().stream() + .anyMatch(npd -> (npd instanceof MessageSigNameDecl) && ((MessageSigNameDecl) npd).getDeclName().toString().equals(a.mid.toString())); + MessageSigNameDecl msnd = null; + if (isSig) + { + msnd = (MessageSigNameDecl) jc.getMainModule().getNonProtocolDecls().stream() + .filter(npd -> (npd instanceof MessageSigNameDecl) && ((MessageSigNameDecl) npd).getDeclName().toString().equals(a.mid.toString())).iterator().next(); + }*/ + + branchAbstract += "case \"" + + SessionApiGenerator.getOpClassName(a.mid) + "\": receive(data, " + + SessionApiGenerator.getEndpointApiRootPackageName(this.proto) + + ".roles." + a.peer + "." + a.peer + ", "; + if (isSig) + { + branchAbstract += "(" + msnd.getExtName() + ") m"; + } + else + { + branchAbstract += "(" + + SessionApiGenerator.getEndpointApiRootPackageName(this.proto) + + ".ops." + SessionApiGenerator.getOpClassName(a.mid) + + ") m.op"; + } + int i = 0; + for (PayElemType pet : a.payload.elems) + { + DataDecl dtd = main.getTypeDeclChild((DataName) pet); + branchAbstract += ", (" + dtd.getExtName() + ") m.payload[" + i++ + "]"; + } + branchAbstract += "); break;\n"; + } + branchAbstract += "default: throw new RuntimeException(\"Shouldn't get in here: \" + m);\n"; + branchAbstract += "}\n"; + branchAbstract += "}\n"; + branchAbstract += "}\n"; + + res.put(bprefix + branchName + ".java", branchAbstract); + } + } + + /*// SessionApiGenerator#constructOpClasses + Module mod = this.job.getContext().getModule(this.proto.getPrefix()); + GProtocolName simpname = this.proto.getSimpleName(); + GProtocolDecl gpd = (GProtocolDecl) mod.getProtocolDecl(simpname); + MessageIdCollector coll = new MessageIdCollector(this.job, ((ModuleDel) mod.del()).getModuleContext()); + gpd.accept(coll); + for (MessageId mid : coll.getNames()) + { + String messageName = SessionApiGenerator.getOpClassName(mid); + String messageClass = ""; + messageClass += "package " + pack + ".handlers.messages;\n"; + messageClass += "\n"; + messageClass += "public class " + messageName + " {\n"; + messageClass += "public final java.util.List pay = new java.util.LinkedList<>();\n"; + messageClass += "public " + messageName + "(" + + ")"; + messageClass += "}\n"; + res.put(prefix + messageName + ".java", messageClass); + }*/ + + return res; + } + + /*// cf. StateChannelApiGenerator#newSocketClassName + public static String getEDStateEnum(GProtocolName gpn, Role self, EState s) + { + return gpn.getSimpleName() + "_" + self + "_" + s.id; + }*/ + + private String generateRegister(GProtoName gpn, Role self, EState s) + { + String prefix = SessionApiGenerator.getEndpointApiRootPackageName(this.proto) + ".handlers.states." + this.self + "." ; + String res = ""; + String name = gpn.getSimpleName() + "_" + self; + switch (s.getStateKind()) + { + case OUTPUT: + { + // FIXME: "untyped" (ScribEvent) -- need state-specific "enums" + res += "public " + name + " callback(" + prefix + name + "_" + s.id + + " sid, java.util.function.Function h) {\n"; // FIXME: factor out + /*res += "this.outputs.put(sid, h);\n"; + res += "return this;\n";*/ + res += "return icallback(sid, h);\n"; + res += "}\n"; + res += "\n"; + /*for (EAction a : s.getAllActions()) + { + String messageIfName = name + "__" + a.peer + "_" + SessionApiGenerator.getOpClassName(a.mid) + a.payload.elems.stream().map(e -> "_" + e).collect(Collectors.joining()); // FIXME: factor out; + res += "public " + name + " callback(" + prefix + name + "_" + s.id + + " sid, java.util.function.Function h) {\n"; + res += "this.outputs.put(sid, h);\n"; + res += "return this;\n"; + res += "}\n"; + res += "\n"; + }*/ + String messageIfName = name + + s.getDetActions().stream().map(a -> "__" + a.peer + "_" + SessionApiGenerator.getOpClassName(a.mid) + a.payload.elems.stream().map(e -> "_" + e).collect(Collectors.joining())).collect(Collectors.joining()); + res += "public\n" + + "\n" // FIXME: factor out + + name + " icallback(" + prefix + name + "_" + s.id + + " sid, java.util.function.Function h) {\n"; + res += "this.outputs.put(sid, h);\n"; + res += "return this;\n"; + res += "}\n"; + res += "\n"; + break; + } + case UNARY_RECEIVE: + case POLY_RECIEVE: + { + res += "public " + name + " callback(" + prefix + name + "_" + s.id + " sid"; + /*for (EAction a : s.getAllActions()) + { + res += ", org.scribble.util.function.Function2<" + SessionApiGenerator.getEndpointApiRootPackageName(this.proto) + ".ops." + SessionApiGenerator.getOpClassName(a.mid) + + ", Object" + + ", Void> h_" + a.mid; + } + res += "java.util.Map> tmp = this.inputs.get(sid);\n"; + res += "if (tmp == null) {\n"; + res += "tmp = new java.util.HashMap<>();\n"; + res += "this.inputs.put(sid, tmp);\n"; + for (EAction a : s.getAllActions()) + { + res += "tmp.put(" + SessionApiGenerator.getEndpointApiRootPackageName(this.proto) + ".ops." + SessionApiGenerator.getOpClassName(a.mid) + "." + SessionApiGenerator.getOpClassName(a.mid) + ", h_" + a.mid + ");\n"; + } + res += "}\n";*/ + res += ", " + SessionApiGenerator.getEndpointApiRootPackageName(this.proto) + ".handlers." + this.self + "." + name + "_" + s.id + "_Branch b"; + res += ") {\n"; + /*res += "this.inputs.put(sid, b);\n"; + res += "return this;\n";*/ + res += "return icallback(sid, b);\n"; + res += "}\n"; + res += "\n"; + String T = s.getActions().stream().map(a -> SessionApiGenerator.getEndpointApiRootPackageName(this.proto) + ".handlers." + this.self + ".interfaces." + name + "__" + a.peer + "_" + + SessionApiGenerator.getOpClassName(a.mid) + a.payload.elems.stream().map(e -> "_" + e).collect(Collectors.joining("")) + "").collect(Collectors.joining(" & ")) + + " & org.scribble.runtime.handlers.ScribBranch"; + res += "public " + "\n" + + name + " icallback(" + prefix + name + "_" + s.id + + " sid, T" + //+ SessionApiGenerator.getEndpointApiRootPackageName(this.proto) + ".handlers." + this.self + ".interfaces." + receiveIfName + " + + " b) {\n"; // FIXME: factor out + res += "this.inputs.put(sid, b);\n"; + res += "return this;\n"; + res += "}\n"; + res += "\n"; + break; + } + case TERMINAL: + { + break; + } + case ACCEPT: + case SERVER_WRAP: + { + throw new RuntimeException("[scrib] TODO: " + s); + } + default: + { + throw new RuntimeException("[scrib] Shouldn't get in here: " + s); + } + } + return res; + } + + /*public String generateRootPackageDecl() + { + return "package " + getRootPackage(); + } + + private String getRootPackage() // Derives only from proto name + { + //throw new RuntimeException("[param-core] TODO:"); + return this.proto.getSimpleName().toString(); + }*/ + + public String generateScribbleRuntimeImports() + { + return getScribbleRuntimeImports().stream().map(x -> "import \"" + x + "\"\n").collect(Collectors.joining()); + } + + private List getScribbleRuntimeImports() // FIXME: factor up + { + return Stream.of( + //EDApiGenConstants.GO_SCRIBBLERUNTIME_SESSION_PACKAGE + "" + ).collect(Collectors.toList()); + } +} diff --git a/scribble-codegen/src/main/java/org/scribble/codegen/java/callbackapi/CBEndpointApiGenerator3.java b/scribble-codegen/src/main/java/org/scribble/codegen/java/callbackapi/CBEndpointApiGenerator3.java new file mode 100644 index 000000000..cbb17e586 --- /dev/null +++ b/scribble-codegen/src/main/java/org/scribble/codegen/java/callbackapi/CBEndpointApiGenerator3.java @@ -0,0 +1,1027 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.codegen.java.callbackapi; + +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +import org.scribble.ast.DataDecl; +import org.scribble.ast.Module; +import org.scribble.ast.SigDecl; +import org.scribble.codegen.java.sessionapi.SessionApiGenerator; +import org.scribble.codegen.java.util.ClassBuilder; +import org.scribble.codegen.java.util.ConstructorBuilder; +import org.scribble.codegen.java.util.FieldBuilder; +import org.scribble.codegen.java.util.InterfaceBuilder; +import org.scribble.codegen.java.util.MethodBuilder; +import org.scribble.core.job.Core; +import org.scribble.core.job.CoreArgs; +import org.scribble.core.job.CoreContext; +import org.scribble.core.model.endpoint.EState; +import org.scribble.core.model.endpoint.EStateKind; +import org.scribble.core.model.endpoint.actions.EAction; +import org.scribble.core.type.name.DataName; +import org.scribble.core.type.name.GProtoName; +import org.scribble.core.type.name.PayElemType; +import org.scribble.core.type.name.Role; +import org.scribble.core.type.name.SigName; +import org.scribble.job.Job; +import org.scribble.job.JobContext; +import org.scribble.util.ScribException; + +// FIXME: integrate with JEndpointApiGenerator -- this class should correspond to StateChanApiGenerator (relying on the common SessionApiGenerator) +// FIXME: consider collecting up all interfaces as statics inside a container class -- also states? +// FIXME: integrate CB (branch) interfaces with old iointerfacs/callback API +// FIXME: consider also "expanding" nested message constructors by op first? -- and consider "partial constructors" along expansions, can they be parameterised typed? +public class CBEndpointApiGenerator3 +{ + public final Job job; + public final Core core; + public final GProtoName proto; + public final Role self; // FIXME: base endpoint API gen is role-oriented, while session API generator should be neutral + + protected final Map stateNames = new HashMap<>(); + + //private final boolean subtypes; // Generate full hierarchy (states -> states, not just indivdual state -> cases) -- cf. ioifaces + + public CBEndpointApiGenerator3(Job job, GProtoName fullname, Role self, + boolean subtypes) + { + this.job = job; + this.core = job.getCore(); + this.proto = fullname; + this.self = self; + + //this.subtypes = subtypes; + if (subtypes) + { + throw new RuntimeException("TODO: -subtypes"); + } + } + + public Map build() throws ScribException + { + this.stateNames.clear(); + Map res = new HashMap<>(); // filepath -> source + res.putAll(buildSessionApi()); + return res; + } + + // FIXME: factor out -- integrate with JEndpointApiGenerator + public Map buildSessionApi() throws ScribException + { + this.job.verbosePrintln("\n[param-core] Running " + CBEndpointApiGenerator3.class + " for " + this.proto + "@" + this.self); + + Map res = new HashMap<>(); + res.putAll(new SessionApiGenerator(this.job, this.proto).generateApi()); + res.putAll(buildEndpointClass()); + return res; + } + + public Map buildEndpointClass() throws ScribException + { + Module main = this.job.getContext().getMainModule(); + Map res = new HashMap<>(); + + CoreContext jobc2 = this.core.getContext(); + EState init = (this.core.config.args.get(CoreArgs.MIN_EFSM) + ? jobc2.getMinimisedEGraph(this.proto, this.self) + : jobc2.getEGraph(this.proto, this.self) + ).init; + // TODO: factor out with StateChannelApiGenerator constructor + Set states = new HashSet<>(); + states.add(init); + states.addAll(init.getReachableStates()); + + String endpointName = this.proto.getSimpleName() + "_" + this.self; + int i = 1; + for (EState s : states) + { + EStateKind kind = s.getStateKind(); + String stateName = (kind == EStateKind.TERMINAL) ? "End" : endpointName + "_" + i++; + this.stateNames.put(s.id, stateName); + } + + // frontend handler class + String rootPack = SessionApiGenerator.getEndpointApiRootPackageName(this.proto); + String sessClassName = rootPack + "." + this.proto.getSimpleName(); + String prefix = getHandlersSelfPackage().replace('.', '/') + "/"; // StateChannelApiGenerator#generateApi + + String epClass = generateEndpointClass(rootPack, endpointName, sessClassName, init, states); + res.put(prefix + endpointName + ".java", epClass); + + // output-choice message i/f's + Set outputCallbacks = new HashSet<>(); // e.g., Proto1_A__B__1_Int + Set outputChoices = new HashSet<>(); // e.g., Proto1_A__B__1_Int__C__2_Int__C__4_Str, i.e., { B__1_Int, C__2_Int, C__4_Str } + Map>> reg = new HashMap<>(); // e.g., Proto1_A__B__1_Int -> { Proto1_A__B__1_Int__C__2_Int__C__4_Str, ... } + for (EState s : (Iterable) states.stream().filter(x -> x.getStateKind() == EStateKind.OUTPUT)::iterator) + { + List as = s.getActions(); + Set set = as.stream().map(this.getCallbackSuffix).collect(Collectors.toSet()); + for (EAction a : as) + { + String callbackName = + //endpointName + "OCallback_" + this.self // FIXME: factor out // Cf. ICallback, has self (due to message expansion nesting) -- but ScribMessage values of this type don't record self? -- Select i/f's have self in name though + + "__" + this.getCallbackSuffix.apply(a); + outputCallbacks.add(callbackName); + if (set.size() > 1) + { + Set> tmp = reg.get(callbackName); + if (tmp == null) + { + tmp = new HashSet<>(); + reg.put(callbackName, tmp); + } + tmp.add(set); + } + } + if (as.size() > 1) + { + String outputChoiceName = + //endpointName + "Select_" + this.self // FIXME: factor out // Cf. original iointerfaces + + as.stream().sorted(Comparator.comparing(a -> a.toString())) + .map(a -> "__" + this.getCallbackSuffix.apply(a)).collect(Collectors.joining()); + outputChoices.add(outputChoiceName); + } + } + for (String name : outputChoices) // TODO: -subtypes -- full subtyping between outputChoice i/f's + { + InterfaceBuilder outputChoice = new InterfaceBuilder(name); + outputChoice.addModifiers("public"); + String pack = getHandlersSelfPackage() + ".outputs.choices"; // FIXME: factor out + outputChoice.setPackage(pack); + res.put(pack.replace('.', '/') + "/" + name + ".java", outputChoice.build()); + } + for (String name : outputCallbacks) + { + InterfaceBuilder outputCallback = new InterfaceBuilder(name); + outputCallback.addModifiers("public"); + if (reg.containsKey(name)) + { + reg.get(name).forEach(iface -> + outputCallback.addInterfaces(getHandlersSelfPackage() + ".outputs.choices." + //+ endpointName + + "Select_" + this.self // FIXME: factor out + + iface.stream().sorted().map(f -> "__" + f).collect(Collectors.joining())) + ); + } + String pack = getHandlersSelfPackage() + ".outputs"; // FIXME: factor out + outputCallback.setPackage(pack); + res.put(pack.replace('.', '/') + "/" + name + ".java", outputCallback.build()); + } + + // states + String sprefix = getStatesSelfPackage().replace('.', '/') + "/"; // StateChannelApiGenerator#generateApi + for (EState s : states) + { + EStateKind kind = s.getStateKind(); + String stateName = this.stateNames.get(s.id); + String stateClass = generateStateClass(s, rootPack, kind, stateName, endpointName); + res.put(sprefix + stateName + ".java", stateClass); + } + + /*// messages + for (EState s : states) + { + if (s.getStateKind() == EStateKind.OUTPUT) + { + String mprefix = getMessagesPackage(rootPack).replace('.', '/') + "/"; + String messageAbstractName = getMessageAbstractName(endpointName, s); + String messageAbstractClass = generateMessageAbstractClass(messageAbstractName, rootPack, mprefix); + res.put(mprefix + messageAbstractName + ".java", messageAbstractClass); + Map messageClasses = generateMessageClasses(endpointName, s, mprefix, rootPack); + messageClasses.values().forEach(c -> res.put(mprefix + c.getName() + ".java", c.build())); + } + }*/ + + // branches + JobContext jobc = this.job.getContext(); + for (EState s : states) + { + if (s.getStateKind() == EStateKind.UNARY_RECEIVE || s.getStateKind() == EStateKind.POLY_RECIEVE) + { + String bprefix = getHandlersSelfPackage().replace('.', '/') + "/"; + String branchName = this.stateNames.get(s.id) + "_Branch"; + + for (EAction a : s.getActions()) + { + // FIXME: factor out + boolean isSig = main.getNonProtoDeclChildren().stream() + .anyMatch(npd -> (npd instanceof SigDecl) + && ((SigDecl) npd).getDeclName().toString() + .equals(a.mid.toString())); + SigDecl msnd = null; + if (isSig) + { + msnd = (SigDecl) main.getNonProtoDeclChildren().stream() + .filter(npd -> (npd instanceof SigDecl) + && ((SigDecl) npd).getDeclName().toString() + .equals(a.mid.toString())) + .iterator().next(); + } + + String receiveIfName = + //endpointName + "__" + "ICallback__" // CHECKME: confusing against "icallback" + + a.peer + "_" + SessionApiGenerator.getOpClassName(a.mid) + + a.payload.elems.stream().map(e -> "_" + getExtName(e)).collect(Collectors.joining()); // FIXME: factor out + String receiveInterface = generateReceiveInterface(isSig, msnd, jobc, a, rootPack, receiveIfName); + res.put((getHandlersSelfPackage() + ".inputs.").replace('.', '/') + + receiveIfName + ".java", receiveInterface); + } + + String branchAbstract = generateBranch(bprefix, jobc, s, endpointName, + rootPack, branchName); + res.put(bprefix + branchName + ".java", branchAbstract); + } + } + + return res; + } + + protected String generateEndpointClass(String rootPack, String endpointName, String sessClassName, EState init, Set states) + { + String initStateName = getStatesSelfPackage() + "." + this.stateNames.get(init.id);//endpointName + "_" + init.id; // FIXME: factor out + + ClassBuilder endpointClass = new ClassBuilder(endpointName); + endpointClass.setPackage(getHandlersSelfPackage()); + endpointClass.addModifiers("public"); + endpointClass.addParameters("D"); + endpointClass.setSuperClass("org.scribble.runtime.session.CBEndpoint<" + sessClassName + ", " + getRolesPackage() + "." + this.self + ", D>"); + ConstructorBuilder cb = endpointClass.newConstructor(sessClassName + " sess", getRolesPackage() + "." + this.self + " self", "org.scribble.runtime.message.ScribMessageFormatter smf", "D data"); + cb.addModifiers("public"); + cb.addExceptions("java.io.IOException", "org.scribble.main.ScribRuntimeException"); + cb.addBodyLine("super(sess, self, smf, " + initStateName + ".id, data);"); + for (EState s : states) + { + //String tmp = (s.getStateKind() == EStateKind.TERMINAL) ? "End" : this.proto.getSimpleName() + "_" + this.self + "_" + s.id; + String tmp = this.stateNames.get(s.id); + cb.addBodyLine("this.states.put(\"" + tmp + "\", " + getStatesSelfPackage() + "." + tmp + ".id);"); + } + MethodBuilder mb = endpointClass.newMethod("run"); + mb.addModifiers("public"); + mb.setReturn("java.util.concurrent.Future"); + mb.addExceptions("org.scribble.main.ScribRuntimeException"); + mb.addAnnotations("@Override"); + mb.addBodyLine("java.util.Set states = java.util.stream.Stream.of(" + + states.stream().filter(s -> s.getStateKind() != EStateKind.TERMINAL) + .map(s -> getStatesSelfPackage() + "." + this.stateNames.get(s.id) + ".id") + .collect(Collectors.joining(", ")) + ").collect(java.util.stream.Collectors.toSet());\n"); + mb.addBodyLine("java.util.Set regd = new java.util.HashSet<>();"); + mb.addBodyLine("regd.addAll(this.inputs.keySet());"); + mb.addBodyLine("regd.addAll(this.outputs.keySet());"); + mb.addBodyLine("if (!states.equals(regd)) {"); + mb.addBodyLine("states.removeAll(regd);"); + mb.addBodyLine("throw new org.scribble.main.ScribRuntimeException(\"Missing state registrations: \" + states);"); + mb.addBodyLine("}"); + mb.addBodyLine("return super.run();"); + for (EState s : states) + { + if (s.getStateKind() != EStateKind.TERMINAL) + { + generateRegister(endpointClass, endpointName, rootPack, s); + } + } + return endpointClass.build(); + + /*String role = SessionApiGenerator.getRolesPackageName(this.proto) + "." + this.self; + String epClass = ""; + + epClass += "package " + rootPack + ".handlers." + this.self + ";\n"; + epClass += "\n"; + epClass += "\n"; + epClass += "public class " + endpointName + " extends org.scribble.runtime.session.CBEndpoint<" + sess + ", " + role + ", D> {\n"; + + epClass += "public " + endpointName + "(" + sess + " sess, " + role + + " self, org.scribble.runtime.message.ScribMessageFormatter smf, D data) throws java.io.IOException, org.scribble.main.ScribbleRuntimeException {\n"; + epClass += "super(sess, self, smf, " + rootPack + ".handlers.states." + this.self + "." + endpointName + "_" + init.id + ".id" + ", data);\n"; // FIXME: factor out + for (EState s : states) + { + String tmp = (s.getStateKind() == EStateKind.TERMINAL) ? "End" : this.proto.getSimpleName() + "_" + this.self + "_" + s.id; + epClass += "this.states.put(\"" + tmp + "\", " + SessionApiGenerator.getEndpointApiRootPackageName(this.proto) + ".handlers.states." + this.self + "." + tmp + ".id);\n"; + } + epClass += "}\n"; + epClass += "\n"; + + + epClass += states.stream().map(s -> generateRegister(this.proto, this.self, s)).collect(Collectors.joining("\n")); + + epClass += "@Override\n"; + epClass += "public java.util.concurrent.Future run() throws org.scribble.main.ScribbleRuntimeException {\n"; + epClass += "java.util.Set states = java.util.stream.Stream.of(" + states.stream().filter(s -> s.getStateKind() != EStateKind.TERMINAL).map(s -> + SessionApiGenerator.getEndpointApiRootPackageName(this.proto) + ".handlers.states." + this.self + "." + this.proto.getSimpleName() + "_" + this.self + "_" + s.id + ".id").collect(Collectors.joining(", ")) + ").collect(java.util.stream.Collectors.toSet());\n"; + epClass += "java.util.Set regd = new java.util.HashSet<>();\n"; + epClass += "regd.addAll(this.inputs.keySet());\n"; + epClass += "regd.addAll(this.outputs.keySet());\n"; + epClass += "if (!states.equals(regd)) {\n"; + epClass += "states.removeAll(regd);\n"; + epClass += "throw new org.scribble.main.ScribbleRuntimeException(\"Missing state registrations: \" + states);\n"; + epClass += "}\n"; + epClass += "return super.run();\n"; + epClass += "}\n"; + + epClass += "}\n"; + + return epClass;*/ + } + + //private String generateRegister(GProtocolName gpn, Role self, EState s) + protected void generateRegister(ClassBuilder endpointClass, String endpointName, String rootPack, EState s) + { + switch (s.getStateKind()) + { + case OUTPUT: + { + MethodBuilder callback = endpointClass.newMethod("callback"); + callback.addModifiers("public"); + callback.setReturn(endpointName + ""); + callback.addParameters(getStatesSelfPackage() + "." + this.stateNames.get(s.id) + " sid", // FIXME: factor out + "java.util.function.Function cb" + ); + /*callback.addBodyLine("this.outputs.put(sid, cb);"); + callback.addBodyLine("return this;");*/ + callback.addBodyLine("return icallback(sid, cb);"); + + MethodBuilder icallback = endpointClass.newMethod("icallback"); + icallback.addModifiers("public"); + icallback.setReturn(endpointName + ""); + String iface = getHandlersSelfPackage() + + ((s.getActions().size() > 1) ? ".outputs.choices.Select" : ".outputs.OCallback") // FIXME: factor out + //+ endpointName + + "_" + this.self + + s.getActions().stream().sorted(Comparator.comparing(a -> a.toString())) + .map(a -> "__" + this.getCallbackSuffix.apply(a)).collect(Collectors.joining()); // FIXME: factor out + icallback.addTypeParameters("T extends " + iface + " & org.scribble.runtime.handlers.ScribOutputEvent"); + icallback.addParameters(getStatesSelfPackage() + "." + this.stateNames.get(s.id) + " sid", // FIXME: factor out + "java.util.function.Function cb" + ); + icallback.addBodyLine("this.outputs.put(sid, cb);"); + icallback.addBodyLine("return this;"); + + break; + } + case UNARY_RECEIVE: + case POLY_RECIEVE: + { + MethodBuilder callback = endpointClass.newMethod("callback"); + callback.addModifiers("public"); + callback.setReturn(endpointName + ""); + callback.addParameters(getStatesSelfPackage() + "." + this.stateNames.get(s.id) + " sid", + getHandlersSelfPackage() + "." + this.stateNames.get(s.id) + "_Branch b" + ); // FIXME: factor out + /*callback.addBodyLine("this.inputs.put(sid, b);"); + callback.addBodyLine("return this;");*/ + callback.addBodyLine("return icallback(sid, b);"); + + MethodBuilder icallback = endpointClass.newMethod("icallback"); + icallback.addModifiers("public"); + icallback.setReturn(endpointName + ""); + String typepar = s.getActions().stream().map(a -> + getHandlersSelfPackage() + ".inputs." + //+ this.proto.getSimpleName() + "_" + this.self // i.e, endpointName + + "ICallback" // FIXME: factor out + + "__" + a.peer + "_" + SessionApiGenerator.getOpClassName(a.mid) + + a.payload.elems.stream().map(e -> "_" + getExtName(e)).collect(Collectors.joining("")) + "" + ).collect(Collectors.joining(" & ")); + icallback.addTypeParameters("T extends " + typepar + " & org.scribble.runtime.handlers.ScribBranch"); + icallback.addParameters(getStatesSelfPackage() + "." + this.stateNames.get(s.id) + " sid", "T b"); // FIXME: factor out + icallback.addBodyLine("this.inputs.put(sid, b);"); + icallback.addBodyLine("return this;"); + break; + } + case SERVER_WRAP: + case ACCEPT: + { + throw new RuntimeException("TODO: " + s.getStateKind()); + } + case TERMINAL: + default: + { + throw new RuntimeException("Shouldn't get in here: " + s.getStateKind()); + } + } + + /*String prefix = SessionApiGenerator.getEndpointApiRootPackageName(this.proto) + ".handlers.states." + this.self + "." ; + String res = ""; + String name = gpn.getSimpleName() + "_" + self; + switch (s.getStateKind()) + { + case OUTPUT: + { + // FIXME: "untyped" (ScribEvent) -- need state-specific "enums" + res += "public " + name + " callback(" + prefix + name + "_" + s.id + + " sid, java.util.function.Function h) {\n"; // FIXME: factor out + /*res += "this.outputs.put(sid, h);\n"; + res += "return this;\n";* / + res += "return icallback(sid, h);\n"; + res += "}\n"; + res += "\n"; + String messageIfName = name + + s.getActions().stream().map(a -> "__" + a.peer + "_" + SessionApiGenerator.getOpClassName(a.mid) + a.payload.elems.stream().map(e -> "_" + e).collect(Collectors.joining())).collect(Collectors.joining()); + res += "public\n" + + "\n" // FIXME: factor out + + name + " icallback(" + prefix + name + "_" + s.id + + " sid, java.util.function.Function h) {\n"; + res += "this.outputs.put(sid, h);\n"; + res += "return this;\n"; + res += "}\n"; + res += "\n"; + break; + } + case UNARY_INPUT: + case POLY_INPUT: + { + res += "public " + name + " callback(" + prefix + name + "_" + s.id + " sid"; + res += ", " + SessionApiGenerator.getEndpointApiRootPackageName(this.proto) + ".handlers." + this.self + "." + name + "_" + s.id + "_Branch b"; + res += ") {\n"; + res += "return icallback(sid, b);\n"; + res += "}\n"; + res += "\n"; + String T = s.getAllActions().stream().map(a -> SessionApiGenerator.getEndpointApiRootPackageName(this.proto) + ".handlers." + this.self + ".interfaces." + name + "__" + a.peer + "_" + + SessionApiGenerator.getOpClassName(a.mid) + a.payload.elems.stream().map(e -> "_" + e).collect(Collectors.joining("")) + "").collect(Collectors.joining(" & ")) + + " & org.scribble.runtime.handlers.ScribBranch"; + res += "public " + "\n" + + name + " icallback(" + prefix + name + "_" + s.id + + " sid, T" + //+ SessionApiGenerator.getEndpointApiRootPackageName(this.proto) + ".handlers." + this.self + ".interfaces." + receiveIfName + " + + " b) {\n"; // FIXME: factor out + res += "this.inputs.put(sid, b);\n"; + res += "return this;\n"; + res += "}\n"; + res += "\n"; + break; + } + case TERMINAL: + { + break; + } + case ACCEPT: + case WRAP_SERVER: + { + throw new RuntimeException("[scrib] TODO: " + s); + } + default: + { + throw new RuntimeException("[scrib] Shouldn't get in here: " + s); + } + } + return res;*/ + } + + protected String generateStateClass(EState s, String rootPack, EStateKind kind, String stateName, String endpointName) + { + Module main = this.job.getContext().getMainModule(); + + String stateKind; + switch (kind) + { + case OUTPUT: stateKind = "org.scribble.runtime.handlers.states.ScribOutputState"; break; + case UNARY_RECEIVE: + case POLY_RECIEVE: stateKind = "org.scribble.runtime.handlers.states.ScribInputState"; break; + case TERMINAL: stateKind = "org.scribble.runtime.handlers.states.ScribEndState"; break; + case ACCEPT: + case SERVER_WRAP: + throw new RuntimeException("TODO"); + default: + throw new RuntimeException("TODO"); + } + + ClassBuilder stateClass = new ClassBuilder(stateName); + stateClass.setPackage(getStatesSelfPackage()); + stateClass.setSuperClass(stateKind); + stateClass.addModifiers("public", "final"); + FieldBuilder id = stateClass.newField("id"); + id.addModifiers("public", "static", "final"); + id.setType(stateName); + id.setExpression("new " + stateName + "(" + //+ ((kind == EStateKind.UNARY_INPUT || kind == EStateKind.POLY_INPUT) ? getRolesPackage() + "." + this.self + "." + this.self : "") // FIXME: factor out + + ")"); + /*String[] params = (kind == EStateKind.UNARY_INPUT || kind == EStateKind.POLY_INPUT) + ? new String[] { "org.scribble.type.name.Role peer" } : new String[0];*/ + ConstructorBuilder stateCons = stateClass.newConstructor(); + stateCons.addModifiers("private"); + Role peer = (kind == EStateKind.UNARY_RECEIVE || kind == EStateKind.POLY_RECIEVE) ? s.getDetActions().iterator().next().peer : null; + stateCons.addBodyLine("super(\"" + stateName + "\"" + + ((kind == EStateKind.UNARY_RECEIVE || kind == EStateKind.POLY_RECIEVE) ? ", " + getRolesPackage() + "." + peer + "." + peer : "") // FIXME: factor out + + ");"); + for (EAction a : s.getActions()) + { + EState succ = s.getDetSuccessor(a); + stateCons.addBodyLine("this.succs.put(" + getOpsPackage() + "." + SessionApiGenerator.getOpClassName(a.mid) + "." + SessionApiGenerator.getOpClassName(a.mid) // FIXME: factor out + + ", \"" + /*+ ((succ.getStateKind() == EStateKind.TERMINAL) + ? "End" : this.proto.getSimpleName() + "_" + this.self + "_" + succ.id) // FIXME: factor out*/ + + this.stateNames.get(succ.id) + + "\");" + ); + } + + if (s.getStateKind() == EStateKind.OUTPUT) // FIXME: factor out + { + if (s.getDetActions().size() > 0) + { + InterfaceBuilder messageIf = stateClass.newMemberInterface("Message"); // FIXME: factor out + messageIf.addModifiers("public", "static"); + messageIf.addInterfaces("org.scribble.runtime.handlers.ScribOutputEvent"); + String iface = getHandlersSelfPackage() // FIXME: factor out with generateRegister + + ((s.getActions().size() > 1) ? ".outputs.choices.Select" : ".outputs.OCallback") // FIXME: factor out + //+ endpointName + + "_" + this.self + + s.getActions().stream().sorted(Comparator.comparing(a -> a.toString())) + .map(a -> "__" + this.getCallbackSuffix.apply(a)).collect(Collectors.joining()); // FIXME: factor out + messageIf.addInterfaces(iface); + } + s.getActions().stream().map(a -> a.peer).distinct().forEachOrdered(r -> + { + ClassBuilder roleClass = stateClass.newMemberClass(r.toString()); + roleClass.addModifiers("public", "static"); + ConstructorBuilder roleCons = roleClass.newConstructor(); + roleCons.addModifiers("private"); + s.getActions().stream().filter(a -> a.peer.equals(r)) + .forEachOrdered(a -> + { + String opName = SessionApiGenerator.getOpClassName(a.mid); + ClassBuilder opClass = roleClass.newMemberClass(opName); + opClass.addModifiers("public", "static"); + opClass.setSuperClass("org.scribble.runtime.message.ScribMessage"); + opClass.addInterfaces(stateName + ".Message"); // FIXME: factor out + opClass.addInterfaces(getHandlersSelfPackage() + ".outputs." // FIXME: factor out + //+ endpointName + + "OCallback_" + this.self // FIXME: factor out + + "__" + this.getCallbackSuffix.apply(a)); + FieldBuilder svu = opClass.newField("serialVersionUID"); + svu.addModifiers("private", "static", "final"); + svu.setType("long"); + svu.setExpression("1L"); + int[] i = { 0 }; + + // FIXME: factor out + boolean isSig = main.getNonProtoDeclChildren().stream() + .anyMatch(npd -> (npd instanceof SigDecl) && ((SigDecl) npd).getDeclName().toString().equals(a.mid.toString())); + SigDecl msnd = null; + if (isSig) + { + msnd = (SigDecl) main.getNonProtoDeclChildren().stream() + .filter(npd -> (npd instanceof SigDecl) && ((SigDecl) npd).getDeclName().toString().equals(a.mid.toString())).iterator().next(); + FieldBuilder m = opClass.newField("m"); + m.addModifiers("private", "final"); + m.setType(msnd.getExtName()); + } + + ConstructorBuilder opCons; + if (isSig) + { + opCons = opClass.newConstructor(msnd.getExtName() + " m"); + opClass.addInterfaces("org.scribble.runtime.handlers.ScribSigMessage"); + } + else + { + opCons = opClass.newConstructor(a.payload.elems.stream().map(e -> + main.getTypeDeclChild((DataName) e).getExtName() + " arg" + i[0]++ + ).collect(Collectors.joining(", "))); + } + opCons.addModifiers("public"); + opCons.addBodyLine("super(" + getOpsPackage() + "." + opName + "." + opName // CHECKME: different "op types" have same equals/hashCode -- OK? + + IntStream.range(0, a.payload.elems.size()).mapToObj(j -> ", arg" + j).collect(Collectors.joining("")) + + ");"); + if (isSig) + { + opCons.addBodyLine("this.m = m;"); + MethodBuilder getSig = opClass.newMethod("getSig"); + getSig.addModifiers("public"); + getSig.addAnnotations("@Override"); + getSig.setReturn("org.scribble.runtime.message.ScribMessage"); + getSig.addBodyLine("return this.m;"); + } + MethodBuilder getPeer = opClass.newMethod("getPeer"); + getPeer.addModifiers("public"); + getPeer.addAnnotations("@Override"); + getPeer.setReturn("org.scribble.core.type.name.Role"); + getPeer.addBodyLine("return " + getRolesPackage() + "." + a.peer + "." + a.peer + ";"); + MethodBuilder getOp = opClass.newMethod("getOp"); + getOp.addModifiers("public"); + getOp.addAnnotations("@Override"); + getOp.setReturn("org.scribble.core.type.name.Op"); + getOp.addBodyLine("return " + getOpsPackage() + "." + SessionApiGenerator.getOpClassName(a.mid) + "." + SessionApiGenerator.getOpClassName(a.mid) + ";"); + MethodBuilder getPayload = opClass.newMethod("getPayload"); + getPayload.addModifiers("public"); + getPayload.addAnnotations("@Override"); + getPayload.setReturn("Object[]"); + getPayload.addBodyLine("return this.payload;"); + }); + }); + } + + return stateClass.build(); + + /*String stateClass = ""; + stateClass += "package " + rootPack + ".handlers.states." + this.self + ";\n"; + stateClass += "\n"; + stateClass += "public final class " + stateName + " extends " + stateKind + " {\n"; + stateClass += "public static final " + stateName + " id = new " + stateName + "(" + + ((kind == EStateKind.UNARY_INPUT || kind == EStateKind.POLY_INPUT) ? SessionApiGenerator.getEndpointApiRootPackageName(this.proto) + ".roles." + s.getActions().get(0).peer + "." + s.getActions().get(0).peer : "") + + ");\n"; + stateClass += "private " + stateName + "(" + + ((kind == EStateKind.UNARY_INPUT || kind == EStateKind.POLY_INPUT) ? "org.scribble.type.name.Role peer" : "") + + ") {\n"; + stateClass += ((kind == EStateKind.UNARY_INPUT || kind == EStateKind.POLY_INPUT) ? "super(\"" + stateName + "\", peer);" : "super(\"" + stateName + "\");") + "\n"; + for (EAction a : s.getAllActions()) + { + stateClass += "this.succs.put(" + SessionApiGenerator.getEndpointApiRootPackageName(this.proto) + ".ops." + SessionApiGenerator.getOpClassName(a.mid) + "." + SessionApiGenerator.getOpClassName(a.mid) + + ", " + /*+ ((s.getSuccessor(a).id == s.id) + ? "this" + : ((s.getSuccessor(a).getStateKind() == EStateKind.TERMINAL) ? "End" : this.proto.getSimpleName() + "_" + this.self + "_" + s.getSuccessor(a).id) + ".id")* / + + "\"" + ((s.getSuccessor(a).getStateKind() == EStateKind.TERMINAL) ? "End" : this.proto.getSimpleName() + "_" + this.self + "_" + s.getSuccessor(a).id) + "\"" + + ");\n"; + } + stateClass += "}\n"; + stateClass += "}\n"; + + return stateClass;*/ + } + + // FIXME: refactor using TypeBuilder API + protected String generateBranch(String bprefix, JobContext jc, EState s, String endpointName, String rootPack, String branchName) + { + String branchAbstract = ""; + branchAbstract += "package " + getHandlersSelfPackage() + ";\n"; + branchAbstract += ""; + branchAbstract += "public abstract class " + branchName + " implements org.scribble.runtime.handlers.ScribBranch"; + branchAbstract += s.getActions().stream().map(a -> + ", " + getHandlersSelfPackage() + ".inputs." + //+ endpointName + + "ICallback" // FIXME: factor out + + "__" + a.peer + "_" + SessionApiGenerator.getOpClassName(a.mid) + + a.payload.elems.stream().map(e -> "_" + getExtName(e)).collect(Collectors.joining()) + "" // FIXME: factor out + ).collect(Collectors.joining("")); + branchAbstract += " {\n"; + + branchAbstract += "\n"; + branchAbstract += "@Override\n"; + branchAbstract += "public void dispatch(D data, org.scribble.runtime.message.ScribMessage m) {\n"; + branchAbstract += "switch (m.op.toString()) {\n"; + for (EAction a : s.getActions()) + { + // FIXME: factor out + boolean isSig = jc.getMainModule().getNonProtoDeclChildren().stream() + .anyMatch(npd -> (npd instanceof SigDecl) && ((SigDecl) npd).getDeclName().toString().equals(a.mid.toString())); + SigDecl msnd = null; + if (isSig) + { + msnd = (SigDecl) jc.getMainModule().getNonProtoDeclChildren().stream() + .filter(npd -> (npd instanceof SigDecl) && ((SigDecl) npd).getDeclName().toString().equals(a.mid.toString())).iterator().next(); + } + + branchAbstract += "case \"" + SessionApiGenerator.getOpClassName(a.mid) + "\": receive(data, " + SessionApiGenerator.getEndpointApiRootPackageName(this.proto) + ".roles." + a.peer + "." + a.peer + ", "; + if (isSig) + { + branchAbstract += "(" + msnd.getExtName() + ") m"; + } + else + { + branchAbstract += "(" + SessionApiGenerator.getEndpointApiRootPackageName(this.proto) + ".ops." + SessionApiGenerator.getOpClassName(a.mid) + ") m.op"; + } + int i = 0; + for (PayElemType pet : a.payload.elems) + { + DataDecl dtd = jc.getMainModule().getTypeDeclChild((DataName) pet); + branchAbstract += ", (" + dtd.getExtName() + ") m.payload[" + i++ + "]"; + } + branchAbstract += "); break;\n"; + } + branchAbstract += "default: throw new RuntimeException(\"Shouldn't get in here: \" + m);\n"; + branchAbstract += "}\n"; + branchAbstract += "}\n"; + branchAbstract += "}\n"; + + return branchAbstract; + } + + protected String generateReceiveInterface(boolean isSig, + SigDecl msnd, JobContext jc, EAction a, String rootPack, + String receiveIfName) + { + String receiveInterface = ""; + receiveInterface += "package " + getHandlersSelfPackage() + ".inputs;\n"; + receiveInterface += "\n"; + receiveInterface += "public interface " + receiveIfName + " {\n"; // Cf. original callback API, have extra parameter (o/w same) + + // Cf. output-callback i/f, only specifies peer and message (not self) + receiveInterface += "\nvoid receive(D data, " + + SessionApiGenerator.getEndpointApiRootPackageName(this.proto) + + ".roles." + a.peer + " peer, "; + if (isSig) + { + receiveInterface += msnd.getExtName() + " m"; + } + else + { + receiveInterface += SessionApiGenerator + .getEndpointApiRootPackageName(this.proto) + ".ops." + + SessionApiGenerator.getOpClassName(a.mid) + " op"; + int i = 1; + for (PayElemType pet : a.payload.elems) + { + DataDecl dtd = jc.getMainModule().getTypeDeclChild((DataName) pet); + receiveInterface += ", " + dtd.getExtName() + " arg" + i++; + } + } + receiveInterface += ");\n"; + receiveInterface += "}\n"; + + return receiveInterface; + } + + /*String generateMessageAbstractClass(String messageAbstractName, String rootPack, String mprefix) + { + InterfaceBuilder messageAbstract = new InterfaceBuilder( messageAbstractName); + messageAbstract.setPackage(getMessagesPackage(rootPack)); + messageAbstract.addModifiers("public"); + messageAbstract.addInterfaces("org.scribble.runtime.handlers.ScribOutputEvent"); + return messageAbstract.build(); + + /* //String messageIfName, String messageAbstractName, String endpointName, String rootPack, String mprefix) + String messageAbstract = ""; + messageAbstract += "package " + rootPack + ".handlers.states." + this.self + ".messages;\n"; + messageAbstract += "\n"; + messageAbstract += "public interface " + messageAbstractName + " extends org.scribble.runtime.handlers.ScribOutputEvent, " + rootPack + ".handlers.states." + this.self + ".messages.interfaces." + messageIfName + " {\n"; + messageAbstract += "}\n"; + + return messageAbstract;* / + } + + Map generateMessageClasses(String endpointName, EState s, String mprefix, String rootPack) + { + /*String messageIfName = endpointName + + s.getActions().stream().map(a -> "__" + a.peer + "_" + SessionApiGenerator.getOpClassName(a.mid) + a.payload.elems.stream().map(e -> "_" + e).collect(Collectors.joining())).collect(Collectors.joining()); + String messageInterface = generateMessageInterface(s, messageIfName, endpointName, rootPack, mprefix); + res.put(mprefix + "interfaces/" + messageIfName + ".java", messageInterface);* / + + String messageAbstractName = getMessageAbstractName(endpointName, s); // FIXME: is interface -- factor out + //String messageAbstract = generateMessageAbstract(messageIfName, messageAbstractName, endpointName, rootPack, mprefix); + + Module main = this.job.getContext().getMainModule(); + Map messageClasses = new HashMap<>(); // A class per Payload for this state + for (EAction a : s.getAllActions()) + { + /*boolean isSig = jc.getMainModule().getNonProtocolDecls().stream() // FIXME + .anyMatch(npd -> (npd instanceof MessageSigNameDecl) && ((MessageSigNameDecl) npd).getDeclName().toString().equals(a.mid.toString()));* / + + ClassBuilder messageClass; + if (!messageClasses.containsKey(a.payload)) + { + messageClass = generateMessageClass(//isSig, messageName, + s, a, endpointName, rootPack, messageAbstractName); + messageClasses.put(a.payload, messageClass); + } + else + { + messageClass = messageClasses.get(a.payload); + } + + /*String messageName = isSig + ? endpointName + "_" + SessionApiGenerator.getOpClassName(a.mid) + : endpointName + "_" + s.id + "_" + SessionApiGenerator.getOpClassName(a.mid); + String messageClass = generateMessageClass(isSig, messageName, s, a, messageIfName, rootPack, messageAbstractName); + res.put(mprefix + messageName + ".java", messageClass);* / + int[] i = { 2 }; + String[] args = new String[a.payload.elems.size() + 2]; + args[0] = getRolesPackage() + "." + a.peer + " peer"; + args[1] = getOpsPackage() + "." + SessionApiGenerator.getOpClassName(a.mid) + " op"; + a.payload.elems.forEach(e -> args[i[0]++] = main.getDataTypeDecl((DataType) e).getExtName() + " arg" + (i[0]-3)); + ConstructorBuilder ob = messageClass.newConstructor(args); + ob.addModifiers("public"); + ob.addBodyLine("super(op" + IntStream.range(0, a.payload.elems.size()).mapToObj(j -> ", arg" + j).collect(Collectors.joining()) + ");"); + } + return messageClasses; + } + + String generateMessageInterface(EState s, String messageIfName, String endpointName, String rootPack, String mprefix) + { + // FIXME: sort cases + // FIXME: generate lattice -- cf. original handler i/f's (with "subtyping") + String messageInterface = ""; + messageInterface += "package " + rootPack + ".handlers.states." + this.self + ".messages.interfaces;\n"; + messageInterface += "\n"; + messageInterface += "public interface " + messageIfName + " {\n"; + messageInterface += "}\n"; + return messageInterface; + } + + ClassBuilder generateMessageClass(//boolean isSig, String messageName, + EState s, EAction a, String endpointName, String rootPack, String messageAbstractName) + { + Module main = this.job.getContext().getMainModule(); + + ClassBuilder messageClass; + String name = //"Pay_" + + this.self + "_" + s.id + "_" // FIXME: factor out + + (a.payload.elems.isEmpty() + ? "Unit" + : a.payload.elems.stream().map(e -> + { + String extName = main.getDataTypeDecl((DataType) e).getExtName(); + return (extName.indexOf(".") != -1) + ? extName.substring(extName.lastIndexOf(".")+1, extName.length()) + : extName; + }).collect(Collectors.joining("_")) + ); // FIXME: extName sime // Not terminal + messageClass = new ClassBuilder(name); + //messageClasses.put(a.payload, messageClass); + messageClass.setPackage(getMessagesPackage(rootPack)); + messageClass.addModifiers("public"); + messageClass.setSuperClass("org.scribble.runtime.message.ScribMessage"); + messageClass.addInterfaces(messageAbstractName); + MethodBuilder getPeer = messageClass.newMethod("getPeer"); + getPeer.addModifiers("public"); + getPeer.addAnnotations("@Override"); + getPeer.setReturn("org.scribble.type.name.Role"); + getPeer.addBodyLine("return " + getRolesPackage() + "." + a.peer + "." + a.peer + ";"); + MethodBuilder getOp = messageClass.newMethod("getOp"); + getOp.addModifiers("public"); + getOp.addAnnotations("@Override"); + getOp.setReturn("org.scribble.type.name.Op"); + getOp.addBodyLine("return " + getOpsPackage() + "." + SessionApiGenerator.getOpClassName(a.mid) + "." + SessionApiGenerator.getOpClassName(a.mid) + ";"); + MethodBuilder getPayload = messageClass.newMethod("getPayload"); + getPayload.addModifiers("public"); + getPayload.addAnnotations("@Override"); + getPayload.setReturn("Object[]"); + getPayload.addBodyLine("return this.payload;"); + FieldBuilder fb = messageClass.newField("serialVersionUID"); + fb.addModifiers("private", "static", "final"); + fb.setType("long"); + fb.setExpression("1L"); + + return messageClass; + + /*MessageSigNameDecl msnd = null; + if (isSig) + { + msnd = getMessageSigNameDecl((MessageSigName) a.mid); + } + + String messageClass = ""; + messageClass += "package " + getMessagesPackage(rootPack) + ";\n"; + messageClass += "\n"; + // extends ScribMessage just for convenience of storing payload (peer/op pre-known) -- instances of this class never "directly" sent, cf., CBEndpoint + messageClass += "public class " + messageName + " extends org.scribble.runtime.message.ScribMessage implements " + messageAbstractName; + if (isSig) + { + messageClass += ", org.scribble.runtime.handlers.ScribSigMessage"; + } + messageClass += " {\n"; + messageClass += "private static final long serialVersionUID = 1L;\n"; + if (isSig) + { + messageClass += "private final " + msnd.getExtName() + " m;\n"; + } + messageClass += "\n"; + messageClass += "public " + messageName + "(" + SessionApiGenerator.getEndpointApiRootPackageName(this.proto) + ".roles." + a.peer + " peer"; + if (isSig) + { + messageClass += ", " + msnd.getExtName() + " m"; + } + else + { + int i = 1; + Module main = this.job.getContext().getMainModule(); + for (PayloadElemType pet : a.payload.elems) + { + DataTypeDecl dtd = main.getDataTypeDecl((DataType) pet); + messageClass += ", " + dtd.getExtName() + " arg" + i++; + } + } + messageClass += ") {\n"; + messageClass += "super(" + + SessionApiGenerator.getEndpointApiRootPackageName(this.proto) + ".ops." + SessionApiGenerator.getOpClassName(a.mid) + "." + SessionApiGenerator.getOpClassName(a.mid) + + IntStream.rangeClosed(1, a.payload.elems.size()).mapToObj(j -> ", arg" + j).collect(Collectors.joining("")) + ");\n"; + if (isSig) + { + messageClass += "this.m = m;\n"; + } + messageClass += "}\n"; + messageClass += "\n"; + messageClass += "@Override\n"; + messageClass += "public org.scribble.type.name.Role getPeer() {\n"; + messageClass += "return " + SessionApiGenerator.getEndpointApiRootPackageName(this.proto) + ".roles." + a.peer + "." + a.peer + ";\n"; + messageClass += "}\n"; + messageClass += "\n"; + messageClass += "@Override\n"; + messageClass += "public org.scribble.type.name.Op getOp() {\n"; + messageClass += "return " + SessionApiGenerator.getEndpointApiRootPackageName(this.proto) + ".ops." + SessionApiGenerator.getOpClassName(a.mid) + "." + SessionApiGenerator.getOpClassName(a.mid) + ";\n"; + messageClass += "}\n"; + messageClass += "\n"; + messageClass += "@Override\n"; + messageClass += "public Object[] getPayload() {\n"; + messageClass += "return this.payload;\n"; + messageClass += "}\n"; + if (isSig) + { + messageClass += "\n"; + messageClass += "@Override\n"; + messageClass += "public org.scribble.runtime.message.ScribMessage getSig() {\n"; + messageClass += "return this.m;\n"; + messageClass += "}\n"; + } + messageClass += "}\n"; + + return messageClass;* / + }*/ + + protected String getHandlersPackage() + { + return SessionApiGenerator.getEndpointApiRootPackageName(this.proto) + ".callbacks"; + } + + protected String getHandlersSelfPackage() + { + return getHandlersPackage() + "." + this.self; + } + + protected String getStatesSelfPackage() + { + return getHandlersPackage() + "." + this.self + ".states"; + } + + protected String getMessageAbstractName(String endpointName, EState s) + { + //return endpointName + "_" + s.id + "_Message"; + return "Pay_" + this.self + "_" + s.id; + } + + protected String getRolesPackage() + { + return SessionApiGenerator.getEndpointApiRootPackageName(this.proto) + ".roles"; + } + + protected String getOpsPackage() + { + return SessionApiGenerator.getEndpointApiRootPackageName(this.proto) + ".ops"; + } + + protected String getMessagesPackage(String rootPack) + { + return rootPack + ".handlers." + this.self + ".states.messages"; + } + + protected SigDecl getMessageSigNameDecl(SigName mid) + { + return (SigDecl) + this.job.getContext().getMainModule().getNonProtoDeclChildren().stream() // FIXME: main module? + .filter(npd -> (npd instanceof SigDecl) && ((SigDecl) npd).getDeclName().toString().equals(mid.toString())) + .iterator().next(); + } + + //protected final Function, String> getExtName = e -> + protected String getExtName(PayElemType e) + { + String extName = this.job.getContext().getMainModule().getTypeDeclChild((DataName) e).getExtName(); + return (extName.indexOf(".") != -1) + ? extName.substring(extName.lastIndexOf(".")+1, extName.length()) + : extName; + }; + + protected final Function getCallbackSuffix = a -> + a.peer + "_" + SessionApiGenerator.getOpClassName(a.mid) + + a.payload.elems.stream().map(e -> "_" + getExtName(e)).collect(Collectors.joining("")); // FIXME: factor out + + /*public String generateScribbleRuntimeImports() + { + return getScribbleRuntimeImports().stream().map(x -> "import \"" + x + "\"\n").collect(Collectors.joining()); + } + + private List getScribbleRuntimeImports() // FIXME: factor up + { + return Stream.of( + //EDApiGenConstants.GO_SCRIBBLERUNTIME_SESSION_PACKAGE + "" + ).collect(Collectors.toList()); + }*/ +} diff --git a/scribble-codegen/src/main/java/org/scribble/codegen/java/sessionapi/SessionApiGenerator.java b/scribble-codegen/src/main/java/org/scribble/codegen/java/sessionapi/SessionApiGenerator.java new file mode 100644 index 000000000..3969e14d4 --- /dev/null +++ b/scribble-codegen/src/main/java/org/scribble/codegen/java/sessionapi/SessionApiGenerator.java @@ -0,0 +1,296 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.codegen.java.sessionapi; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +import org.scribble.ast.Module; +import org.scribble.ast.global.GProtoDecl; +import org.scribble.codegen.java.ApiGen; +import org.scribble.codegen.java.util.ClassBuilder; +import org.scribble.codegen.java.util.ConstructorBuilder; +import org.scribble.codegen.java.util.FieldBuilder; +import org.scribble.codegen.java.util.JavaBuilder; +import org.scribble.codegen.java.util.MethodBuilder; +import org.scribble.core.lang.global.GProtocol; +import org.scribble.core.type.kind.Global; +import org.scribble.core.type.name.GProtoName; +import org.scribble.core.type.name.MsgId; +import org.scribble.core.type.name.Role; +import org.scribble.core.type.session.global.GSeq; +import org.scribble.core.visit.gather.MessageIdGatherer; +import org.scribble.job.Job; +import org.scribble.util.ScribException; + +public class SessionApiGenerator extends ApiGen +{ + public static final String GPROTOCOLNAME_CLASS = "org.scribble.core.type.name.GProtoName"; + public static final String OP_CLASS = "org.scribble.core.type.name.Op"; + public static final String ROLE_CLASS = "org.scribble.core.type.name.Role"; + public static final String SESSION_CLASS = "org.scribble.runtime.session.Session"; + public static final String SESSIONTYPEFACTORY_CLASS = "org.scribble.core.type.session.STypeFactory"; + + private static final String IMPATH_FIELD = "IMPATH"; + private static final String SOURCE_FIELD = "SOURCE"; + private static final String PROTO_FIELD = "PROTO"; + + private final Set roles = new HashSet<>(); + private final Set> mids = new HashSet<>(); + + private final ClassBuilder cb = new ClassBuilder(); + private final Map classes = new HashMap<>(); // All classes in same package, for protected constructor access + + public SessionApiGenerator(Job job, GProtoName fullname) throws ScribException + { + super(job, fullname); + constructRoleClasses(); + constructOpClasses(); + constructSessionClass(); // Depends on the above two being done first + } + + @Override + public Map generateApi() + { + String simpname = getSessionClassName(this.gpn); + //String path = getPackageName(this.gpn).replace('.', '/') + "/" + simpname + ".java"; + String path = makePath(this.gpn, simpname); + StringBuilder sb = new StringBuilder(this.cb.build()); + //this.roles.values().forEach((cb) -> sb.append("\n\n").append(cb.generate()) ); + //this.mids.values().forEach((cb) -> sb.append("\n\n").append(cb.generate()) ); + Map map = new HashMap<>(); + map.put(path, sb.toString()); + + this.classes.keySet().stream() + .forEachOrdered(n -> map.put(n, this.classes.get(n).build())); + + return map; + } + + private static String makePath(GProtoName gpn, String simpname) + { + return getEndpointApiRootPackageName(gpn).replace('.', '/') + "/" + simpname + ".java"; + } + + /*public Map, String> getOpClasses() + { + return this.mids; + }*/ + + private void constructSessionClass() + { + String packname = getEndpointApiRootPackageName(this.gpn); + String simpname = getSessionClassName(this.gpn); + + this.cb.setName(simpname); + this.cb.setPackage(packname); + this.cb.addImports(/*"java.io.IOException", */"java.util.Arrays", "java.util.Collections", "java.util.LinkedList", "java.util.List"); + //this.cb.addImports("org.scribble.main.ScribbleRuntimeException", "org.scribble.net.session.SessionEndpoint", "org.scribble.net.ScribMessageFormatter"); + this.cb.addImports(ROLE_CLASS); + this.cb.addImports(getRolesPackageName(this.gpn) + ".*"); + if (!this.mids.isEmpty()) + { + this.cb.addImports(getOpsPackageName(this.gpn) + ".*"); + } + this.cb.addModifiers(JavaBuilder.PUBLIC, JavaBuilder.FINAL); + this.cb.setSuperClass(SessionApiGenerator.SESSION_CLASS); + + FieldBuilder fb1 = this.cb.newField(SessionApiGenerator.IMPATH_FIELD); + fb1.setType("List"); + fb1.addModifiers(JavaBuilder.PUBLIC, JavaBuilder.STATIC, JavaBuilder.FINAL); + fb1.setExpression("new LinkedList<>()"); + + FieldBuilder fb2 = this.cb.newField(SessionApiGenerator.SOURCE_FIELD); + fb2.setType("String"); + fb2.addModifiers(JavaBuilder.PUBLIC, JavaBuilder.STATIC, JavaBuilder.FINAL); + fb2.setExpression("\"getSource\""); + + FieldBuilder fb3 = this.cb.newField(SessionApiGenerator.PROTO_FIELD); + fb3.setType(SessionApiGenerator.GPROTOCOLNAME_CLASS); + fb3.addModifiers(JavaBuilder.PUBLIC, JavaBuilder.STATIC, JavaBuilder.FINAL); + fb3.setExpression(SessionApiGenerator.SESSIONTYPEFACTORY_CLASS + + ".parseGlobalProtocolName(\"" + gpn + "\")"); + + this.roles.forEach(r -> addRoleField(this.cb, r)); + this.mids.forEach(mid -> addOpField(this.cb, mid)); + + ConstructorBuilder ctor = this.cb.newConstructor(); + ctor.addModifiers(JavaBuilder.PUBLIC); + //ctor.setName(simpname); // ? + ctor.addBodyLine(JavaBuilder.SUPER + "(" + + simpname + "." + SessionApiGenerator.IMPATH_FIELD + ", " + + simpname + "." + SessionApiGenerator.SOURCE_FIELD + ", " + + simpname + "." + SessionApiGenerator.PROTO_FIELD + ");"); + + FieldBuilder fb4 = this.cb.newField("ROLES"); + fb4.setType("List"); + fb4.addModifiers(JavaBuilder.PUBLIC, JavaBuilder.STATIC, JavaBuilder.FINAL); + String roles = "Collections.unmodifiableList(Arrays.asList(new Role[] {"; + roles += this.roles.stream().map((r) -> r.toString()).collect(Collectors.joining(", ")); + roles += "}))"; + fb4.setExpression(roles); + + /*for (Role r : this.roles) + { + String role = getRoleClassName(r); + MethodBuilder mb = this.cb.newMethod("project"); // No: use new on SessionEndpoint directly for Eclipse resource leak warning + mb.addModifiers(ClassBuilder.PUBLIC); + mb.setReturn("SessionEndpoint<" + simpname + ", " + role + ">"); + mb.addParameters(role + " role", "ScribMessageFormatter smf"); + mb.addExceptions("ScribbleRuntimeException", "IOException"); + mb.addBodyLine(ClassBuilder.RETURN + " " + ClassBuilder.SUPER + ".project(role, smf);"); + }*/ + + MethodBuilder mb = this.cb.newMethod("getRoles"); + mb.addAnnotations("@Override"); + mb.addModifiers(JavaBuilder.PUBLIC); + mb.setReturn("List"); + mb.addParameters(); + mb.addBodyLine(JavaBuilder.RETURN + " " + simpname + ".ROLES;"); + } + + private void addRoleField(ClassBuilder cb, Role role) + { + addSingletonConstant(cb, "roles", getRoleClassName(role)); // FIXME: factor out + } + + private void addOpField(ClassBuilder cb, MsgId mid) + { + addSingletonConstant(cb, "ops", getOpClassName(mid)); // FIXME: factor out + } + + private void addSingletonConstant(ClassBuilder cb, String subpack, String type) + { + FieldBuilder fb = cb.newField(type); + fb.setType(type); + fb.addModifiers(JavaBuilder.PUBLIC, JavaBuilder.STATIC, JavaBuilder.FINAL); + //fb.setExpression(ClassBuilder.NEW + " " + type + "()"); + fb.setExpression(getEndpointApiRootPackageName(this.gpn) + "." + subpack + "." + type + "." + type); // Currently requires source Scribble to be in a package that is not the root -- can fix by generating to a subpackage based on Module and/or protocol + } + + private void constructOpClasses() throws ScribException + { + /*Module mod = this.lang.getContext().getModule(this.gpn.getPrefix()); + GProtocolName simpname = this.gpn.getSimpleName(); + GProtocolDecl gpd = (GProtocolDecl) mod.getProtocolDeclChild(simpname); + MessageIdCollector coll = new MessageIdCollector(this.lang, ((ModuleDel) mod.del()).getModuleContext()); + gpd.accept(coll); + for (MessageId mid : coll.getNames())*/ + GProtocol inlined = this.core.getContext().getInlined(this.gpn); + for (MsgId mid : inlined.def + .gather(new MessageIdGatherer()::visit) + .collect(Collectors.toList())) + { + //constructOpClass(this.cb.newClass(), mid); + //constructOpClass(new ClassBuilder(), getEndpointApiRootPackageName(this.gpn), mid); + constructOpClass(new ClassBuilder(), getOpsPackageName(this.gpn), mid); + this.mids.add(mid); + } + } + + private void constructRoleClasses() throws ScribException + { + Module mod = this.job.getContext().getModule(this.gpn.getPrefix()); + GProtoName simpname = this.gpn.getSimpleName(); + GProtoDecl gpd = (GProtoDecl) mod.getGProtocolDeclChild(simpname); + for (Role r : gpd.getRoles()) + { + //constructRoleClass(this.cb.newClass(), r); + //constructRoleClass(new ClassBuilder(), getEndpointApiRootPackageName(this.gpn), r); + constructRoleClass(new ClassBuilder(), getRolesPackageName(this.gpn), r); + this.roles.add(r); + } + } + + private ClassBuilder constructRoleClass(ClassBuilder cb, String pack, Role r) + { + return constructSingletonClass(cb, pack, SessionApiGenerator.ROLE_CLASS, getRoleClassName(r)); + } + + private ClassBuilder constructOpClass(ClassBuilder cb, String pack, MsgId mid) + { + return constructSingletonClass(cb, pack, SessionApiGenerator.OP_CLASS, getOpClassName(mid)); + } + + private ClassBuilder constructSingletonClass(ClassBuilder cb, String pack, String superc, String type) + { + cb.setName(type); + cb.addModifiers(JavaBuilder.PUBLIC, JavaBuilder.FINAL); + cb.setPackage(pack); + cb.setSuperClass(superc); + + FieldBuilder fb = cb.newField("serialVersionUID"); + fb.addModifiers(JavaBuilder.PRIVATE, JavaBuilder.STATIC, JavaBuilder.FINAL); + fb.setType("long"); + fb.setExpression("1L"); + + FieldBuilder fb2 = cb.newField(type); + fb2.addModifiers(JavaBuilder.PUBLIC, JavaBuilder.STATIC, JavaBuilder.FINAL); + fb2.setType(type); + fb2.setExpression(JavaBuilder.NEW + " " + type + "()"); + + ConstructorBuilder mb = cb.newConstructor(); + mb.addModifiers(JavaBuilder.PRIVATE); + mb.addBodyLine(JavaBuilder.SUPER + "(\"" + type + "\");"); + + this.classes.put(pack.replace('.', '/') + "/" + type + ".java", cb); + return cb; + } + + // Returns the simple Session Class name + public static String getSessionClassName(GProtoName gpn) + { + return gpn.getSimpleName().toString(); + } + + // Returns the Java output package: currently the Scribble package excluding the Module + public static String getEndpointApiRootPackageName(GProtoName gpn) + { + //return gpn.getPrefix().getPrefix().toString(); // Java output package name (not Scribble package) + // FIXME: factor out with StateChannelApiGenerator.generateClasses + //return gpn.getPrefix().getPrefix().toString() + "." + gpn.getSimpleName(); // Java output package name (not Scribble package) + return gpn.toString(); + } + + public static String getRolesPackageName(GProtoName gpn) + { + return getEndpointApiRootPackageName(gpn) + ".roles"; + } + + public static String getOpsPackageName(GProtoName gpn) + { + return getEndpointApiRootPackageName(gpn) + ".ops"; + } + + public static String getStateChannelPackageName(GProtoName gpn, Role self) + { + return getEndpointApiRootPackageName(gpn) + ".statechans." + self; + } + + // Returns the simple Role Class name + public static String getRoleClassName(Role r) + { + return r.toString(); + } + + // Returns the simple Op Class name: names starting with a digit are prefixed by '_' + public static String getOpClassName(MsgId mid) + { + String s = mid.toString(); + return (s.isEmpty() || s.charAt(0) < 65) ? "_" + s : s; // Hacky? + } +} diff --git a/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/AcceptSockGen.java b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/AcceptSockGen.java new file mode 100644 index 000000000..b05af6f76 --- /dev/null +++ b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/AcceptSockGen.java @@ -0,0 +1,84 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.codegen.java.statechanapi; + +import java.util.List; + +import org.scribble.codegen.java.sessionapi.SessionApiGenerator; +import org.scribble.codegen.java.util.JavaBuilder; +import org.scribble.codegen.java.util.MethodBuilder; +import org.scribble.core.model.endpoint.EState; +import org.scribble.core.model.endpoint.actions.EAction; + +public class AcceptSockGen extends ScribSockGen +{ + public AcceptSockGen(StateChannelApiGenerator apigen, EState curr) + { + super(apigen, curr); + } + + @Override + protected String getSuperClassType() + { + return ACCEPTSOCKET_CLASS + "<" + getSessionClassName() + ", " + getSelfClassName() + ">"; + } + + @Override + protected void addImports() + { + super.addImports(); + //this.cb.addImports(getOpsPackageName() + ".*"); + } + + @Override + protected void addMethods() + { + //Set as = curr.getActions(); + List as = curr.getDetActions(); + if (as.size() > 1) + { + throw new RuntimeException("AcceptSocket generation not yet supported for accept-branches: " + as); + } + EAction a = as.iterator().next(); + EState succ = curr.getDetSuccessor(a); + makeAcceptMethod(a, succ); + } + + private void makeAcceptMethod(EAction a, EState succ) + { + MethodBuilder mb = makeAcceptHeader(a, succ); + mb.addBodyLine(JavaBuilder.SUPER + ".accept(ss, " + getSessionApiRoleConstant(a.obj) + ");"); + addReturnNextSocket(mb, succ); + } + + private MethodBuilder makeAcceptHeader(EAction a, EState succ) + { + MethodBuilder mb = this.cb.newMethod(); + setAcceptHeaderWithoutReturnType(this.apigen, a, mb); + setNextSocketReturnType(this.apigen, mb, succ); + return mb; + } + + // Doesn't include return type + //public static void makeReceiveHeader(StateChannelApiGenerator apigen, IOAction a, EndpointState succ, MethodBuilder mb) + public static void setAcceptHeaderWithoutReturnType(StateChannelApiGenerator apigen, EAction a, MethodBuilder mb) + { + final String ROLE_PARAM = "role"; + + mb.setName("accept"); + mb.addModifiers(JavaBuilder.PUBLIC); + mb.addExceptions(StateChannelApiGenerator.SCRIBBLERUNTIMEEXCEPTION_CLASS, "java.io.IOException"); + mb.addParameters(SessionApiGenerator.getRoleClassName(a.obj) + " " + ROLE_PARAM, SCRIBSERVERSOCKET_CLASS + " ss"); + } +} diff --git a/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/AuxStateChanTypeGen.java b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/AuxStateChanTypeGen.java new file mode 100644 index 000000000..8cad5b6d5 --- /dev/null +++ b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/AuxStateChanTypeGen.java @@ -0,0 +1,28 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.codegen.java.statechanapi; + +import org.scribble.codegen.java.util.TypeBuilder; + +// An auxiliary class builder: supplemental to the class being built via the parent ClassBuilder +public abstract class AuxStateChanTypeGen extends StateChanTypeGen +{ + protected final TypeBuilder parent; + + public AuxStateChanTypeGen(StateChannelApiGenerator apigen, TypeBuilder parent) + { + super(apigen); + this.parent = parent; + } +} diff --git a/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/BranchSockGen.java b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/BranchSockGen.java new file mode 100644 index 000000000..e5f5aa47b --- /dev/null +++ b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/BranchSockGen.java @@ -0,0 +1,405 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.codegen.java.statechanapi; + +import java.util.stream.Collectors; + +import org.scribble.ast.DataDecl; +import org.scribble.ast.SigDecl; +import org.scribble.ast.Module; +import org.scribble.codegen.java.sessionapi.SessionApiGenerator; +import org.scribble.codegen.java.statechanapi.ioifaces.BranchIfaceGen; +import org.scribble.codegen.java.statechanapi.ioifaces.HandleIfaceGen; +import org.scribble.codegen.java.statechanapi.ioifaces.IOStateIfaceGen; +import org.scribble.codegen.java.statechanapi.ioifaces.SuccessorIfaceGen; +import org.scribble.codegen.java.util.ClassBuilder; +import org.scribble.codegen.java.util.EnumBuilder; +import org.scribble.codegen.java.util.JavaBuilder; +import org.scribble.codegen.java.util.MethodBuilder; +import org.scribble.core.model.endpoint.EState; +import org.scribble.core.model.endpoint.actions.EAction; +import org.scribble.core.type.name.DataName; +import org.scribble.core.type.name.SigName; +import org.scribble.core.type.name.PayElemType; +import org.scribble.core.type.name.Role; +import org.scribble.util.ScribException; + +public class BranchSockGen extends ScribSockGen +{ + public BranchSockGen(StateChannelApiGenerator apigen, EState curr) + { + super(apigen, curr); + } + + @Override + protected String getSuperClassType() + { + return BRANCHSOCKET_CLASS + "<" + getSessionClassName() + ", " + getSelfClassName() + ">"; + } + + @Override + protected void addImports() + { + this.cb.addImports("java.io.IOException"); + super.addImports(); + } + + //private void addBranchMethod(ClassBuilder cb, EndpointState curr) + @Override + protected void addMethods() throws ScribException + { + final String ROLE_PARAM = "role"; + final String MESSAGE_VAR = "m"; + final String OPENUM_VAR = "openum"; + final String OP = MESSAGE_VAR + "." + StateChannelApiGenerator.SCRIBMESSAGE_OP_FIELD; + + Module main = this.apigen.getMainModule(); + + //String next = constructCaseClass(curr, main); + ClassBuilder caseclass = new CaseSockGen(this.apigen, this.curr).generateType(); + String next = caseclass.getName(); + String enumClass = getBranchEnumClassName(this.apigen, this.curr); + + //cb.addImports("java.util.concurrent.ExecutionException"); + + //boolean first; + Role peer = this.curr.getDetActions().iterator().next().obj; + + // Branch method + addBranchMethod(ROLE_PARAM, MESSAGE_VAR, OPENUM_VAR, OP, peer, next, enumClass); + + //if (IOInterfacesGenerator.skipIOInterfacesGeneration(apigen.getInitialState())) + if (this.apigen.skipIOInterfacesGeneration) + { + EnumBuilder eb = cb.newMemberEnum(enumClass); + eb.addModifiers(JavaBuilder.PUBLIC); + eb.addInterfaces(OPENUM_INTERFACE); + this.curr.getDetActions().forEach( + a -> eb.addValues(SessionApiGenerator.getOpClassName(a.mid))); + + addDirectBranchCallbackMethod(ROLE_PARAM, MESSAGE_VAR, OP, main, peer); // Hack: callback apigen while i/o i/f's not supported for connect/accept/etc + } + else + { + // Callback methods + String handleif = addBranchCallbackMethod(ROLE_PARAM, peer); + addHandleInterfaceCallbackMethod(ROLE_PARAM, MESSAGE_VAR, OP, main, peer, handleif); + addHandleMethod(ROLE_PARAM, MESSAGE_VAR, OP, main, peer); + } + + this.apigen.addTypeDecl(new HandlerIfaceGen(this.apigen, this.cb, this.curr).generateType()); + } + + private void addBranchMethod(final String ROLE_PARAM, final String MESSAGE_VAR, final String OPENUM_VAR, final String OP, + Role peer, String next, String enumClass) + { + MethodBuilder mb = cb.newMethod("branch"); + mb.setReturn(next); + mb.addParameters(SessionApiGenerator.getRoleClassName(curr.getDetActions().iterator().next().obj) + " " + ROLE_PARAM); + mb.addModifiers(JavaBuilder.PUBLIC); + mb.addExceptions(StateChannelApiGenerator.SCRIBBLERUNTIMEEXCEPTION_CLASS, "IOException", "ClassNotFoundException");//, "ExecutionException", "InterruptedException"); + if (!this.apigen.skipIOInterfacesGeneration) + { + mb.addAnnotations("@Override"); + } + + mb.addBodyLine(StateChannelApiGenerator.SCRIBMESSAGE_CLASS + " " + MESSAGE_VAR + " = " + + JavaBuilder.SUPER + ".readScribMessage(" + getSessionApiRoleConstant(peer) + ");"); + mb.addBodyLine(enumClass + " " + OPENUM_VAR + ";"); + boolean first = true; + for (EAction a : this.curr.getDetActions()) + { + mb.addBodyLine(((first) ? "" : "else ") + "if (" + OP + ".equals(" + getSessionApiOpConstant(a.mid) + ")) {"); + mb.addBodyLine(1, OPENUM_VAR + " = " + + enumClass + "." + SessionApiGenerator.getOpClassName(a.mid) + ";"); + mb.addBodyLine("}"); + first = false; + } + mb.addBodyLine("else {"); + mb.addBodyLine(1, "throw " + JavaBuilder.NEW + " RuntimeException(\"Won't get here: \" + " + OP + ");"); + mb.addBodyLine("}"); + mb.addBodyLine(JavaBuilder.RETURN + " " + + JavaBuilder.NEW + " " + next + "(" + SCRIBSOCKET_SE_FIELD + ", true, " + OPENUM_VAR + ", " + MESSAGE_VAR + ");"); // FIXME: dummy boolean not needed + } + + private String addBranchCallbackMethod(final String ROLE_PARAM, Role peer) + { + boolean first; + String handlerif = HandlerIfaceGen.getHandlerInterfaceName(this.cb.getName()); + String handleif = HandleIfaceGen.getHandleInterfaceName(this.apigen.getSelf(), this.curr); + MethodBuilder mb2 = this.cb.newMethod("branch"); + mb2.addParameters(SessionApiGenerator.getRoleClassName(peer) + " " + ROLE_PARAM); + //mb2.addParameters("java.util.concurrent.Callable<" + ifname + "> branch"); + mb2.addParameters(handlerif + " handler"); + mb2.setReturn(JavaBuilder.VOID); + mb2.addModifiers(JavaBuilder.PUBLIC); + mb2.addExceptions(StateChannelApiGenerator.SCRIBBLERUNTIMEEXCEPTION_CLASS, "IOException", "ClassNotFoundException");//, "ExecutionException", "InterruptedException"); + first = true; + handleif += "<"; + for (EAction a : this.curr.getDetActions().stream().sorted(IOStateIfaceGen.IOACTION_COMPARATOR).collect(Collectors.toList())) + { + if (first) + { + first = false; + } + else + { + handleif += ", "; + } + EState succ = this.curr.getDetSuccessor(a); + if (succ.isTerminal()) + { + handleif += ScribSockGen.GENERATED_ENDSOCKET_NAME; + } + else + { + handleif += this.apigen.getSocketClassName(succ); + } + } + handleif += ">"; + mb2.addBodyLine("branch(role, (" + handleif + ") handler);"); + return handleif; + } + + private void addHandleInterfaceCallbackMethod(final String ROLE_PARAM, + final String MESSAGE_VAR, final String OP, Module main, Role peer, + String handleif) + { + MethodBuilder mb3 = this.cb.newMethod("branch"); + mb3.addParameters(SessionApiGenerator.getRoleClassName(peer) + " " + ROLE_PARAM); + //mb2.addParameters("java.util.concurrent.Callable<" + ifname + "> branch"); + mb3.addParameters(handleif + " handler"); + mb3.setReturn(JavaBuilder.VOID); + mb3.addModifiers(JavaBuilder.PUBLIC); + mb3.addAnnotations("@Override"); + mb3.addExceptions(StateChannelApiGenerator.SCRIBBLERUNTIMEEXCEPTION_CLASS, "IOException", "ClassNotFoundException");//, "ExecutionException", "InterruptedException"); + + addCallbackCases(mb3, ROLE_PARAM, MESSAGE_VAR, OP, main, peer); + + /*boolean first; + mb3.addBodyLine(StateChannelApiGenerator.SCRIBMESSAGE_CLASS + " " + MESSAGE_VAR + " = " + + JavaBuilder.SUPER + ".readScribMessage(" + getSessionApiRoleConstant(peer) + ");"); + first = true; + for (EAction a : this.curr.getActions()) + { + EState succ = this.curr.getSuccessor(a); + if (first) + { + first = false; + } + else + { + mb3.addBodyLine("else"); + } + mb3.addBodyLine("if (" + MESSAGE_VAR + "." + StateChannelApiGenerator.SCRIBMESSAGE_OP_FIELD + ".equals(" + getSessionApiOpConstant(a.mid) + ")) {"); + if (succ.isTerminal()) + { + mb3.addBodyLine(1, SCRIBSOCKET_SE_FIELD + ".setCompleted();"); + } + String ln = "handler.receive("; + //if (!succ.isTerminal()) + { + //FIXME: factor out with addReturn? + ln += JavaBuilder.NEW + " " + (succ.isTerminal() ? ScribSocketGenerator.GENERATED_ENDSOCKET_NAME : this.apigen.getSocketClassName(succ)) + "(" + SCRIBSOCKET_SE_FIELD + ", true), "; + } + ln += getSessionApiOpConstant(a.mid); + + // Based on receive parameters + if (a.mid.isOp()) + { + if (!a.payload.isEmpty()) + { + String buffSuper = JavaBuilder.NEW + " " + BUF_CLASS + "<>("; + int i = 0; + for (PayloadType pt : a.payload.elems) + { + DataTypeDecl dtd = main.getDataTypeDecl((DataType) pt); // TODO: if not DataType + ln += ", " + buffSuper + "(" + dtd.extName + ") " + RECEIVE_MESSAGE_PARAM + "." + SCRIBMESSAGE_PAYLOAD_FIELD + "[" + i++ + "])"; + } + } + } + else + { + MessageSigNameDecl msd = main.getMessageSigDecl(((MessageSigName) a.mid).getSimpleName()); // FIXME: might not belong to main module + ln += ", " + JavaBuilder.NEW + " " + BUF_CLASS + "<>((" + msd.extName + ") " + RECEIVE_MESSAGE_PARAM + "." + SCRIBMESSAGE_PAYLOAD_FIELD + "[0])"; + } + + ln += ");"; + mb3.addBodyLine(1, ln); + mb3.addBodyLine("}"); + } + mb3.addBodyLine("else {"); + mb3.addBodyLine(1, "throw " + JavaBuilder.NEW + " RuntimeException(\"Won't get here: \" + " + OP + ");"); + mb3.addBodyLine("}");*/ + } + + // FIXME: factor out with others (addCallbackCases) + private void addHandleMethod(final String ROLE_PARAM, final String MESSAGE_VAR, final String OP, Module main, Role peer) + { + boolean first; + MethodBuilder mb4 = this.cb.newMethod("handle"); + mb4.addParameters(SessionApiGenerator.getRoleClassName(peer) + " " + ROLE_PARAM); + String tmp = HandleIfaceGen.getHandleInterfaceName(this.apigen.getSelf(), this.curr) + "<"; + tmp += this.curr.getDetActions().stream().sorted(IOStateIfaceGen.IOACTION_COMPARATOR) + .map((a) -> SuccessorIfaceGen.getSuccessorInterfaceName(a)).collect(Collectors.joining(", ")) + ">"; + mb4.addParameters(tmp + " handler"); + mb4.setReturn(JavaBuilder.VOID); + mb4.addModifiers(JavaBuilder.PUBLIC); + mb4.addExceptions(StateChannelApiGenerator.SCRIBBLERUNTIMEEXCEPTION_CLASS, "IOException", "ClassNotFoundException");//, "ExecutionException", "InterruptedException"); + mb4.addAnnotations("@Override"); + mb4.addBodyLine(StateChannelApiGenerator.SCRIBMESSAGE_CLASS + " " + MESSAGE_VAR + " = " + + JavaBuilder.SUPER + ".readScribMessage(" + getSessionApiRoleConstant(peer) + ");"); + first = true; + for (EAction a : this.curr.getDetActions()) + { + EState succ = this.curr.getDetSuccessor(a); + if (first) + { + first = false; + } + else + { + mb4.addBodyLine("else"); + } + mb4.addBodyLine("if (" + MESSAGE_VAR + "." + StateChannelApiGenerator.SCRIBMESSAGE_OP_FIELD + ".equals(" + getSessionApiOpConstant(a.mid) + ")) {"); + if (succ.isTerminal()) + { + mb4.addBodyLine(1, SCRIBSOCKET_SE_FIELD + ".setCompleted();"); + } + String ln = "handler.receive("; + //if (!succ.isTerminal()) + { + //FIXME: factor out with addReturn? + ln += JavaBuilder.NEW + " " + (succ.isTerminal() ? ScribSockGen.GENERATED_ENDSOCKET_NAME : this.apigen.getSocketClassName(succ)) + "(" + SCRIBSOCKET_SE_FIELD + ", true), "; + } + ln += getSessionApiOpConstant(a.mid); + + // Based on receive parameters + if (a.mid.isOp()) + { + if (!a.payload.isEmpty()) + { + String buffSuper = JavaBuilder.NEW + " " + BUF_CLASS + "<>("; + int i = 0; + for (PayElemType pt : a.payload.elems) + { + DataDecl dtd = main.getTypeDeclChild((DataName) pt); // TODO: if not DataType + ln += ", " + buffSuper + "(" + dtd.getExtName() + ") " + RECEIVE_MESSAGE_PARAM + "." + SCRIBMESSAGE_PAYLOAD_FIELD + "[" + i++ + "])"; + } + } + } + else + { + SigDecl msd = main.getSigDeclChild(((SigName) a.mid).getSimpleName()); // FIXME: might not belong to main module + ln += ", " + JavaBuilder.NEW + " " + BUF_CLASS + "<>((" + msd.getExtName() + ") " + RECEIVE_MESSAGE_PARAM + //+ "." + SCRIBMESSAGE_PAYLOAD_FIELD + "[0]" // CHECKME: betty16.lec2.smtp.SmtpC4 + + ")"; + } + + ln += ");"; + mb4.addBodyLine(1, ln); + mb4.addBodyLine("}"); + } + mb4.addBodyLine("else {"); + mb4.addBodyLine(1, "throw " + JavaBuilder.NEW + " RuntimeException(\"Won't get here: \" + " + OP + ");"); + mb4.addBodyLine("}"); + } + + protected static String getBranchEnumClassName(StateChannelApiGenerator apigen, EState curr) + { + //return BranchInterfaceGenerator.getBranchInterfaceEnumName(apigen.getSelf(), curr); + //return (IOInterfacesGenerator.skipIOInterfacesGeneration(apigen.getInitialState())) + return apigen.skipIOInterfacesGeneration + ? apigen.getSocketClassName(curr) + "_Enum" + : BranchIfaceGen.getBranchInterfaceEnumName(apigen.getSelf(), curr); + } + + // branch callback, that doesn't just call handle (cf. addBranchCallbackMethod) -- hack, callback apigen while i/o i/f's not supported for connect/accept/etc + private void addDirectBranchCallbackMethod(final String ROLE_PARAM, + final String MESSAGE_VAR, final String OP, Module main, Role peer) + { + String handlerif = HandlerIfaceGen.getHandlerInterfaceName(this.cb.getName()); + MethodBuilder mb2 = this.cb.newMethod("branch"); + mb2.addParameters(SessionApiGenerator.getRoleClassName(peer) + " " + ROLE_PARAM); + mb2.addParameters(handlerif + " handler"); + mb2.setReturn(JavaBuilder.VOID); + mb2.addModifiers(JavaBuilder.PUBLIC); + mb2.addExceptions(StateChannelApiGenerator.SCRIBBLERUNTIMEEXCEPTION_CLASS, "IOException", "ClassNotFoundException");//, "ExecutionException", "InterruptedException"); + //mb2.addBodyLine("branch(role, (" + handleif + ") handler);"); + + addCallbackCases(mb2, ROLE_PARAM, MESSAGE_VAR, OP, main, peer); + } + + private void addCallbackCases(MethodBuilder mb2, final String ROLE_PARAM, + final String MESSAGE_VAR, final String OP, Module main, Role peer) + { + boolean first; + mb2.addBodyLine(StateChannelApiGenerator.SCRIBMESSAGE_CLASS + " " + MESSAGE_VAR + " = " + + JavaBuilder.SUPER + ".readScribMessage(" + getSessionApiRoleConstant(peer) + ");"); + first = true; + for (EAction a : this.curr.getDetActions()) + { + EState succ = this.curr.getDetSuccessor(a); + if (first) + { + first = false; + } + else + { + mb2.addBodyLine("else"); + } + mb2.addBodyLine("if (" + MESSAGE_VAR + "." + StateChannelApiGenerator.SCRIBMESSAGE_OP_FIELD + ".equals(" + getSessionApiOpConstant(a.mid) + ")) {"); + if (succ.isTerminal()) + { + mb2.addBodyLine(1, SCRIBSOCKET_SE_FIELD + ".setCompleted();"); + } + String ln = "handler.receive("; + //if (!succ.isTerminal()) + { + //FIXME: factor out with addReturn? + ln += JavaBuilder.NEW + " " + (succ.isTerminal() ? ScribSockGen.GENERATED_ENDSOCKET_NAME : this.apigen.getSocketClassName(succ)) + "(" + SCRIBSOCKET_SE_FIELD + ", true), "; + } + ln += getSessionApiOpConstant(a.mid); + + // Based on receive parameters + if (a.mid.isOp()) + { + if (!a.payload.isEmpty()) + { + String buffSuper = JavaBuilder.NEW + " " + BUF_CLASS + "<>("; + int i = 0; + for (PayElemType pt : a.payload.elems) + { + DataDecl dtd = main.getTypeDeclChild((DataName) pt); // TODO: if not DataType + ln += ", " + buffSuper + "(" + dtd.getExtName() + ") " + RECEIVE_MESSAGE_PARAM + "." + SCRIBMESSAGE_PAYLOAD_FIELD + "[" + i++ + "])"; + } + } + } + else + { + SigDecl msd = main.getSigDeclChild(((SigName) a.mid).getSimpleName()); // FIXME: might not belong to main module + ln += ", " + JavaBuilder.NEW + " " + BUF_CLASS + "<>((" + msd.getExtName() + ") " + RECEIVE_MESSAGE_PARAM + //+ "." + SCRIBMESSAGE_PAYLOAD_FIELD + "[0]" // CHECKME: betty16.lec2.smtp.SmtpC4 + + ")"; + } + + ln += ");"; + mb2.addBodyLine(1, ln); + mb2.addBodyLine("}"); + } + mb2.addBodyLine("else {"); + mb2.addBodyLine(1, "throw " + JavaBuilder.NEW + " RuntimeException(\"Won't get here: \" + " + OP + ");"); + mb2.addBodyLine("}"); + } +} diff --git a/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/CaseSockGen.java b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/CaseSockGen.java new file mode 100644 index 000000000..e64c90412 --- /dev/null +++ b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/CaseSockGen.java @@ -0,0 +1,251 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.codegen.java.statechanapi; + +import java.util.stream.Collectors; + +import org.scribble.ast.SigDecl; +import org.scribble.ast.Module; +import org.scribble.codegen.java.sessionapi.SessionApiGenerator; +import org.scribble.codegen.java.statechanapi.ioifaces.BranchIfaceGen; +import org.scribble.codegen.java.statechanapi.ioifaces.IOStateIfaceGen; +import org.scribble.codegen.java.util.ClassBuilder; +import org.scribble.codegen.java.util.FieldBuilder; +import org.scribble.codegen.java.util.JavaBuilder; +import org.scribble.codegen.java.util.MethodBuilder; +import org.scribble.core.model.endpoint.EState; +import org.scribble.core.model.endpoint.actions.EAction; +import org.scribble.core.type.name.DataName; +import org.scribble.core.type.name.SigName; +import org.scribble.core.type.name.Role; +import org.scribble.util.ScribException; + +public class CaseSockGen extends ScribSockGen +{ + public CaseSockGen(StateChannelApiGenerator apigen, EState curr) + { + super(apigen, curr); + } + + @Override + protected String getClassName() + { + return getCaseSocketName(super.getClassName()); + } + + @Override + protected String getSuperClassType() + { + return CASESOCKET_CLASS + "<" + getSessionClassName() + ", " + getSelfClassName() + ">"; + } + + @Override + protected void addImports() + { + super.addImports(); + this.cb.addImports(getOpsPackageName() + ".*"); + } + + @Override + protected void addInitialStateConstructor() + { + return; + } + + @Override + protected MethodBuilder addConstructor() + { + String branchName = this.apigen.getSocketClassName(curr); // Name of "parent" branch class (curr state is the branch state) + String enumClassName = branchName + "." + BranchSockGen.getBranchEnumClassName(this.apigen, this.curr); + + MethodBuilder ctor = super.addConstructor(); + ctor.addParameters(enumClassName + " " + CASE_OP_PARAM, StateChannelApiGenerator.SCRIBMESSAGE_CLASS + " " + CASE_MESSAGE_PARAM); + ctor.addBodyLine(JavaBuilder.THIS + "." + CASE_OP_FIELD + " = " + CASE_OP_PARAM + ";"); + ctor.addBodyLine(JavaBuilder.THIS + "." + CASE_MESSAGE_FIELD + " = " + CASE_MESSAGE_PARAM + ";"); + return ctor; + } + + //private String constructCaseClass(EndpointState curr, Module main) + @Override + protected void addMethods() throws ScribException + { + String branchName = this.apigen.getSocketClassName(curr); // Name of "parent" branch class (curr state is the branch state) + String enumClassName = branchName + "." + BranchSockGen.getBranchEnumClassName(this.apigen, this.curr); + //String className = newClassName(); // Name of branch-receive class + + FieldBuilder fb1 = this.cb.newField(CASE_OP_FIELD); // The op enum, for convenient switch/if/etc by user (correctly derived by code generation from the received ScribMessage) + fb1.addModifiers(JavaBuilder.PUBLIC, JavaBuilder.FINAL); + fb1.setType(enumClassName); + + FieldBuilder fb2 = this.cb.newField(CASE_MESSAGE_FIELD); // The received ScribMessage (branch-check checks the user-selected receive op against the ScribMessage op) + fb2.addModifiers(JavaBuilder.PRIVATE, JavaBuilder.FINAL); + fb2.setType(StateChannelApiGenerator.SCRIBMESSAGE_CLASS); + + for (EAction a : this.curr.getDetActions()) + { + EState succ = this.curr.getDetSuccessor(a); + addReceiveMethod(this.cb, a, succ); + addCaseReceiveMethod(this.cb, a, succ); + if (!a.payload.isEmpty() || a.mid.isSigName()) + { + addCaseReceiveDiscardMethod(this.cb, a, succ); + } + } + + if (!this.apigen.skipIOInterfacesGeneration) + { + Role self = this.apigen.getSelf(); + MethodBuilder mb = this.cb.newMethod("getOp"); + mb.addAnnotations("@Override"); + mb.addModifiers(JavaBuilder.PUBLIC); + mb.setReturn(IOStateIfaceGen.getIOStateInterfaceName(self, this.curr) + "." + BranchIfaceGen.getBranchInterfaceEnumName(self, this.curr)); + mb.addBodyLine(JavaBuilder.RETURN + " " + JavaBuilder.THIS + "." + CASE_OP_FIELD + ";"); + } + + this.apigen.addTypeDecl(this.cb); // CaseSocketBuilder used by BranchSocketBuilder, not EndpointApiGenerator + } + + // Same as in ReceiveSocketGenerator + private MethodBuilder makeReceiveHeader(ClassBuilder cb, EAction a, EState succ) throws ScribException + { + MethodBuilder mb = cb.newMethod(); + ReceiveSockGen.setReceiveHeaderWithoutReturnType(this.apigen, a, mb); + setNextSocketReturnType(this.apigen, mb, succ); + return mb; + } + + private void addReceiveMethod(ClassBuilder cb, EAction a, EState succ) throws ScribException + { + Module main = this.apigen.getMainModule(); + + MethodBuilder mb = makeReceiveHeader(cb, a, succ); + if (a.mid.isOp()) + { + mb.addBodyLine(JavaBuilder.SUPER + ".use();"); + addBranchCheck(getSessionApiOpConstant(a.mid), mb, CASE_MESSAGE_FIELD); + ReceiveSockGen.addPayloadBuffSetters(main, a, mb); + } + else //if (a.mid.isMessageSigName()) + { + SigDecl msd = main.getSigDeclChild(((SigName) a.mid).getSimpleName()); // FIXME: might not belong to main module + mb.addBodyLine(JavaBuilder.SUPER + ".use();"); + addBranchCheck(getSessionApiOpConstant(a.mid), mb, CASE_MESSAGE_FIELD); + mb.addBodyLine(CASE_ARG_PREFIX + "." + BUFF_VAL_FIELD + " = (" + msd.getExtName() + ") " + CASE_MESSAGE_FIELD + ";"); + } + addReturnNextSocket(mb, succ); + } + + private MethodBuilder makeCaseReceiveHeader(ClassBuilder cb, EAction a, EState succ) throws ScribException + { + MethodBuilder mb = cb.newMethod(); + setCaseReceiveHeaderWithoutReturnType(this.apigen, a, mb); + setNextSocketReturnType(this.apigen, mb, succ); + return mb; + } + + private void addCaseReceiveMethod(ClassBuilder cb, EAction a, EState succ) throws ScribException + { + MethodBuilder mb = makeCaseReceiveHeader(cb, a, succ); + String ln = JavaBuilder.RETURN + " " + "receive(" + getSessionApiRoleConstant(a.obj) + ", "; + //ln += mb.getParameters().stream().map((p) -> p.substring(p.indexOf(" ") + 1, p.length())).collect(Collectors.joining(", ")) + ");"; + boolean first = true; + for (String param : mb.getParameters()) + { + if (first) + { + first = false; + } + else + { + ln += ", "; + } + if (param.contains("<")) + { + param = param.substring(param.lastIndexOf('>') + 1, param.length()); + } + ln += param.substring(param.indexOf(" ") + 1, param.length()); + } + mb.addBodyLine(ln + ");"); + } + + private void addCaseReceiveDiscardMethod(ClassBuilder cb, EAction a, EState succ) + { + Module main = this.apigen.getMainModule(); + + MethodBuilder mb = cb.newMethod(); + setCaseReceiveDiscardHeaderWithoutReturnType(this.apigen, a, mb); + setNextSocketReturnType(this.apigen, mb, succ); + + mb.addAnnotations("@SuppressWarnings(\"unchecked\")"); + String ln = JavaBuilder.RETURN + " "; + ln += "receive(" + CASE_OP_PARAM + ", "; + if (a.mid.isOp()) + { + ln += a.payload.elems.stream() + .map((pt) -> getGarbageBuf(main.getTypeDeclChild(((DataName) pt)).getExtName())).collect(Collectors.joining(", ")) + ");"; + } + else + { + SigDecl msd = main.getSigDeclChild(((SigName) a.mid).getSimpleName()); // Factor out? (send/receive/branchreceive/...) + ln += getGarbageBuf(msd.getExtName()) + ");"; + } + mb.addBodyLine(ln); + } + + private static void addBranchCheck(String opClassName, MethodBuilder mb, String messageField) + { + String op = JavaBuilder.THIS + "." + messageField + "." + StateChannelApiGenerator.SCRIBMESSAGE_OP_FIELD; + mb.addBodyLine("if (!" + op + ".equals(" + opClassName + ")) {"); + mb.addBodyLine(1, "throw " + JavaBuilder.NEW + " " + StateChannelApiGenerator.SCRIBBLERUNTIMEEXCEPTION_CLASS + "(\"Wrong branch, received: \" + " + op + ");"); + mb.addBodyLine("}"); + } + + // As for ReceiveSocket, but without peer param + public static void setCaseReceiveHeaderWithoutReturnType(StateChannelApiGenerator apigen, EAction a, MethodBuilder mb) throws ScribException + { + //final String ROLE_PARAM = "role"; + Module main = apigen.getMainModule(); // FIXME: main not necessarily the right module? + String opClass = SessionApiGenerator.getOpClassName(a.mid); + + mb.setName("receive"); + mb.addModifiers(JavaBuilder.PUBLIC); + mb.addParameters(opClass + " " + StateChannelApiGenerator.RECEIVE_OP_PARAM); // More params may be added later (payload-arg/future Buffs) + mb.addExceptions(StateChannelApiGenerator.SCRIBBLERUNTIMEEXCEPTION_CLASS, "java.io.IOException", "ClassNotFoundException");//, "ExecutionException", "InterruptedException"); + if (a.mid.isOp()) + { + ReceiveSockGen.addReceiveOpParams(mb, main, a, true); + } + else //if (a.mid.isMessageSigName()) + { + SigDecl msd = main.getSigDeclChild(((SigName) a.mid).getSimpleName()); // FIXME: might not belong to main module + ReceiveSockGen.addReceiveMessageSigNameParams(mb, msd, true); + } + } + + public static void setCaseReceiveDiscardHeaderWithoutReturnType(StateChannelApiGenerator apigen, EAction a, MethodBuilder mb) + { + // Duplicated from makeCaseReceiveHeader, without parameters + final String opClass = SessionApiGenerator.getOpClassName(a.mid); + + mb.setName("receive"); + mb.addModifiers(JavaBuilder.PUBLIC); + mb.addParameters(opClass + " " + StateChannelApiGenerator.RECEIVE_OP_PARAM); // More params may be added later (payload-arg/future Buffs) + mb.addExceptions(StateChannelApiGenerator.SCRIBBLERUNTIMEEXCEPTION_CLASS, "java.io.IOException", "ClassNotFoundException");//, "ExecutionException", "InterruptedException"); + } + + public static String getCaseSocketName(String branchSocketName) + { + return branchSocketName + "_Cases"; + } +} diff --git a/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/EndSockGen.java b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/EndSockGen.java new file mode 100644 index 000000000..31efe7e2c --- /dev/null +++ b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/EndSockGen.java @@ -0,0 +1,48 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.codegen.java.statechanapi; + +import org.scribble.core.model.endpoint.EState; + +public class EndSockGen extends ScribSockGen +{ + public EndSockGen(StateChannelApiGenerator apigen, EState curr) + { + super(apigen, curr); + } + + @Override + protected String getClassName() + { + return GENERATED_ENDSOCKET_NAME; + } + + @Override + protected String getSuperClassType() + { + return ENDSOCKET_CLASS + "<" + getSessionClassName() + ", " + getSelfClassName() + ">"; + } + + @Override + protected void addImports() + { + super.addImports(); + } + + @Override + protected void addMethods() + { + + } +} diff --git a/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/HandlerIfaceGen.java b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/HandlerIfaceGen.java new file mode 100644 index 000000000..6407e0702 --- /dev/null +++ b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/HandlerIfaceGen.java @@ -0,0 +1,120 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.codegen.java.statechanapi; + +import org.scribble.ast.SigDecl; +import org.scribble.ast.Module; +import org.scribble.codegen.java.sessionapi.SessionApiGenerator; +import org.scribble.codegen.java.util.AbstractMethodBuilder; +import org.scribble.codegen.java.util.ClassBuilder; +import org.scribble.codegen.java.util.InterfaceBuilder; +import org.scribble.codegen.java.util.JavaBuilder; +import org.scribble.codegen.java.util.MethodBuilder; +import org.scribble.core.model.endpoint.EState; +import org.scribble.core.model.endpoint.actions.EAction; +import org.scribble.core.type.name.GProtoName; +import org.scribble.core.type.name.SigName; +import org.scribble.util.ScribException; + +// Factor out +public class HandlerIfaceGen extends AuxStateChanTypeGen +{ + private final EState curr; + + // Pre: cb is the BranchSocketBuilder + public HandlerIfaceGen(StateChannelApiGenerator apigen, ClassBuilder parent, EState curr) + { + super(apigen, parent); + this.curr = curr; + } + + @Override + public InterfaceBuilder generateType() throws ScribException + { + GProtoName gpn = this.apigen.getGProtocolName(); + + // Handler interface + InterfaceBuilder ib = new InterfaceBuilder(); + ib.setPackage(SessionApiGenerator.getStateChannelPackageName(gpn, this.apigen.getSelf())); // FIXME: factor out with ScribSocketBuilder + ib.addImports(SessionApiGenerator.getOpsPackageName(gpn) + ".*"); // FIXME: factor out with ScribSocketBuilder + //ib.setName(getHandlerInterfaceName(parent)); + ib.setName(getHandlerInterfaceName(this.parent.getName())); + ib.addModifiers(InterfaceBuilder.PUBLIC); + + for (EAction a : this.curr.getDetActions()) // Doesn't need to be sorted + { + EState succ = this.curr.getDetSuccessor(a); + String nextClass = this.apigen.getSocketClassName(succ); + + AbstractMethodBuilder mb3 = ib.newAbstractMethod(); + if (!this.apigen.skipIOInterfacesGeneration) + { + mb3.addAnnotations("@Override"); + } + setHandleMethodHeaderWithoutParamTypes(this.apigen, mb3); + if (succ.isTerminal()) + { + mb3.addParameters(ScribSockGen.GENERATED_ENDSOCKET_NAME + " schan"); // FIXME: factor out + } + else + { + mb3.addParameters(nextClass + " schan"); // FIXME: factor out + } + addHandleMethodOpAndPayloadParams(this.apigen, a, mb3); + + if (this.curr.getDetSuccessor(a).isTerminal()) + { + // FIXME: potentially repeated (but OK) + ib.addImports(SessionApiGenerator.getEndpointApiRootPackageName(gpn) + ".*"); // FIXME: factor out with ScribSocketBuilder + ib.addImports(SessionApiGenerator.getRolesPackageName(this.apigen.getGProtocolName()) + ".*"); + } + } + + return ib; + } + + // void return type -- have to deal with Succ as param + public static void setHandleMethodHeaderWithoutParamTypes(StateChannelApiGenerator apigen, MethodBuilder mb) + { + mb.setName("receive"); + mb.addModifiers(JavaBuilder.PUBLIC); + mb.setReturn(InterfaceBuilder.VOID); + mb.addExceptions(StateChannelApiGenerator.SCRIBBLERUNTIMEEXCEPTION_CLASS, "java.io.IOException", "ClassNotFoundException"); + } + + public static void addHandleMethodOpAndPayloadParams(StateChannelApiGenerator apigen, EAction a, MethodBuilder mb) throws ScribException + { + Module main = apigen.getMainModule(); + String opClass = SessionApiGenerator.getOpClassName(a.mid); + + mb.addParameters(opClass + " " + StateChannelApiGenerator.RECEIVE_OP_PARAM); // More params added below + + if (a.mid.isOp()) + { + ReceiveSockGen.addReceiveOpParams(mb, apigen.getMainModule(), a, false); + } + else //if (a.mid.isMessageSigName()) + { + SigDecl msd = main.getSigDeclChild(((SigName) a.mid).getSimpleName()); // FIXME: might not belong to main module + ReceiveSockGen.addReceiveMessageSigNameParams(mb, msd, false); + } + } + + // Pre: cb is the BranchSocketBuilder + //public static String getHandlerInterfaceName(TypeBuilder cb) + public static String getHandlerInterfaceName(String branchName) + { + return branchName + "_Handler"; + } +} diff --git a/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/InputFutureGen.java b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/InputFutureGen.java new file mode 100644 index 000000000..222729a0b --- /dev/null +++ b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/InputFutureGen.java @@ -0,0 +1,141 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.codegen.java.statechanapi; + +import java.util.LinkedList; +import java.util.List; + +import org.scribble.ast.DataDecl; +import org.scribble.ast.SigDecl; +import org.scribble.ast.Module; +import org.scribble.codegen.java.sessionapi.SessionApiGenerator; +import org.scribble.codegen.java.util.ClassBuilder; +import org.scribble.codegen.java.util.ConstructorBuilder; +import org.scribble.codegen.java.util.FieldBuilder; +import org.scribble.codegen.java.util.InterfaceBuilder; +import org.scribble.codegen.java.util.JavaBuilder; +import org.scribble.codegen.java.util.MethodBuilder; +import org.scribble.core.model.endpoint.actions.EAction; +import org.scribble.core.type.name.DataName; +import org.scribble.core.type.name.GProtoName; +import org.scribble.core.type.name.SigName; +import org.scribble.core.type.name.PayElemType; +import org.scribble.util.ScribException; + +public class InputFutureGen extends AuxStateChanTypeGen +{ + protected static final String SCRIBFUTURE_CLASS = "org.scribble.runtime.util.ScribFuture"; + + private final EAction a; + + // Pre: cb is ReceiveSocketBuilder + public InputFutureGen(StateChannelApiGenerator apigen, ClassBuilder parent, EAction a) + { + super(apigen, parent); + this.a = a; + } + + @Override + public ClassBuilder generateType() throws ScribException + { + final String FUTURE_PARAM = "fut"; + Module main = this.apigen.getMainModule(); + GProtoName gpn = this.apigen.getGProtocolName(); + + String futureClass = getInputFutureName(this.parent.getName()); // Fresh enough? need only one future class per receive (unary receive) + + //cb.addImports("java.util.concurrent.CompletableFuture"); // "parent" cb, not the future class + //cb.addImports("java.util.concurrent.ExecutionException"); + + //ClassBuilder future = cb.newClass(); // FIXME: inner class + // Duplicated from BranchInterfaceBuilder -- FIXME: factor out + ClassBuilder future = new ClassBuilder(); + future.setPackage(SessionApiGenerator.getStateChannelPackageName(gpn, this.apigen.getSelf())); // FIXME: factor out with ScribSocketBuilder + future.addImports("java.io.IOException"); + future.addImports("java.util.concurrent.CompletableFuture"); // "parent" cb, not the future class + future.addModifiers(InterfaceBuilder.PUBLIC); + + future.setName(futureClass); + future.setSuperClass(SCRIBFUTURE_CLASS); + List types = new LinkedList<>(); + if (a.mid.isOp()) + { + if (!a.payload.isEmpty()) + { + int i = 1; + for (PayElemType pt : a.payload.elems) + { + if (!pt.isDataName()) + { + throw new ScribException("[TODO] API generation not supported for non- data type payloads: " + pt); + } + DataDecl dtd = main.getTypeDeclChild((DataName) pt); + ScribSockGen.checkJavaDataTypeDecl(dtd); + String type = dtd.getExtName(); + types.add(type); + FieldBuilder f = future.newField("pay" + i++); + f.setType(type); + f.addModifiers(JavaBuilder.PUBLIC); + } + } + } + else + { + SigDecl msd = main.getSigDeclChild(((SigName) a.mid).getSimpleName()); + ScribSockGen.checkMessageSigNameDecl(msd); + String type = msd.getExtName(); + types.add(type); + FieldBuilder f = future.newField("msg"); + f.setType(type); + f.addModifiers(JavaBuilder.PUBLIC); + } + + ConstructorBuilder cons = future.newConstructor("CompletableFuture<" + StateChannelApiGenerator.SCRIBMESSAGE_CLASS + "> " + FUTURE_PARAM); + cons.addModifiers(JavaBuilder.PROTECTED); + cons.addBodyLine(JavaBuilder.SUPER + "(" + FUTURE_PARAM + ");"); + + MethodBuilder sync = future.newMethod("sync"); + sync.addModifiers(JavaBuilder.PUBLIC); + sync.setReturn(futureClass); + //sync.addExceptions("ExecutionException", "InterruptedException"); + sync.addExceptions("IOException"); + String ln = (a.mid.isOp() && a.payload.isEmpty()) ? "" : StateChannelApiGenerator.SCRIBMESSAGE_CLASS + " m = "; + ln += JavaBuilder.SUPER + ".get();"; + sync.addBodyLine(ln); + if (a.mid.isOp()) + { + if (!a.payload.isEmpty()) + { + int i = 1; + for (String type : types) + { + sync.addBodyLine(JavaBuilder.THIS + "." + "pay" + i + " = (" + type + ") m.payload[" + (i - 1) + "];"); + i++; + } + } + } + else + { + sync.addBodyLine(JavaBuilder.THIS + "." + "msg" + " = (" + types.get(0) + ") m;"); + } + sync.addBodyLine(JavaBuilder.RETURN + " " + JavaBuilder.THIS + ";"); + + return future; + } + + public static String getInputFutureName(String parent) + { + return parent + "_Future"; // Fresh enough? need only one future class per receive (unary receive) + } +} diff --git a/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/OutputSockGen.java b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/OutputSockGen.java new file mode 100644 index 000000000..ccd3af9cc --- /dev/null +++ b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/OutputSockGen.java @@ -0,0 +1,239 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.codegen.java.statechanapi; + +import java.util.Iterator; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +import org.scribble.ast.DataDecl; +import org.scribble.ast.SigDecl; +import org.scribble.ast.Module; +import org.scribble.codegen.java.sessionapi.SessionApiGenerator; +import org.scribble.codegen.java.util.JavaBuilder; +import org.scribble.codegen.java.util.MethodBuilder; +import org.scribble.core.model.endpoint.EState; +import org.scribble.core.model.endpoint.actions.EAction; +import org.scribble.core.type.name.DataName; +import org.scribble.core.type.name.SigName; +import org.scribble.core.type.name.PayElemType; +import org.scribble.util.ScribException; + +public class OutputSockGen extends ScribSockGen +{ + public OutputSockGen(StateChannelApiGenerator apigen, EState curr) + { + super(apigen, curr); + } + + @Override + protected String getSuperClassType() + { + return OUTPUTSOCKET_CLASS + "<" + getSessionClassName() + ", " + getSelfClassName() + ">"; + } + + @Override + protected void addImports() + { + this.cb.addImports("java.io.IOException"); + super.addImports(); + } + + // A method for each successor state + //private void addSendMethods(ClassBuilder cb, EndpointState curr) + @Override + protected void addMethods() throws ScribException + { + final String ROLE_PARAM = "role"; + + // Mixed sends and connects + boolean hasConnect = false; + boolean hasWrap = false; + for (EAction a : curr.getDetActions()) // (Scribble ensures all "a" are input or all are output) + { + EState succ = curr.getDetSuccessor(a); + + MethodBuilder mb = this.cb.newMethod(); + if (a.isSend()) + { + setSendHeaderWithoutReturnType(apigen, a, mb); + } + else if (a.isRequest()) + { + hasConnect = true; + setConnectHeaderWithoutReturnType(apigen, a, mb); + } + else if (a.isDisconnect()) + { + setDisconnectHeaderWithoutReturnType(apigen, a, mb); + } + else if (a.isClientWrap()) + { + hasWrap = true; + setWrapClientHeaderWithoutReturnType(apigen, a, mb); + } + else + { + throw new RuntimeException("[TODO] OutputSocket API generation for: " + a); + } + + setNextSocketReturnType(this.apigen, mb, succ); + if (a.mid.isOp()) + { + this.cb.addImports(getOpsPackageName() + ".*"); // FIXME: repeated + } + + if (a.isSend()) + { + if (a.mid.isOp()) + { + List args = getSendPayloadArgs(a); + String body = JavaBuilder.SUPER + ".writeScribMessage(" + ROLE_PARAM + ", " + getSessionApiOpConstant(a.mid); + if (!a.payload.isEmpty()) + { + body += ", " + args.stream().collect(Collectors.joining(", ")); + } + body += ");\n"; + mb.addBodyLine(body); + } + else //if (a.mid.isMessageSigName()) + { + final String MESSAGE_PARAM = "m"; // FIXME: factor out + + mb.addBodyLine(JavaBuilder.SUPER + ".writeScribMessage(" + ROLE_PARAM + ", " + MESSAGE_PARAM + ");"); + } + } + else if (a.isRequest()) + { + //throw new RuntimeException("Shouldn't get in here: " + a); + mb.addBodyLine(JavaBuilder.SUPER + ".connect(" + ROLE_PARAM + ", cons, host, port);\n"); + } + else if (a.isDisconnect()) + { + mb.addBodyLine(JavaBuilder.SUPER + ".disconnect(" + ROLE_PARAM + ");\n"); + } + else if (a.isClientWrap()) + { + mb.addBodyLine(JavaBuilder.SUPER + ".wrapClient(" + ROLE_PARAM + ", wrapper);\n"); + } + else + { + throw new RuntimeException("Shouldn't get in here: " + a); + } + + addReturnNextSocket(mb, succ); + } + + if (hasConnect) + { + this.cb.addImports("java.util.concurrent.Callable"); + this.cb.addImports("org.scribble.runtime.net.BinaryChannelEndpoint"); + } + if (hasWrap) + { + this.cb.addImports("java.util.concurrent.Callable"); + this.cb.addImports("org.scribble.runtime.net.BinaryChannelWrapper"); + } + } + + private static List getSendPayloadArgs(EAction a) + { + final String ARG_PREFIX = "arg"; + + return IntStream.range(0, a.payload.elems.size()).mapToObj((i) -> ARG_PREFIX + i++).collect(Collectors.toList()); // FIXME: factor out with params + } + + public static void setSendHeaderWithoutReturnType(StateChannelApiGenerator apigen, EAction a, MethodBuilder mb) throws ScribException + { + final String ROLE_PARAM = "role"; + Module main = apigen.getMainModule(); // FIXME: main not necessarily the right module? + + mb.setName("send"); + mb.addModifiers(JavaBuilder.PUBLIC); + mb.addExceptions(StateChannelApiGenerator.SCRIBBLERUNTIMEEXCEPTION_CLASS, "IOException"); + mb.addParameters(SessionApiGenerator.getRoleClassName(a.obj) + " " + ROLE_PARAM); // More params added below + if (a.mid.isOp()) + { + addSendOpParams(apigen, mb, main, a); + } + else //if (a.mid.isMessageSigName()) + { + SigDecl msd = main.getSigDeclChild(((SigName) a.mid).getSimpleName()); // FIXME: might not belong to main module + addSendMessageSigNameParams(mb, msd); + } + } + + public static void setConnectHeaderWithoutReturnType(StateChannelApiGenerator apigen, EAction a, MethodBuilder mb) + { + final String ROLE_PARAM = "role"; + + mb.setName("request"); + mb.addModifiers(JavaBuilder.PUBLIC); + mb.addExceptions(StateChannelApiGenerator.SCRIBBLERUNTIMEEXCEPTION_CLASS, "IOException"); + mb.addParameters(SessionApiGenerator.getRoleClassName(a.obj) + " " + ROLE_PARAM); // More params added below + mb.addParameters("Callable cons"); + mb.addParameters("String host"); + mb.addParameters("int port"); + } + + public static void setDisconnectHeaderWithoutReturnType(StateChannelApiGenerator apigen, EAction a, MethodBuilder mb) + { + final String ROLE_PARAM = "role"; + + mb.setName("disconnect"); + mb.addModifiers(JavaBuilder.PUBLIC); + mb.addExceptions(StateChannelApiGenerator.SCRIBBLERUNTIMEEXCEPTION_CLASS, "IOException"); + mb.addParameters(SessionApiGenerator.getRoleClassName(a.obj) + " " + ROLE_PARAM); + } + + public static void setWrapClientHeaderWithoutReturnType(StateChannelApiGenerator apigen, EAction a, MethodBuilder mb) + { + final String ROLE_PARAM = "role"; + + mb.setName("wrapClient"); + mb.addModifiers(JavaBuilder.PUBLIC); + mb.addExceptions(StateChannelApiGenerator.SCRIBBLERUNTIMEEXCEPTION_CLASS, "IOException"); + mb.addParameters(SessionApiGenerator.getRoleClassName(a.obj) + " " + ROLE_PARAM); + mb.addParameters("Callable wrapper"); + } + + protected static void addSendOpParams(StateChannelApiGenerator apigen, MethodBuilder mb, Module main, EAction a) throws ScribException + { + List args = getSendPayloadArgs(a); + mb.addParameters(SessionApiGenerator.getOpClassName(a.mid) + " op"); // opClass -- op param not actually used in body + if (!a.payload.isEmpty()) + { + Iterator as = args.iterator(); + for (PayElemType pt : a.payload.elems) + { + if (!pt.isDataName()) + { + throw new ScribException("[TODO] API generation not supported for non- data type payloads: " + pt); + } + DataDecl dtd = main.getTypeDeclChild((DataName) pt); // FIXME: might not belong to main module // TODO: if not DataType + ScribSockGen.checkJavaDataTypeDecl(dtd); + mb.addParameters(dtd.getExtName() + " " + as.next()); + } + } + } + + protected static void addSendMessageSigNameParams(MethodBuilder mb, SigDecl msd) throws ScribException + { + final String MESSAGE_PARAM = "m"; + + ScribSockGen.checkMessageSigNameDecl(msd); + mb.addParameters(msd.getExtName() + " " + MESSAGE_PARAM); + } +} diff --git a/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/ReceiveSockGen.java b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/ReceiveSockGen.java new file mode 100644 index 000000000..19273b0ac --- /dev/null +++ b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/ReceiveSockGen.java @@ -0,0 +1,227 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.codegen.java.statechanapi; + +import org.scribble.ast.DataDecl; +import org.scribble.ast.SigDecl; +import org.scribble.ast.Module; +import org.scribble.codegen.java.sessionapi.SessionApiGenerator; +import org.scribble.codegen.java.util.ClassBuilder; +import org.scribble.codegen.java.util.JavaBuilder; +import org.scribble.codegen.java.util.MethodBuilder; +import org.scribble.core.model.endpoint.EState; +import org.scribble.core.model.endpoint.actions.EAction; +import org.scribble.core.type.name.DataName; +import org.scribble.core.type.name.SigName; +import org.scribble.core.type.name.PayElemType; +import org.scribble.util.ScribException; + +public class ReceiveSockGen extends ScribSockGen +{ + public ReceiveSockGen(StateChannelApiGenerator apigen, EState curr) + { + super(apigen, curr); + } + + @Override + protected String getSuperClassType() + { + return RECEIVESOCKET_CLASS + "<" + getSessionClassName() + ", " + getSelfClassName() + ">"; + } + + @Override + protected void addImports() + { + super.addImports(); + this.cb.addImports(getOpsPackageName() + ".*"); + } + + // Single receive (unary branch -- singleton next state) + // But generates a set of methods related to this input (regular receive, async with future, async with discard, arrived polling) -- TODO: call-back + // FIXME: most general async would also allow whole input-only compound statements (choice, recursion) to be bypassed + //private void addReceiveMethods(ClassBuilder cb, EndpointState curr) + @Override + protected void addMethods() throws ScribException + { + EAction a = curr.getDetActions().iterator().next(); + //String nextClass = this.apigen.getSocketClassName(curr.accept(a)); + EState succ = curr.getDetSuccessor(a); + ClassBuilder futureClass = new InputFutureGen(this.apigen, this.cb, a).generateType(); // Wraps all payload elements as fields (set by future completion) + // FIXME: problem if package and protocol have the same name -- still? + this.apigen.addTypeDecl(futureClass); + + makeReceiveMethod(a, succ); // [nextClass] receive([opClass] op, Buff arg, ...) + makeAsyncMethod(a, succ, futureClass.getName()); // [nextClass] async([opClass] op, Buff arg) + makeIsDoneMethod(a); // boolean isDone() + makeAsyncDiscardMethod(a, succ, futureClass.getName()); // [nextClass] async([opClass] op) + } + + // [nextClass] receive([opClass] op, Buf arg, ...) + //private void makeReceiveMethod(ClassBuilder cb, Module main, IOAction a, String nextClass, String opClass) + private void makeReceiveMethod(EAction a, EState succ) throws ScribException + { + Module main = this.apigen.getMainModule(); // FIXME: main not necessarily the right module? + + MethodBuilder mb = makeReceiveHeader(a, succ); + if (a.mid.isOp()) + { + //addReceiveOpParams(mb, main, a); + String ln = a.payload.isEmpty() ? "" : StateChannelApiGenerator.SCRIBMESSAGE_CLASS + " " + RECEIVE_MESSAGE_PARAM + " = "; + ln += JavaBuilder.SUPER + ".readScribMessage(" + getSessionApiRoleConstant(a.obj) + ");"; + mb.addBodyLine(ln); + addPayloadBuffSetters(main, a, mb); + } + else //if (a.mid.isMessageSigName()) + { + SigDecl msd = main.getSigDeclChild(((SigName) a.mid).getSimpleName()); // FIXME: might not belong to main module + //addReceiveMessageSigNameParams(mb, a, msd);*/ + mb.addBodyLine(StateChannelApiGenerator.SCRIBMESSAGE_CLASS + " " + RECEIVE_MESSAGE_PARAM + " = " + + JavaBuilder.SUPER + ".readScribMessage(" + getSessionApiRoleConstant(a.obj) + ");"); + mb.addBodyLine(RECEIVE_ARG_PREFIX + "." + BUFF_VAL_FIELD + " = (" + msd.getExtName() + ") " + RECEIVE_MESSAGE_PARAM + ";"); + } + addReturnNextSocket(mb, succ); + } + + // Payload parameters added later + private MethodBuilder makeReceiveHeader(EAction a, EState succ) throws ScribException + { + MethodBuilder mb = this.cb.newMethod(); + setReceiveHeaderWithoutReturnType(this.apigen, a, mb); + setNextSocketReturnType(this.apigen, mb, succ); + return mb; + } + + // [nextClass] async([opClass] op, Buf arg) + private void makeAsyncMethod(EAction a, EState succ, String futureClass) + { + final String ROLE_PARAM = "role"; + String opClass = SessionApiGenerator.getOpClassName(a.mid); + + MethodBuilder mb = this.cb.newMethod("async"); + // Blurb stuff similar to makeReceiveHeader + mb.addModifiers(JavaBuilder.PUBLIC);//, ClassBuilder.SYNCHRONIZED); + //setNextSocketReturnType(mb, succ); + setNextSocketReturnType(this.apigen, mb, succ); + mb.addExceptions(StateChannelApiGenerator.SCRIBBLERUNTIMEEXCEPTION_CLASS); + mb.addParameters(SessionApiGenerator.getRoleClassName(a.obj) + " " + ROLE_PARAM); + mb.addParameters(opClass + " " + StateChannelApiGenerator.RECEIVE_OP_PARAM); + mb.addParameters(BUF_CLASS + "<" + futureClass + "> " + RECEIVE_ARG_PREFIX); // Method for future-buf even if no payload, for sync action + //mb.addBodyLine(ClassBuilder.SUPER + ".use();"); + //mb2.addBodyLine(ARG_PREFIX + ".val = " + " " + ClassBuilder.SUPER + ".getFuture(" + getPrefixedRoleClassName(a.peer) + ");"); + mb.addBodyLine(RECEIVE_ARG_PREFIX + "." + BUFF_VAL_FIELD + " = " + + JavaBuilder.NEW + " " + futureClass + "(" + JavaBuilder.SUPER + ".getFuture(" + getSessionApiRoleConstant(a.obj) + "));"); + addReturnNextSocket(mb, succ); + } + + // [nextClass] async([opClass] op) -- wrapper for makeAsyncMethod + private void makeAsyncDiscardMethod(EAction a, EState succ, String futureClass) + { + MethodBuilder mb = makeAsyncDiscardHeader(a, succ, futureClass); + mb.addBodyLine(JavaBuilder.RETURN + " async(" + SessionApiGenerator.getSessionClassName(apigen.getGProtocolName()) + "." + a.obj + ", " + StateChannelApiGenerator.RECEIVE_OP_PARAM + ", " + getGarbageBuf(futureClass) + ");"); + mb.addAnnotations("@SuppressWarnings(\"unchecked\")"); // To cast the generic garbage buf + } + + private MethodBuilder makeAsyncDiscardHeader(EAction a, EState succ, String futureClass) + { + MethodBuilder mb = this.cb.newMethod(); + setAsyncDiscardHeaderWithoutReturnType(this.apigen, a, mb, futureClass); + setNextSocketReturnType(this.apigen, mb, succ); + return mb; + } + + // boolean isDone() + private void makeIsDoneMethod(EAction a) + { + MethodBuilder mb = cb.newMethod("isDone"); + mb.addModifiers(JavaBuilder.PUBLIC); + mb.setReturn("boolean"); + mb.addBodyLine(JavaBuilder.RETURN + " " + JavaBuilder.SUPER + ".isDone(" + getSessionApiRoleConstant(a.obj) + ");"); + } + + // Doesn't include return type + //public static void makeReceiveHeader(StateChannelApiGenerator apigen, IOAction a, EndpointState succ, MethodBuilder mb) + public static void setReceiveHeaderWithoutReturnType(StateChannelApiGenerator apigen, EAction a, MethodBuilder mb) throws ScribException + { + final String ROLE_PARAM = "role"; + Module main = apigen.getMainModule(); // FIXME: main not necessarily the right module? + String opClass = SessionApiGenerator.getOpClassName(a.mid); + + mb.setName("receive"); + mb.addModifiers(JavaBuilder.PUBLIC); + mb.addExceptions(StateChannelApiGenerator.SCRIBBLERUNTIMEEXCEPTION_CLASS, "java.io.IOException", "ClassNotFoundException"); + //, "ExecutionException", "InterruptedException"); + mb.addParameters(SessionApiGenerator.getRoleClassName(a.obj) + " " + ROLE_PARAM, opClass + " " + StateChannelApiGenerator.RECEIVE_OP_PARAM); + if (a.mid.isOp()) + { + addReceiveOpParams(mb, main, a, true); + } + else //if (a.mid.isMessageSigName()) + { + SigDecl msd = main.getSigDeclChild(((SigName) a.mid).getSimpleName()); // FIXME: might not belong to main module + addReceiveMessageSigNameParams(mb, msd, true); + } + } + + // FIXME: main may not be the right module + protected static void addReceiveOpParams(MethodBuilder mb, Module main, EAction a, boolean superr) throws ScribException + { + if (!a.payload.isEmpty()) + { + String buffSuper = BUF_CLASS + "<" + ((superr) ? "? " + JavaBuilder.SUPER + " " : ""); + int i = 1; + for (PayElemType pt : a.payload.elems) + { + if (!pt.isDataName()) + { + throw new ScribException("[TODO] API generation not supported for non- data type payloads: " + pt); + } + DataDecl dtd = main.getTypeDeclChild((DataName) pt); // TODO: if not DataType + ScribSockGen.checkJavaDataTypeDecl(dtd); + mb.addParameters(buffSuper + dtd.getExtName() + "> " + RECEIVE_ARG_PREFIX + i++); + } + } + } + + protected static void addPayloadBuffSetters(Module main, EAction a, MethodBuilder mb) + { + if (!a.payload.isEmpty()) + { + int i = 1; + for (PayElemType pt : a.payload.elems) // Could factor out this loop (arg names) with addReceiveOpParams (as for send) + { + DataDecl dtd = main.getTypeDeclChild((DataName) pt); // TODO: if not DataType + mb.addBodyLine(RECEIVE_ARG_PREFIX + i + "." + BUFF_VAL_FIELD + " = (" + dtd.getExtName() + ") " + + RECEIVE_MESSAGE_PARAM + "." + SCRIBMESSAGE_PAYLOAD_FIELD + "[" + (i++ - 1) +"];"); + } + } + } + + protected static void addReceiveMessageSigNameParams(MethodBuilder mb, SigDecl msd, boolean superr) throws ScribException + { + ScribSockGen.checkMessageSigNameDecl(msd); + mb.addParameters(BUF_CLASS + "<" + ((superr) ? "? " + JavaBuilder.SUPER + " " : "") + msd.getExtName() + "> " + RECEIVE_ARG_PREFIX); + } + + // Similar to setReceiveHeader + public static void setAsyncDiscardHeaderWithoutReturnType(StateChannelApiGenerator apigen, EAction a, MethodBuilder mb, String futureClass) + { + final String ROLE_PARAM = "role"; + final String opClass = SessionApiGenerator.getOpClassName(a.mid); + + mb.setName("async"); + mb.addModifiers(JavaBuilder.PUBLIC); + mb.addParameters(SessionApiGenerator.getRoleClassName(a.obj) + " " + ROLE_PARAM, opClass + " " + StateChannelApiGenerator.RECEIVE_OP_PARAM); + mb.addExceptions(StateChannelApiGenerator.SCRIBBLERUNTIMEEXCEPTION_CLASS); + } +} diff --git a/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/ScribSockGen.java b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/ScribSockGen.java new file mode 100644 index 000000000..1321f20fd --- /dev/null +++ b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/ScribSockGen.java @@ -0,0 +1,316 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.codegen.java.statechanapi; + +import org.scribble.ast.DataDecl; +import org.scribble.ast.SigDecl; +import org.scribble.ast.NonProtoDecl; +import org.scribble.ast.global.GProtoDecl; +import org.scribble.codegen.java.sessionapi.SessionApiGenerator; +import org.scribble.codegen.java.util.ClassBuilder; +import org.scribble.codegen.java.util.ConstructorBuilder; +import org.scribble.codegen.java.util.FieldBuilder; +import org.scribble.codegen.java.util.JavaBuilder; +import org.scribble.codegen.java.util.MethodBuilder; +import org.scribble.core.model.endpoint.EState; +import org.scribble.core.type.name.GProtoName; +import org.scribble.core.type.name.MsgId; +import org.scribble.core.type.name.Role; +import org.scribble.util.ScribException; + +// Parameterize on output class type +public abstract class ScribSockGen extends StateChanTypeGen +{ + public static final String JAVA_SCHEMA = "java"; // FIXME: factor out + + public static final String SESSIONENDPOINT_CLASS = "org.scribble.runtime.session.SessionEndpoint"; + public static final String MPSTENDPOINT_CLASS = "org.scribble.runtime.session.MPSTEndpoint"; + public static final String EXPLICITENDPOINT_CLASS = "org.scribble.runtime.session.ExplicitEndpoint"; + public static final String OPENUM_INTERFACE = "org.scribble.runtime.session.OpEnum"; + + public static final String BUF_CLASS = "org.scribble.runtime.util.Buf"; + + //public static final String CONNECTSOCKET_CLASS = "org.scribble.statechans.ConnectSocket"; + public static final String ACCEPTSOCKET_CLASS = "org.scribble.runtime.statechans.AcceptSocket"; + //public static final String DISCONNECTSOCKET_CLASS = "org.scribble.statechans.DisconnectSocket"; + public static final String OUTPUTSOCKET_CLASS = "org.scribble.runtime.statechans.OutputSocket"; + public static final String RECEIVESOCKET_CLASS = "org.scribble.runtime.statechans.ReceiveSocket"; + public static final String BRANCHSOCKET_CLASS = "org.scribble.runtime.statechans.BranchSocket"; + public static final String CASESOCKET_CLASS = "org.scribble.runtime.statechans.CaseSocket"; + public static final String ENDSOCKET_CLASS = "org.scribble.runtime.statechans.EndSocket"; + + public static final String SCRIBSERVERSOCKET_CLASS = "org.scribble.runtime.net.ScribServerSocket"; + + public static final String GENERATED_ENDSOCKET_NAME = "EndSocket"; + + public static final String BUFF_VAL_FIELD = "val"; + public static final String SCRIBSOCKET_SE_FIELD = JavaBuilder.THIS + ".se"; + public static final String SCRIBMESSAGE_PAYLOAD_FIELD = "payload"; + + public static final String RECEIVE_MESSAGE_PARAM = "m"; + public static final String RECEIVE_ARG_PREFIX = "arg"; + + public static final String CASE_OP_FIELD = "op"; + public static final String CASE_OP_PARAM = CASE_OP_FIELD; + public static final String CASE_MESSAGE_FIELD = "m"; + public static final String CASE_MESSAGE_PARAM = CASE_MESSAGE_FIELD; + public static final String CASE_ARG_PREFIX = "arg"; + + protected final EState curr; + protected final String className; + + protected final ClassBuilder cb = new ClassBuilder(); + + public ScribSockGen(StateChannelApiGenerator apigen, EState curr) + { + super(apigen); + this.curr = curr; + this.className = getClassName(); + } + + protected String getClassName() + { + return this.apigen.getSocketClassName(this.curr); + } + + @Override + public ClassBuilder generateType() throws ScribException + { + constructClass(); // So className can be "overridden" in subclass constructor (CaseSocket) + return this.cb; + } + + protected void constructClass() throws ScribException + { + constructClassExceptMethods(); + addMethods(); + } + + protected void constructClassExceptMethods() + { + this.cb.setName(this.className); + //this.cb.setPackage(getSessionPackageName()); + this.cb.setPackage(getStateChannelPackageName()); + this.cb.addModifiers(JavaBuilder.PUBLIC, JavaBuilder.FINAL); + //cb.setSuperClass(superc + "<" + SessionApiGenerator.getSessionClassName(this.gpn) + ", " + SessionApiGenerator.getRoleClassName(this.self) + ">"); + this.cb.setSuperClass(getSuperClassType()); + addImports(); + addConstructor(); + + FieldBuilder cast = this.cb.newField("cast"); + cast.addModifiers(JavaBuilder.PUBLIC, JavaBuilder.STATIC, JavaBuilder.FINAL); + cast.setType(this.className); + cast.setExpression("null"); + } + + protected abstract String getSuperClassType(); + + protected void addImports() + { + //this.cb.addImports("java.io.IOException"); + //this.cb.addImports(getSessionPackageName() + "." + getSessionClassName()); + this.cb.addImports(getEndpointApiRootPackageName() + ".*"); + this.cb.addImports(getRolesPackageName() + ".*"); + } + + protected MethodBuilder addConstructor() + { + final String SESSIONENDPOINT_PARAM = "se"; + final String sess = getSessionClassName(); + final String role = getSelfClassName(); + + ConstructorBuilder ctor = cb.newConstructor(SESSIONENDPOINT_CLASS + "<" + sess + ", " + role + "> " + SESSIONENDPOINT_PARAM, "boolean dummy"); + ctor.addModifiers(JavaBuilder.PROTECTED); + ctor.addBodyLine(JavaBuilder.SUPER + "(" + SESSIONENDPOINT_PARAM + ");"); + if (this.curr.equals(this.apigen.getInitialState())) + { + addInitialStateConstructor(); + } + return ctor; + } + + protected void addInitialStateConstructor() + { + final String SESSIONENDPOINT_PARAM = "se"; + String sess = getSessionClassName(); + String role = getSelfClassName(); + /*MethodBuilder mb = cb.newMethod("init"); + mb.addModifiers(ClassBuilder.PUBLIC, ClassBuilder.STATIC); + mb.setReturn(this.root); + mb.addParameters(SESSIONENDPOINT_CLASS + "<" + role + "> " + SESSIONENDPOINT_PARAM); + mb.addExceptions(SCRIBBLERUNTIMEEXCEPTION_CLASS); + mb.addBodyLine(SESSIONENDPOINT_PARAM + ".init();"); + mb.addBodyLine(ClassBuilder.RETURN + " " + ClassBuilder.NEW + " " + this.root + "(" + SESSIONENDPOINT_PARAM + ");");*/ + + GProtoDecl gpd = (GProtoDecl) this.apigen.getJob().getContext() + .getModule(this.apigen.gpn.getPrefix()) + .getGProtocolDeclChild(this.apigen.gpn.getSimpleName()); + String epClass = gpd.isExplicit() ? EXPLICITENDPOINT_CLASS + : MPSTENDPOINT_CLASS; + ConstructorBuilder ctor2 = cb.newConstructor( + epClass + "<" + sess + ", " + role + "> " + SESSIONENDPOINT_PARAM); + + ctor2.addExceptions(StateChannelApiGenerator.SCRIBBLERUNTIMEEXCEPTION_CLASS); + ctor2.addModifiers(JavaBuilder.PUBLIC); + ctor2.addBodyLine(JavaBuilder.SUPER + "(" + SESSIONENDPOINT_PARAM + ");"); + ctor2.addBodyLine(SESSIONENDPOINT_PARAM + ".init();"); + } + + protected abstract void addMethods() throws ScribException; + + /*@Deprecated + protected void setNextSocketReturnType(MethodBuilder mb, EState succ) + { + setNextSocketReturnType(this.apigen, mb, succ); + }*/ + + //protected void addReturnNextSocket(MethodBuilder mb, String nextClass) + protected void addReturnNextSocket(MethodBuilder mb, EState s) + { + String nextClass; + //if (isTerminalClassName(nextClass)) + if (s.isTerminal()) + { + mb.addBodyLine(SCRIBSOCKET_SE_FIELD + ".setCompleted();"); // Do before the IO action? in case of exception? + nextClass = GENERATED_ENDSOCKET_NAME;// + "<>"; + } + else + { + nextClass = this.apigen.getSocketClassName(s); + } + mb.addBodyLine(JavaBuilder.RETURN + " " + JavaBuilder.NEW + " " + nextClass + "(" + SCRIBSOCKET_SE_FIELD + ", true);"); + } + + protected String getGarbageBuf(String futureClass) + { + //return ClassBuilder.NEW + " " + BUFF_CLASS + "<>()"; // Makes a trash Buff every time, but clean -- would be more efficient to generate the code to spawn the future without buff-ing it (partly duplicate of the normal receive generated code) + return "(" + BUF_CLASS + "<" + futureClass + ">) " + SCRIBSOCKET_SE_FIELD + ".gc"; // FIXME: generic cast warning (this.ep.gc is Buff) -- also retains unnecessary reference to the last created garbage future (but allows no-arg receive/async to be generated as simple wrapper call) + } + + // Not fully qualified, just Session API class prefix + // The constant singleton value of this type in the Session API (which is the same "name" as the class) + protected String getSessionApiRoleConstant(Role role) + { + return SessionApiGenerator.getSessionClassName(this.apigen.getGProtocolName()) + "." + role; + } + + // Not fully qualified, just Session API class prefix + // The constant singleton value of this type in the Session API (which is the same "name" as the class) + protected String getSessionApiOpConstant(MsgId mid) + { + return SessionApiGenerator.getSessionClassName(this.apigen.getGProtocolName()) + "." + SessionApiGenerator.getOpClassName(mid); + } + + // Wrappers for EndpointApiGenerator getters + protected String getSessionClassName() + { + return SessionApiGenerator.getSessionClassName(this.apigen.getGProtocolName()); + } + + protected String getSelfClassName() + { + return SessionApiGenerator.getRoleClassName(this.apigen.getSelf()); + } + + protected String getEndpointApiRootPackageName() + { + /*GProtocolName gpn = this.apigen.getGProtocolName(); + return SessionApiGenerator.getSessionApiPackageName(this.apigen.getGProtocolName()) + ".api" + gpn.getSimpleName();*/ + return SessionApiGenerator.getEndpointApiRootPackageName(this.apigen.getGProtocolName()); + } + + protected String getRolesPackageName() + { + return SessionApiGenerator.getRolesPackageName(this.apigen.getGProtocolName()); + } + + protected String getOpsPackageName() + { + return SessionApiGenerator.getOpsPackageName(this.apigen.getGProtocolName()); + } + + protected String getStateChannelPackageName() + { + //return getSessionPackageName() + ".channels." + this.apigen.getSelf(); + return SessionApiGenerator.getStateChannelPackageName(this.apigen.getGProtocolName(), this.apigen.getSelf()); + } + + public static void setNextSocketReturnType(StateChannelApiGenerator apigen, MethodBuilder mb, EState succ) + { + String ret; + if (succ.isTerminal()) + { + GProtoName gpn = apigen.getGProtocolName(); + Role self = apigen.getSelf(); + ret = SessionApiGenerator.getStateChannelPackageName(gpn, self) + "." + GENERATED_ENDSOCKET_NAME; + //+ "<" + SessionApiGenerator.getSessionClassName(gpn) + ", " + SessionApiGenerator.getRoleClassName(self) + ">"; + } + else + { + ret = apigen.getSocketClassName(succ); + } + mb.setReturn(ret); + } + + protected static void checkJavaDataTypeDecl(DataDecl dtd) throws ScribException + { + checkJavaSchema(dtd); + } + + protected static void checkMessageSigNameDecl(SigDecl msd) throws ScribException + { + checkJavaSchema(msd); + } + + protected static void checkJavaSchema(NonProtoDecl npd) throws ScribException + { + if (!npd.getSchema().equals(ScribSockGen.JAVA_SCHEMA)) // FIXME: factor out + { + throw new ScribException(npd.getSource(), "Unsupported data type schema: " + npd.getSchema()); + } + } + + /*private static boolean isTerminalClassName(String n) + { + //return n.equals(ClassBuilder.VOID); + return n.equals(EndpointApiGenerator.ENDSOCKET_CLASS); + }*/ + + /*// Pre: not a terminal state (i.e. className is not void) + private ClassBuilder constructInitClass(String className) + { + final String SESSIONENDPOINT_PARAM = "se"; + String role = SessionApiGenerator.getRoleClassName(this.self); + + ClassBuilder cb = new ClassBuilder(); + cb.setName(className); + cb.setPackage(getPackageName()); + cb.setSuperClass(INITSOCKET_CLASS + "<" + role + ">"); + cb.addModifiers(ClassBuilder.PUBLIC); + + MethodBuilder ctor = cb.newConstructor(SESSIONENDPOINT_CLASS + "<" + role + "> " + SESSIONENDPOINT_PARAM); + ctor.addModifiers(ClassBuilder.PUBLIC); + ctor.addBodyLine(ClassBuilder.SUPER + "(" + SESSIONENDPOINT_PARAM + ");"); + + MethodBuilder mb = cb.newMethod("init"); + mb.setReturn(this.root); + mb.addModifiers(ClassBuilder.PUBLIC); + mb.addExceptions(SCRIBBLERUNTIMEEXCEPTION_CLASS); + mb.addBodyLine(ClassBuilder.SUPER + ".use();"); // Factor out + //mb.addBodyLine(SCRIBSOCKET_SE_FIELD + ".init();"); // Factor out + addReturnNextSocket(mb, this.root); + + return cb; + }*/ +} diff --git a/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/StateChanTypeGen.java b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/StateChanTypeGen.java new file mode 100644 index 000000000..1c6ac3777 --- /dev/null +++ b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/StateChanTypeGen.java @@ -0,0 +1,30 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.codegen.java.statechanapi; + +import org.scribble.codegen.java.util.TypeBuilder; +import org.scribble.util.ScribException; + +// Build a (top-level) type declaration for the API generation output +public abstract class StateChanTypeGen +{ + protected final StateChannelApiGenerator apigen; + + public StateChanTypeGen(StateChannelApiGenerator apigen) + { + this.apigen = apigen; + } + + public abstract TypeBuilder generateType() throws ScribException; // FIXME: APIGenerationException? +} diff --git a/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/StateChannelApiGenerator.java b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/StateChannelApiGenerator.java new file mode 100644 index 000000000..abd041396 --- /dev/null +++ b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/StateChannelApiGenerator.java @@ -0,0 +1,231 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.codegen.java.statechanapi; + +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +import org.scribble.ast.Module; +import org.scribble.codegen.java.ApiGen; +import org.scribble.codegen.java.sessionapi.SessionApiGenerator; +import org.scribble.codegen.java.util.ClassBuilder; +import org.scribble.codegen.java.util.TypeBuilder; +import org.scribble.core.job.CoreArgs; +import org.scribble.core.job.CoreContext; +import org.scribble.core.model.endpoint.EState; +import org.scribble.core.model.endpoint.actions.EAction; +import org.scribble.core.type.name.GProtoName; +import org.scribble.core.type.name.LProtoName; +import org.scribble.core.type.name.Role; +import org.scribble.core.visit.global.InlinedProjector; +import org.scribble.job.Job; +import org.scribble.util.ScribException; + +// TODO: "wildcard" unary async: op doesn't matter -- for branch-receive op "still needed" to cast to correct branch state +// TODO: "functional state interfaces", e.g. for smtp ehlo and quit actions + +// FIXME: selector(?) hanging on runtimeexception (from message formatter) +// FIXME: consume futures before wrap/reconnect +public class StateChannelApiGenerator extends ApiGen +{ + public static final String SCRIBMESSAGE_CLASS = "org.scribble.runtime.message.ScribMessage"; + public static final String SCRIBBLERUNTIMEEXCEPTION_CLASS = "org.scribble.main.ScribRuntimeException"; + public static final String RECEIVE_OP_PARAM = "op"; + public static final String SCRIBMESSAGE_OP_FIELD = "op"; + + private final Role self; + private final LProtoName lpn; + private final EState init; + //private final String root; + + protected final boolean skipIOInterfacesGeneration; + + private int counter = 1; + private Map classNames = new HashMap<>(); // Doesn't include terminal states + + private Map types = new HashMap<>(); // class/iface name key + + public StateChannelApiGenerator(Job job, GProtoName fullname, Role self) + throws ScribException // CHECKME: APIGenerationException? + { + super(job, fullname); + + this.self = self; + this.lpn = InlinedProjector.getFullProjectionName(fullname, self); + //this.init = job.getContext().getEndpointGraph(fullname, self).init; + CoreContext corec = this.core.getContext(); + this.init = this.job.config.args.get(CoreArgs.MIN_EFSM) + ? corec.getMinimisedEGraph(fullname, self).init + : corec.getEGraph(fullname, self).init; + + this.skipIOInterfacesGeneration = skipIOInterfacesGeneration(this.init); + + generateClassNames(this.init); + //this.root = this.classNames.get(this.init); + constructClasses(this.init); + + //EndpointState term = EndpointState.findTerminalState(new HashSet<>(), this.init); + EState term = this.init.getTerminal(); + if (term != null) + { + ClassBuilder cb = new EndSockGen(this, term).generateType(); + this.types.put(cb.getName(), cb); + } + } + + // Cf. IOInterfacesGenerator constructor + private static boolean skipIOInterfacesGeneration(EState init) + { + Set as = init.getReachableActions(); + as.addAll(init.getActions()); + if (as.stream().anyMatch(a -> !a.isSend() && !a.isReceive())) // HACK FIXME (connect/disconnect) + { + return true; + } + return false; + } + + // Return: key (package and Java class file path) -> val (Java class source) + @Override + public Map generateApi() + { + Map map = new HashMap(); + // FIXME: factor out with ScribSocketBuilder.getPackageName + String prefix = SessionApiGenerator.getEndpointApiRootPackageName(this.gpn) + .replace('.', '/') + "/statechans/" + this.self + "/"; + for (String s : this.types.keySet()) + { + String path = prefix + s + ".java"; + map.put(path, this.types.get(s).build()); + } + return map; + } + + private void generateClassNames(EState ps) + { + if (this.classNames.containsKey(ps)) + { + return; + } + if (ps.isTerminal()) + { + //this.classNames.put(ps, ENDSOCKET_CLASS); // FIXME: add generic parameters? or don't record? + return; + } + this.classNames.put(ps, newSocketClassName()); + for (EState succ : ps.getSuccs()) + { + generateClassNames(succ); + } + } + + private String newSocketClassName() + { + return this.lpn.getSimpleName().toString() + "_" + this.counter++; + } + + private void constructClasses(EState curr) throws ScribException + { + if (curr.isTerminal()) + { + return; // Generic EndSocket for terminal states + } + String className = this.classNames.get(curr); + if (this.types.containsKey(className)) + { + return; + } + this.types.put(className, constructClass(curr)); + for (EState succ : curr.getSuccs()) + { + constructClasses(succ); + } + + // Depends on the above being done first (for this.root) + /*String init = this.lpn.getSimpleName().toString() + "_" + 0; // FIXME: factor out with newClassName + this.classes.put(init, constructInitClass(init));*/ + } + + // Pre: curr is not terminal state + private ClassBuilder constructClass(EState curr) throws ScribException // FIXME: APIGenerationException? + { + switch (curr.getStateKind()) + { + case OUTPUT: + { + /*Set as = curr.getTakeable(); + if (as.stream().allMatch((a) -> a.isSend()))*/ + { + return new OutputSockGen(this, curr).generateType(); + } + //throw new RuntimeException("TODO: " + curr.toLongString()); + } + case ACCEPT: + { + return new AcceptSockGen(this, curr).generateType(); + } + case UNARY_RECEIVE: + { + return new ReceiveSockGen(this, curr).generateType(); + } + case POLY_RECIEVE: + { + // Receive only + return new BranchSockGen(this, curr).generateType(); + } + default: + { + throw new RuntimeException( + "[TODO] State Channel API generation not supported for: " + + curr.getStateKind() + ", " + curr.toVerboseString()); + } + } + } + + public GProtoName getGProtocolName() + { + return this.gpn; + } + + public Role getSelf() + { + return this.self; + } + + protected EState getInitialState() + { + return this.init; + } + + protected Module getMainModule() + { + return this.job.getContext().getMainModule(); + } + + protected void addTypeDecl(TypeBuilder tb) + { + this.types.put(tb.getName(), tb); + } + + public String getSocketClassName(EState s) + { + return this.classNames.get(s); + } + + public TypeBuilder getType(String key) + { + return this.types.get(key); + } +} diff --git a/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/ioifaces/ActionIfaceGen.java b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/ioifaces/ActionIfaceGen.java new file mode 100644 index 000000000..c256808a8 --- /dev/null +++ b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/ioifaces/ActionIfaceGen.java @@ -0,0 +1,140 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.codegen.java.statechanapi.ioifaces; + +import org.scribble.codegen.java.sessionapi.SessionApiGenerator; +import org.scribble.codegen.java.statechanapi.OutputSockGen; +import org.scribble.codegen.java.statechanapi.ReceiveSockGen; +import org.scribble.codegen.java.statechanapi.StateChannelApiGenerator; +import org.scribble.codegen.java.util.AbstractMethodBuilder; +import org.scribble.codegen.java.util.InterfaceBuilder; +import org.scribble.codegen.java.util.JavaBuilder; +import org.scribble.core.model.endpoint.EState; +import org.scribble.core.model.endpoint.actions.EAction; +import org.scribble.core.model.endpoint.actions.ERecv; +import org.scribble.core.type.name.GProtoName; +import org.scribble.core.type.name.PayElemType; +import org.scribble.util.ScribException; + +public class ActionIfaceGen extends IOIfaceGen +{ + private final EAction a; + private final InterfaceBuilder ib = new InterfaceBuilder(); + + public ActionIfaceGen(StateChannelApiGenerator apigen, EState curr, EAction a) + { + super(apigen, curr); + this.a = a; + } + + @Override + public InterfaceBuilder generateType() throws ScribException + { + GProtoName gpn = this.apigen.getGProtocolName(); + + this.ib.setName(getActionInterfaceName(this.a)); + this.ib.setPackage(IOInterfacesGenerator.getIOInterfacePackageName(this.apigen.getGProtocolName(), this.apigen.getSelf())); + this.ib.addImports("java.io.IOException"); + this.ib.addImports(SessionApiGenerator.getEndpointApiRootPackageName(gpn) + ".*"); // FIXME: factor out with ScribSocketGenerator + this.ib.addImports(SessionApiGenerator.getRolesPackageName(gpn) + ".*"); + this.ib.addImports(SessionApiGenerator.getOpsPackageName(gpn) + ".*"); + this.ib.addModifiers(JavaBuilder.PUBLIC); + this.ib.addParameters("__Succ extends " + SuccessorIfaceGen.getSuccessorInterfaceName(this.a)); + AbstractMethodBuilder mb = this.ib.newAbstractMethod(); // FIXME: factor out with ReceiveSocketBuilder + //AbstractMethodBuilder mb2 = null; + if (this.a instanceof ERecv) + { + /*if (this.curr.getAcceptable().size() > 1) + { + //CaseSocketGenerator.setCaseReceiveHeaderWithoutReturnType(this.apigen, this.a, mb); + } + //else*/ + { + ReceiveSockGen.setReceiveHeaderWithoutReturnType(this.apigen, this.a, mb); + /*if (this.curr.getAcceptable().size() == 1) // FIXME: action interface should not depend on curr state -- should generate this method in the IO State I/f, not here + { + mb2 = this.ib.newAbstractMethod(); + ReceiveSocketGenerator.setAsyncDiscardHeaderWithoutReturnType(this.apigen, this.a, mb2, + InputFutureGenerator.getInputFutureName(this.apigen.getSocketClassName(this.curr))); + } + /*else + { + CaseSocketGenerator.setCaseReceiveDiscardHeaderWithoutReturnType(this.apigen, this.a, mb2); + }*/ + } + } + else //if (this.a instanceof Send) + { + OutputSockGen.setSendHeaderWithoutReturnType(this.apigen, this.a, mb); + } + /*EndpointState succ = this.curr.accept(this.a); + if (succ.isTerminal()) + { + ScribSocketGenerator.setNextSocketReturnType(this.apigen, mb, succ); + /*if (this.a instanceof Receive) + { + ScribSocketGenerator.setNextSocketReturnType(this.apigen, mb2, succ); + }* / + } + else*/ + { + mb.setReturn("__Succ"); + //if (this.a instanceof Receive) + /*if (this.a instanceof Receive && this.curr.getAcceptable().size() == 1) + { + mb2.setReturn("__Succ"); + }*/ + } + return ib; + } + + // FIXME: curr unnecessary + public static String getActionInterfaceName(EAction a) + { + /*String name = (a instanceof Receive) + ? "In" + : "Out";*/ + String name; + //if (curr.getAcceptable().iterator().next() instanceof Receive) + if (a instanceof ERecv) + { + /*if (curr.getAcceptable().size() > 1) + { + name = "Case"; // FIXME: make subtype of In? + } + //else*/ + { + name = "In"; + } + } + else + { + name = "Out"; + } + name += "_" + getActionString(a); + return name; + } + + public static String getActionString(EAction a) // FIXME: peer not needed for inputs + { + //String name = a.peer + "$" + a.mid; + String name = a.obj + "_" + a.mid; + for (PayElemType pay : a.payload.elems) + { + //name += "$" + pay; + name += "_" + pay; + } + return name; + } +} diff --git a/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/ioifaces/BranchIfaceGen.java b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/ioifaces/BranchIfaceGen.java new file mode 100644 index 000000000..90c0f47c9 --- /dev/null +++ b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/ioifaces/BranchIfaceGen.java @@ -0,0 +1,107 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.codegen.java.statechanapi.ioifaces; + +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +import org.scribble.codegen.java.sessionapi.SessionApiGenerator; +import org.scribble.codegen.java.statechanapi.ScribSockGen; +import org.scribble.codegen.java.statechanapi.StateChannelApiGenerator; +import org.scribble.codegen.java.util.AbstractMethodBuilder; +import org.scribble.codegen.java.util.EnumBuilder; +import org.scribble.codegen.java.util.InterfaceBuilder; +import org.scribble.codegen.java.util.JavaBuilder; +import org.scribble.core.model.endpoint.EState; +import org.scribble.core.model.endpoint.actions.EAction; +import org.scribble.core.type.name.Role; +import org.scribble.util.ScribException; + +public class BranchIfaceGen extends IOStateIfaceGen +{ + public BranchIfaceGen(StateChannelApiGenerator apigen, Map actions, EState curr) + { + super(apigen, actions, curr); + } + + @Override + protected void constructInterface() throws ScribException + { + super.constructInterface(); + addBranchEnum(); + addBranchMethods(); + } + + protected void addBranchMethods() + { + Role self = this.apigen.getSelf(); + //Set as = this.curr.getActions(); + List as = this.curr.getDetActions(); + + // FIXME: factor out with BranchSocketGenerator + AbstractMethodBuilder bra = this.ib.newAbstractMethod("branch"); + String ret = CaseIfaceGen.getCasesInterfaceName(self, this.curr) + + "<" + IntStream.range(1, as.size()+1).mapToObj((i) -> "__Succ" + i).collect(Collectors.joining(", ")) + ">"; // FIXME: factor out + bra.setReturn(ret); + bra.addParameters(SessionApiGenerator.getRoleClassName(as.iterator().next().obj) + " role"); + bra.addExceptions(StateChannelApiGenerator.SCRIBBLERUNTIMEEXCEPTION_CLASS, "java.io.IOException", "ClassNotFoundException"); + + AbstractMethodBuilder bra2 = this.ib.newAbstractMethod("branch"); + bra2.setReturn(JavaBuilder.VOID); + bra2.addParameters(SessionApiGenerator.getRoleClassName(as.iterator().next().obj) + " role"); + String next = HandleIfaceGen.getHandleInterfaceName(self, this.curr) + "<" + IntStream.range(1, as.size() + 1).mapToObj((i) -> "__Succ" + i).collect(Collectors.joining(", ")) + ">"; + bra2.addParameters(next + " handler"); + bra2.addExceptions(StateChannelApiGenerator.SCRIBBLERUNTIMEEXCEPTION_CLASS, "java.io.IOException", "ClassNotFoundException"); + + AbstractMethodBuilder bra3 = this.ib.newAbstractMethod("handle"); + bra3.setReturn(JavaBuilder.VOID); + bra3.addParameters(SessionApiGenerator.getRoleClassName(as.iterator().next().obj) + " role"); + String handle = HandleIfaceGen.getHandleInterfaceName(self, this.curr) + "<" + + as.stream().sorted(IOStateIfaceGen.IOACTION_COMPARATOR) + .map((a) -> SuccessorIfaceGen.getSuccessorInterfaceName(a)).collect(Collectors.joining(", ")) + ">"; + bra3.addParameters(handle + " handler"); + bra3.addExceptions(StateChannelApiGenerator.SCRIBBLERUNTIMEEXCEPTION_CLASS, "java.io.IOException", "ClassNotFoundException"); + } + + protected void addBranchEnum() + { + Role self = this.apigen.getSelf(); + + // Duplicated from BranchSocketGenerator + EnumBuilder eb = this.ib.newMemberEnum(getBranchInterfaceEnumName(self, this.curr)); + eb.addModifiers(JavaBuilder.PUBLIC); + eb.addInterfaces(ScribSockGen.OPENUM_INTERFACE); + this.curr.getDetActions() + .forEach(a -> eb.addValues(SessionApiGenerator.getOpClassName(a.mid))); + } + + // Don't add Action Interfaces (added to CaseInterface) + @Override + protected void addSuccessorParamsAndActionInterfaces() + { + int i = 1; + for (EAction a : this.curr.getDetActions().stream().sorted(IOACTION_COMPARATOR).collect(Collectors.toList())) + { + this.ib.addParameters("__Succ" + i + " extends " + SuccessorIfaceGen.getSuccessorInterfaceName(a)); + i++; + } + } + + public static String getBranchInterfaceEnumName(Role self, EState curr) + { + return getIOStateInterfaceName(self, curr) + "_Enum"; + } +} diff --git a/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/ioifaces/CaseIfaceGen.java b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/ioifaces/CaseIfaceGen.java new file mode 100644 index 000000000..4d22aca14 --- /dev/null +++ b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/ioifaces/CaseIfaceGen.java @@ -0,0 +1,111 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.codegen.java.statechanapi.ioifaces; + +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import org.scribble.codegen.java.sessionapi.SessionApiGenerator; +import org.scribble.codegen.java.statechanapi.CaseSockGen; +import org.scribble.codegen.java.statechanapi.ScribSockGen; +import org.scribble.codegen.java.statechanapi.StateChannelApiGenerator; +import org.scribble.codegen.java.util.AbstractMethodBuilder; +import org.scribble.codegen.java.util.InterfaceBuilder; +import org.scribble.codegen.java.util.JavaBuilder; +import org.scribble.codegen.java.util.MethodBuilder; +import org.scribble.core.model.endpoint.EState; +import org.scribble.core.model.endpoint.actions.EAction; +import org.scribble.core.type.name.GProtoName; +import org.scribble.core.type.name.Role; +import org.scribble.util.ScribException; + +public class CaseIfaceGen extends IOStateIfaceGen +{ + public CaseIfaceGen(StateChannelApiGenerator apigen, Map actions, EState curr) + { + super(apigen, actions, curr); + } + + @Override + protected void constructInterface() throws ScribException + { + super.constructInterface(); + addBranchEnumField(); + addCaseReceiveDiscardMethods(); + } + + @Override + protected void addHeader() + { + GProtoName gpn = this.apigen.getGProtocolName(); + Role self = this.apigen.getSelf(); + String packname = IOInterfacesGenerator.getIOInterfacePackageName(gpn, self); + String ifname = getCasesInterfaceName(self, this.curr); + + this.ib.setName(ifname); + this.ib.setPackage(packname); + this.ib.addModifiers(JavaBuilder.PUBLIC); + } + + /*@Override + protected void addSuccessorInterfaces() + { + + }*/ + + protected void addBranchEnumField() + { + Role self = this.apigen.getSelf(); + String name = super.getIOStateInterfaceName(self, this.curr); + + AbstractMethodBuilder op = this.ib.newAbstractMethod("getOp"); + op.setReturn(name + "." + BranchIfaceGen.getBranchInterfaceEnumName(self, this.curr)); + } + + protected void addCaseReceiveDiscardMethods() + { + GProtoName gpn = this.apigen.getGProtocolName(); + //Set as = this.curr.getActions(); + List as = this.curr.getDetActions(); + + int i = 1; + this.ib.addImports(SessionApiGenerator.getOpsPackageName(gpn) + ".*"); + for (EAction a : as.stream().sorted(IOACTION_COMPARATOR).collect(Collectors.toList())) + { + MethodBuilder mb = this.ib.newAbstractMethod(); + CaseSockGen.setCaseReceiveDiscardHeaderWithoutReturnType(this.apigen, a, mb); + EState succ = this.curr.getDetSuccessor(a); + if (succ.isTerminal()) + { + ScribSockGen.setNextSocketReturnType(this.apigen, mb, succ); + } + else + { + mb.setReturn("__Succ" + i); // Hacky? // FIXME: factor out Succ + } + i++; + } + } + + //protected static String getCasesInterfaceName(String braif) + // Pre: s is a branch state + // Cf. IOStateInterfaceGenerator.getIOStateInterfaceName + protected static String getCasesInterfaceName(Role self, EState s) + { + //return "Case_" + braif.substring("Branch_".length(), braif.length()); + return "Case_" + self + "_" + s.getDetActions().stream().sorted(IOACTION_COMPARATOR) + .map((a) -> ActionIfaceGen.getActionString(a)).collect(Collectors.joining("__")); + } +} diff --git a/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/ioifaces/HandleIfaceGen.java b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/ioifaces/HandleIfaceGen.java new file mode 100644 index 000000000..e84fb1266 --- /dev/null +++ b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/ioifaces/HandleIfaceGen.java @@ -0,0 +1,214 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.codegen.java.statechanapi.ioifaces; + +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import org.scribble.codegen.java.sessionapi.SessionApiGenerator; +import org.scribble.codegen.java.statechanapi.HandlerIfaceGen; +import org.scribble.codegen.java.statechanapi.ScribSockGen; +import org.scribble.codegen.java.util.InterfaceBuilder; +import org.scribble.codegen.java.util.JavaBuilder; +import org.scribble.codegen.java.util.MethodBuilder; +import org.scribble.core.model.endpoint.EState; +import org.scribble.core.model.endpoint.actions.EAction; +import org.scribble.core.type.name.GProtoName; +import org.scribble.core.type.name.Role; +import org.scribble.util.ScribException; + +// Cf. HandlerInterfaceGenerator +public class HandleIfaceGen extends IOStateIfaceGen +{ + //private final IOInterfacesGenerator iogen; + + private final Map caseActions; + + public HandleIfaceGen(IOInterfacesGenerator iogen, Map actions, EState curr, Map caseActions) + { + super(iogen.apigen, actions, curr); + //this.iogen = iogen; + + this.caseActions = caseActions; + } + + @Override + protected void constructInterface() throws ScribException + { + super.constructInterface(); + addHandleMethods(); + } + + @Override + protected void addHeader() + { + GProtoName gpn = this.apigen.getGProtocolName(); + Role self = this.apigen.getSelf(); + String packname = IOInterfacesGenerator.getIOInterfacePackageName(gpn, self); + String ifname = getHandleInterfaceName(self, this.curr); + + this.ib.setName(ifname); + this.ib.setPackage(packname); + this.ib.addModifiers(JavaBuilder.PUBLIC); + } + + @Override + protected void addCastField() + { + + } + + @Override + protected void addSuccessorParamsAndActionInterfaces() + { + //Role self = this.apigen.getSelf(); + + int i = 1; + //for (IOAction a : getHandleInterfaceIOActionParams(this.curr)) // Branch successor state successors, not the "direct" successors + // Duplicated from BranchInterfaceGenerator + for (EAction a : this.curr.getDetActions().stream().sorted(IOACTION_COMPARATOR).collect(Collectors.toList())) + { + this.ib.addParameters("__Succ" + i + " extends " + SuccessorIfaceGen.getSuccessorInterfaceName(a)); + this.ib.addInterfaces(this.caseActions.get(a).getName() + "<__Succ" + i + ">"); + i++; + } + /*for (InterfaceBuilder ib : this.succifs) // Already sorted + { + this.ib.addParameters("__Succ" + i + " extends " + ib.getName()); + i++; + }*/ + } + + /*// Pre: curr is a branch state + private static List getHandleInterfaceIOActionParams(EndpointState curr) + { + List as = new LinkedList<>(); + for (IOAction a : curr.getAcceptable().stream().sorted(IOACTION_COMPARATOR).collect(Collectors.toList())) + { + EndpointState succ = curr.accept(a); + /*InterfaceBuilder iostateif = this.iogen.getIOStateInterface(IOStateInterfaceGenerator.getIOStateInterfaceName(self, succ)); + for (String param : iostateif.getParameters()) + { + this.ib.addParameters("__Succ" + i + " extends " + SuccessorInterfaceGenerator.getSuccessorInterfaceName(this.curr, a)); + }* / + for (IOAction b : succ.getAcceptable().stream().sorted(IOACTION_COMPARATOR).collect(Collectors.toList())) + { + //if (!as.contains(b)) + { + as.add(b); + } + } + } + return as; + }*/ + + protected void addHandleMethods() throws ScribException + { + GProtoName gpn = this.apigen.getGProtocolName(); + //Role self = this.apigen.getSelf(); + //Set as = this.curr.getActions(); + List as = this.curr.getDetActions(); + + this.ib.addImports(SessionApiGenerator.getOpsPackageName(gpn) + ".*"); + int i = 1; + for (EAction a : as.stream().sorted(IOACTION_COMPARATOR).collect(Collectors.toList())) + { + /*EndpointState succ = this.curr.accept(a); + MethodBuilder mb = this.ib.newAbstractMethod(); + HandlerInterfaceGenerator.setHandleMethodHeaderWithoutParamTypes(this.apigen, mb); + i = setHandleMethodSuccessorParam(this.iogen, self, succ, mb, i); + HandlerInterfaceGenerator.addHandleMethodOpAndPayloadParams(this.apigen, a, mb);*/ + + MethodBuilder mb = this.ib.newAbstractMethod(); + HandlerIfaceGen.setHandleMethodHeaderWithoutParamTypes(this.apigen, mb); + //setHandleMethodSuccessorParam(this.iogen, self, succ, mb); + mb.addParameters("__Succ" + i++ + " schan"); + HandlerIfaceGen.addHandleMethodOpAndPayloadParams(this.apigen, a, mb); + } + } + + //protected static int setHandleMethodSuccessorParam(IOInterfacesGenerator iogen, Role self, EndpointState succ, MethodBuilder mb, int i) + protected static void setHandleMethodSuccessorParam(IOInterfacesGenerator iogen, Role self, EState succ, MethodBuilder mb, List as, Map count) + { + if (succ.isTerminal()) + { + mb.addParameters(ScribSockGen.ENDSOCKET_CLASS + " end"); + } + else + { + InterfaceBuilder next = iogen.getIOStateInterface(IOStateIfaceGen.getIOStateInterfaceName(self, succ)); // Select/Receive/Branch + String ret = next.getName() + "<"; + /*//ret += "<" + next.getParameters().stream().map((p) -> "__Succ" + i++).collect(Collectors.joining(", ")) + ">"; // FIXME: fragile? + boolean first = true; + for (String p : next.getParameters()) + { + if (first) + { + first = false; + } + else + { + ret += ", "; + } + ret += "__Succ" + i++; + } + ret += ">"; + mb.addParameters(ret + " schan"); + + // duplicates possible? -- can have repeat continuations, but the branch operation ops themselves will be distinct + } + return i;*/ + + //Map ount = new HashMap<>(); + boolean first = true; + for (EAction a : succ.getDetActions().stream().sorted(IOStateIfaceGen.IOACTION_COMPARATOR).collect(Collectors.toList())) + { + int offset; + if (!count.containsKey(a)) + { + offset = 0; + count.put(a, 0); + } + else + { + offset = count.get(a) + 1; + count.put(a, offset); + } + //if (count.keySet().size() > 1) + if (first) + { + first = false; + } + else + { + ret += ", "; + } + ret += "__Succ" + (as.indexOf(a) + 1 + offset); + } + ret += ">"; + mb.addParameters(ret + " schan"); + } + } + + // Pre: s is a branch state + public static String getHandleInterfaceName(Role self, EState s) + { + // FIXME: factor out (CaseInterfaceGenerator, IOStateInterfaceGenerator.getIOStateInterfaceName) + String name = "Handle_" + self + "_" + s.getDetActions().stream().sorted(IOACTION_COMPARATOR) + .map((a) -> ActionIfaceGen.getActionString(a)).collect(Collectors.joining("__")); + IOStateIfaceGen.checkIOStateInterfaceNameLength(name); + return name; + } +} diff --git a/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/ioifaces/IOIfaceGen.java b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/ioifaces/IOIfaceGen.java new file mode 100644 index 000000000..b7692af9a --- /dev/null +++ b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/ioifaces/IOIfaceGen.java @@ -0,0 +1,29 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.codegen.java.statechanapi.ioifaces; + +import org.scribble.codegen.java.statechanapi.StateChanTypeGen; +import org.scribble.codegen.java.statechanapi.StateChannelApiGenerator; +import org.scribble.core.model.endpoint.EState; + +public abstract class IOIfaceGen extends StateChanTypeGen +{ + protected final EState curr; + + public IOIfaceGen(StateChannelApiGenerator apigen, EState curr) + { + super(apigen); + this.curr = curr; + } +} diff --git a/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/ioifaces/IOInterfacesGenerator.java b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/ioifaces/IOInterfacesGenerator.java new file mode 100644 index 000000000..2aec10116 --- /dev/null +++ b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/ioifaces/IOInterfacesGenerator.java @@ -0,0 +1,1057 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.codegen.java.statechanapi.ioifaces; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +import org.scribble.codegen.java.ApiGen; +import org.scribble.codegen.java.sessionapi.SessionApiGenerator; +import org.scribble.codegen.java.statechanapi.CaseSockGen; +import org.scribble.codegen.java.statechanapi.HandlerIfaceGen; +import org.scribble.codegen.java.statechanapi.ScribSockGen; +import org.scribble.codegen.java.statechanapi.StateChannelApiGenerator; +import org.scribble.codegen.java.util.AbstractMethodBuilder; +import org.scribble.codegen.java.util.ClassBuilder; +import org.scribble.codegen.java.util.FieldBuilder; +import org.scribble.codegen.java.util.InterfaceBuilder; +import org.scribble.codegen.java.util.JavaBuilder; +import org.scribble.codegen.java.util.MethodBuilder; +import org.scribble.codegen.java.util.TypeBuilder; +import org.scribble.core.job.CoreArgs; +import org.scribble.core.job.CoreContext; +import org.scribble.core.model.endpoint.EState; +import org.scribble.core.model.endpoint.EStateKind; +import org.scribble.core.model.endpoint.actions.EAction; +import org.scribble.core.type.name.GProtoName; +import org.scribble.core.type.name.Role; +import org.scribble.util.RuntimeScribException; +import org.scribble.util.ScribException; + +// Cf. StateChannelApiGenerator +// TODO: concrete state channel "to" casts for supertype i/f's (the info is there in the Java type hierachy though) +// Maybe record subtype hierarchy explicitly +// TODO: check if generated subtypes scalability issue is just Eclipse or also javac +// FIXME: try I/O i/f's with "message decomposition" approach (split op and each payload as separate messages) -- should make nominal interfaces more manageable -- cf. Sig messages +public class IOInterfacesGenerator extends ApiGen +{ + private final boolean SUBTYPES; + + protected StateChannelApiGenerator apigen; + + private final Map actions = new HashMap<>(); + private final Map succs = new HashMap<>(); + private final Map iostates = new HashMap<>(); // Key is interface simple name + + private final Map caseActions = new HashMap<>(); + + private final Map> preActions = new HashMap<>(); // Pre set: the actions that lead to each state + private final Map> preds = new HashMap<>(); + + private final Map> branchPostActions = new HashMap<>(); + //private final Map> branchSuccs = new HashMap<>(); + private final Map> branchSuccs = new HashMap<>(); // key: HandleInterface name // Sorted when collected + + public IOInterfacesGenerator(StateChannelApiGenerator apigen, + boolean subtypes) throws RuntimeScribException, ScribException + { + super(apigen.getJob(), apigen.getGProtocolName()); + this.apigen = apigen; + this.SUBTYPES = subtypes; + + GProtoName fullname = apigen.getGProtocolName(); + Role self = getSelf(); + //EndpointState init = this.job.getContext().getEndpointGraph(fullname, self).init; + CoreContext corec = this.core.getContext(); + EState init = this.job.config.args.get(CoreArgs.MIN_EFSM) + ? corec.getMinimisedEGraph(fullname, self).init + : corec.getEGraph(fullname, self).init; + //if (IOInterfacesGenerator.skipIOInterfacesGeneration(init)) + { + // FIXME: factor out with skipIOInterfacesGeneration + Set as = init.getReachableActions(); + if (as.stream().anyMatch(a -> !a.isSend() && !a.isReceive())) // HACK FIXME (connect/disconnect) + { + throw new RuntimeScribException( + "[TODO] I/O Interface generation not supported for: " + + as.stream().filter(a -> !a.isSend() && !a.isReceive()) + .collect(Collectors.toList())); + } + } + + generateActionAndSuccessorInterfacesAndCollectPreActions(new HashSet<>(), init); + generateIOStateInterfacesFirstPass(new HashSet<>(), init); + collectPreds(); + + //EndpointState term = EndpointState.findTerminalState(new HashSet<>(), init); + EState term = init.getTerminal(); + ClassBuilder endsock = null; + if (term != null) + { + endsock = (ClassBuilder) this.apigen.getType(ScribSockGen.GENERATED_ENDSOCKET_NAME); + for (InterfaceBuilder ib : this.preds.get(term)) + { + endsock.addInterfaces(ib.getName()); + + MethodBuilder mb2 = addToCastMethod(ib, "EndSocket"); + if (mb2 != null) + { + ib.addImports(SessionApiGenerator.getStateChannelPackageName(this.gpn, self) + ".EndSocket"); + } + } + endsock.addImports(getIOInterfacePackageName(this.gpn, self) + ".*"); + } + + generateIOStateInterfacesSecondPass(new HashSet<>(), init); + collectBranchSuccs(); + generateHandleInterfaces(new HashSet<>(), init); + generateHandleInterfacesSecondPass(new HashSet<>(), init); + addIOStateInterfacesToStateChannels(new HashSet<>(), init); // Except EndSocket + + if (this.SUBTYPES) + { + addSupertypeInterfaces(); + } + + // Successor I/f's for EndSocket + // FIXME: refactor EndSocket into main collection of generated types (this.apigen.getType) + //EndpointState term = EndpointState.findTerminalState(new HashSet<>(), init); + if (term != null) + { + //endsock = (ClassBuilder) this.apigen.getType(ScribSocketGenerator.GENERATED_ENDSOCKET_NAME); + //endsock.addImports(getIOInterfacePackageName(this.gpn, self) + ".*"); + for (InterfaceBuilder ib : this.preds.get(term)) + { + //endsock.addInterfaces(ib.getName()); + + // Duplicated from generateIOStateInterfacesSecondPass + for (MethodBuilder cast : ib.getDefaultMethods()) // cast is a default method (a to cast -- hacky) in pred + { + // Overriding every Successor I/f to methods in the I/O State I/f, even if unnecessary + if (!cast.getReturn().equals("EndSocket")) + { + MethodBuilder mb = addEndSocketToCastMethod(endsock, cast.getReturn(), "throw new RuntimeScribException(\"Invalid cast of EndSocket: \" + cast);"); + if (mb != null) + + { + mb.addModifiers(JavaBuilder.PUBLIC); + mb.addAnnotations("@Override"); + endsock.addImports("org.scribble.util.RuntimeScribException"); + } + } + } + } + + /*MethodBuilder mb2 = addToCastMethod(ib, "EndSocket"); + if (mb2 != null) + { + ib.addImports(SessionApiGenerator.getStateChannelPackageName(this.gpn, self) + ".EndSocket"); + }*/ + MethodBuilder mb3 = addEndSocketToCastMethod(endsock, "EndSocket", "return (EndSocket) this;"); + if (mb3 != null) + { + mb3.addModifiers(JavaBuilder.PUBLIC); + mb3.addAnnotations("@Override"); + } + } + } + + /*public static boolean skipIOInterfacesGeneration(EndpointState init) + { + Set as = EndpointState.getAllReachableActions(init); + if (as.stream().anyMatch((a) -> !a.isSend() && !a.isReceive())) // HACK FIXME (connect/disconnect) + { + return true; + } + return false; + }*/ + + @Override + public Map generateApi() + { + Map output = new HashMap<>(); + String prefix = getIOInterfacePackageName(this.gpn, getSelf()).replace('.', '/') + "/"; + this.actions.values() + .forEach(ib -> output.put(prefix + ib.getName() + ".java", ib.build())); + this.succs.values() + .forEach(ib -> output.put(prefix + ib.getName() + ".java", ib.build())); + this.iostates.values() + .forEach(tb -> output.put(prefix + tb.getName() + ".java", tb.build())); + + this.caseActions.values() + .forEach(ib -> output.put(prefix + ib.getName() + ".java", ib.build())); + + return output; + } + + // Factor out FSM visitor? + private void generateActionAndSuccessorInterfacesAndCollectPreActions(Set visited, EState s) throws ScribException + { + if (visited.contains(s) || s.isTerminal()) + { + return; + } + visited.add(s); + + //Set as = s.getActions(); + List as = s.getDetActions(); + for (EAction a : as.stream().sorted(IOStateIfaceGen.IOACTION_COMPARATOR).collect(Collectors.toList())) + { + if (!a.isSend() && !a.isReceive()) // TODO (connect/disconnect) + { + throw new RuntimeScribException("TODO: " + a); + } + + if (!this.actions.containsKey(a)) + { + this.actions.put(a, new ActionIfaceGen(this.apigen, s, a).generateType()); + this.succs.put(a, new SuccessorIfaceGen(this.apigen, s, a).generateType()); + + if (s.getStateKind() == EStateKind.POLY_RECIEVE) + { + // Duplicated from ActionInterfaceGenerator + InterfaceBuilder ib = new InterfaceBuilder(); + ib.setName("Callback_" + ActionIfaceGen.getActionString(a)); + ib.setPackage(IOInterfacesGenerator.getIOInterfacePackageName(this.apigen.getGProtocolName(), this.apigen.getSelf())); + ib.addImports("java.io.IOException"); + ib.addImports(SessionApiGenerator.getEndpointApiRootPackageName(this.gpn) + ".*"); + ib.addImports(SessionApiGenerator.getRolesPackageName(this.gpn) + ".*"); + ib.addImports(SessionApiGenerator.getOpsPackageName(this.gpn) + ".*"); + ib.addModifiers(JavaBuilder.PUBLIC); + ib.addParameters("__Succ extends " + SuccessorIfaceGen.getSuccessorInterfaceName(a)); + AbstractMethodBuilder mb = ib.newAbstractMethod(); + // Duplicated from HandleInterfaceGenerator + HandlerIfaceGen.setHandleMethodHeaderWithoutParamTypes(this.apigen, mb); + mb.addParameters("__Succ schan"); + HandlerIfaceGen.addHandleMethodOpAndPayloadParams(this.apigen, a, mb); + this.caseActions.put(a, ib); + } + } + + EState succ = s.getDetSuccessor(a); + putPreAction(succ, a); + + if (s.getStateKind() == EStateKind.POLY_RECIEVE) + { + /*for (IOAction b : s.accept(a).getAcceptable().stream().sorted(IOStateInterfaceGenerator.IOACTION_COMPARATOR).collect(Collectors.toList())) + { + putBranchPostAction(s, b); + }*/ + putBranchPostAction(s, a); + } + + generateActionAndSuccessorInterfacesAndCollectPreActions(visited, succ); + /*Set tmp = new HashSet<>(visited); + tmp.add(s); // merge paths visited multiple times + generateActionAndSuccessorInterfacesAndCollectPredecessors(tmp, succ);*/ + } + } + + // Generates partial IO State Interfaces + private void generateIOStateInterfacesFirstPass(Set visited, EState s) throws ScribException + { + if (visited.contains(s) || s.isTerminal()) + { + return; + } + + String key = IOStateIfaceGen.getIOStateInterfaceName(getSelf(), s); + if (!this.iostates.containsKey(key)) // Don't generate if one already exists (up to this pass, repeats will all be the same, i.e. name, Action Interfaces, and action-succ parameters) + { + // Make the partial I/O State Interface (Successor Interfaces and cast methods added later -- different states may share same State I/f) + IOStateIfaceGen ifgen = null; + switch (s.getStateKind()) + { + case OUTPUT: // Send, connect, disconnect + ifgen = new SelectIfaceGen(this.apigen, this.actions, s); + break; + case UNARY_RECEIVE: + ifgen = new ReceiveIfaceGen(this.apigen, this.actions, s); + break; + case POLY_RECIEVE: + InterfaceBuilder cases = new CaseIfaceGen(this.apigen, this.actions, s).generateType(); + this.iostates.put(cases.getName(), cases); + ifgen = new BranchIfaceGen(this.apigen, this.actions, s); + break; + case TERMINAL: + default: + throw new RuntimeException("(TODO) I/O interface generation: " + s.getStateKind()); + } + this.iostates.put(key, ifgen.generateType()); + } + + visited.add(s); + for (EAction a : s.getDetActions()) + { + generateIOStateInterfacesFirstPass(visited, s.getDetSuccessor(a)); + } + } + + // Adds Successor Interfaces and to-cast methods to IO State Interfaces + private void generateIOStateInterfacesSecondPass(Set visited, EState s) + { + if (visited.contains(s) || s.isTerminal()) + { + return; + } + + Set succifs = this.preds.get(s); // Successor interfaces to be implemented by IO State Interface of s + if (succifs != null) + { + InterfaceBuilder iostate = this.iostates.get(IOStateIfaceGen.getIOStateInterfaceName(getSelf(), s)); + if (this.SUBTYPES) // HACK moved here from addSupertypeInterfaces to ensure duplicate inherited to's get overridden + { + // Generate Succ I/f supertype "to" cast methods for supertype to's + String name = iostate.getName(); + if (name.startsWith("Select")) + { + List ifs = this.iostates.get(name).getInterfaces(); + List outs = ifs.stream().filter((i) -> i.startsWith("Out")) + .map((o) -> (o = o.substring(0, o.indexOf("<"))).substring(o.indexOf("_") + 1, o.length())) + .sorted((s1, s2) -> s1.compareTo(s2)) + .collect(Collectors.toList()); + addSupertypeInterfaceToMethods(s, outs, "Select", "Out"); + } + } + + for (InterfaceBuilder pred : succifs) // pred is a Successor Interface for the state s + { + // May already have "visited" this State I/f for a different state -- Interfaces recorded as a Set, to support repeated adds + iostate.addInterfaces(pred.getName()); // Adds Successor Interfaces to this I/O State Interface + String ret = iostate.getName() + "<" + + IntStream.range(0, iostate.getParameters().size()).mapToObj((i) -> "?").collect(Collectors.joining(", ")) + ">"; + addToCastMethod(pred, ret); + + for (MethodBuilder cast : pred.getDefaultMethods()) // cast is a default method (a to cast -- hacky) in pred + { + // Overriding every Successor I/f "to" method in the I/O State I/f, even if unnecessary + MethodBuilder mb = addToCastMethod(iostate, cast.getReturn()); + if (mb != null) + { + mb.addAnnotations("@Override"); + } + } + } + } + + visited.add(s); + for (EAction a : s.getDetActions()) + { + generateIOStateInterfacesSecondPass(visited, s.getDetSuccessor(a)); + } + } + + private void generateHandleInterfaces(Set visited, EState s) throws ScribException + { + if (visited.contains(s) || s.isTerminal()) + { + return; + } + + if (s.getStateKind() == EStateKind.POLY_RECIEVE) + { + //Set succifs = this.preds.get(s); + String key = HandleIfaceGen.getHandleInterfaceName(getSelf(), s); + if (!this.iostates.containsKey(key)) + { + IOStateIfaceGen ifgen = new HandleIfaceGen(this, this.actions, s, this.caseActions); + this.iostates.put(key, ifgen.generateType()); + } + } + + visited.add(s); + for (EAction a : s.getDetActions()) + { + generateHandleInterfaces(visited, s.getDetSuccessor(a)); + } + } + + private void generateHandleInterfacesSecondPass(Set visited, EState s) + { + if (visited.contains(s) || s.isTerminal()) + { + return; + } + + if (s.getStateKind() == EStateKind.POLY_RECIEVE) + { + //GProtocolName gpn = this.apigen.getGProtocolName(); + Role self = this.apigen.getSelf(); + + //String foo = HandlerInterfaceGenerator.getHandlerInterfaceName(IOStateInterfaceGenerator.getIOStateInterfaceName(self, s)); + String key = HandleIfaceGen.getHandleInterfaceName(self, s); + List succifs = this.branchSuccs.get(key); + if (succifs != null) + { + ////InterfaceBuilder handleif = this.iostates.get(HandleInterfaceGenerator.getHandleInterfaceName(self, s)); + //InterfaceBuilder handleif = this.iostates.get(key); + + /*if (handleif.getParameters().isEmpty()) // Hacky? + { + int i = 1; + for (IOAction b : succifs) // Already sorted + { + handleif.addParameters("__Succ" + i + " extends " + SuccessorInterfaceGenerator.getSuccessorInterfaceName(b));//this.succs.get(b).getName()); + i++; + } + + handleif.addImports(SessionApiGenerator.getOpsPackageName(gpn) + ".*"); + //int j = 1; + /*Iterator foo = s.getAcceptable().stream().sorted(IOStateInterfaceGenerator.IOACTION_COMPARATOR).iterator(); + EndpointState succ = s.accept(foo.next());* / + }*/ + + ////Map count = new HashMap<>(); + //List tmp = this.branchSuccs.get(key); + ////tmp.stream().forEach((a) -> count.put(a, (int) tmp.stream().filter((b) -> b.equals(a)).count())); + //Map count = new HashMap<>(); + /*for (IOAction a : this.branchPostActions.get(s).stream().sorted(IOStateInterfaceGenerator.IOACTION_COMPARATOR).collect(Collectors.toList())) + { + /*for (IOAction b : succifs) + { + if (!succ.isAcceptable(b)) + { + succ = s.accept(foo.next()); + }* / + EndpointState succ = s.accept(a); + MethodBuilder mb = handleif.newAbstractMethod(); + HandlerInterfaceGenerator.setHandleMethodHeaderWithoutParamTypes(this.apigen, mb); + //j = HandleInterfaceGenerator.setHandleMethodSuccessorParam(this, self, succ, mb, j); + HandleInterfaceGenerator.setHandleMethodSuccessorParam(this, self, succ, mb, tmp, count); + /*for (IOAction b : count.keySet()) + { + for (int j = 0; j < count.get(b); j++) + { + tmp.remove(b); + } + }* / + HandlerInterfaceGenerator.addHandleMethodOpAndPayloadParams(this.apigen, a, mb); + + handleif.checkDuplicateMethods(mb); // Hacky + //} + }*/ + } + } + + visited.add(s); + for (EAction a : s.getDetActions()) + { + generateHandleInterfacesSecondPass(visited, s.getDetSuccessor(a)); + } + } + + // Except EndSocket + private void addIOStateInterfacesToStateChannels(Set visited, EState s) + { + if (visited.contains(s) || s.isTerminal()) + { + return; + } + + Role self = getSelf(); + String scname = this.apigen.getSocketClassName(s); + String ioname = IOStateIfaceGen.getIOStateInterfaceName(self, s); + + TypeBuilder tb = this.apigen.getType(scname); + + // Add I/O State Interface to each ScribSocket (except CaseSocket) + // Do here (not inside I/O State Interface generators) because multiple states can share the same I/O State Interface + tb.addImports(getIOInterfacePackageName(this.gpn, self) + ".*"); + tb.addInterfaces(ioname + getConcreteSuccessorParameters(s)); + + InterfaceBuilder iostate = this.iostates.get(ioname); + MethodBuilder mb = addToCastMethod(iostate, scname); + if (mb != null) + { + iostate.addImports(SessionApiGenerator.getStateChannelPackageName(this.gpn, self) + ".*"); + } + + if (s.getStateKind() == EStateKind.POLY_RECIEVE) + { + // Add CaseInterface to each CaseSocket + TypeBuilder cases = this.apigen.getType(CaseSockGen.getCaseSocketName(this.apigen.getSocketClassName(s))); + cases.addImports(getIOInterfacePackageName(this.gpn, self) + ".*"); + cases.addInterfaces(CaseIfaceGen.getCasesInterfaceName(self, s) + getConcreteSuccessorParameters(s)); + + // Add HandleInterface to each HandlerInterface + InterfaceBuilder handler = (InterfaceBuilder) this.apigen.getType(HandlerIfaceGen.getHandlerInterfaceName(this.apigen.getSocketClassName(s))); + handler.addImports(getIOInterfacePackageName(this.gpn, self) + ".*"); + // FIXME: factor out with HandleInterfaceGenerator and getConcreteSuccessorParameters + String tmp = ""; + boolean first = true; + /*for (IOAction a : s.getAcceptable().stream().sorted(IOStateInterfaceGenerator.IOACTION_COMPARATOR).collect(Collectors.toList())) + { + EndpointState succ = s.accept(a); + for (IOAction b : succ.getAcceptable().stream().sorted(IOStateInterfaceGenerator.IOACTION_COMPARATOR).collect(Collectors.toList())) + { + if (first) + { + first = false; + } + else + { + tmp += ", "; + } + tmp += this.getSuccName.apply(succ.accept(b)); + } + }*/ + String handle = HandleIfaceGen.getHandleInterfaceName(self, s); + /*List foo1 = new LinkedList<>(); + List bar1 = new LinkedList<>(); + for (IOAction a : s.getAcceptable().stream().sorted(IOStateInterfaceGenerator.IOACTION_COMPARATOR).collect(Collectors.toList())) + { + EndpointState succ = s.accept(a); + for (IOAction b : succ.getAcceptable().stream().sorted(IOStateInterfaceGenerator.IOACTION_COMPARATOR).collect(Collectors.toList())) + { + foo1.add(b); + bar1.add(succ); + } + } + System.out.println("BBB: " + handle);*/ + //for (IOAction a : this.branchSuccs.get(handle)) + // FIXME: move back into HandlerInterfaceGenerator + for (EAction a : s.getDetActions().stream().sorted(IOStateIfaceGen.IOACTION_COMPARATOR).collect(Collectors.toList())) + { + if (first) + { + first = false; + } + else + { + tmp += ", "; + } + /*if (foo1.contains(a)) + { + EndpointState succ = bar1.get(foo1.indexOf(a)); + tmp += this.getSuccName.apply(succ.accept(a)); + foo1.remove(a); + bar1.remove(succ); + } + else + { + tmp += SuccessorInterfaceGenerator.getSuccessorInterfaceName(a); + }*/ + EState succ = s.getDetSuccessor(a); + if (succ.isTerminal()) + { + tmp += ScribSockGen.GENERATED_ENDSOCKET_NAME; + } + else + { + tmp += this.apigen.getSocketClassName(succ); + } + } + + handler.addInterfaces(handle + "<" + tmp + ">"); + + /*// Override abstract handle methods with default cast implementation + for (IOAction a : s.getAcceptable().stream().sorted(IOStateInterfaceGenerator.IOACTION_COMPARATOR).collect(Collectors.toList())) + { + EndpointState succ = s.accept(a); + this.iostates.get(HandleInterfaceGenerator.getHandleInterfaceName(self, succ)); + MethodBuilder override = handler.newDefaultMethod(); + //override.addModifiers(JavaBuilder.FINAL); // Default methods cannot be final + HandlerInterfaceGenerator.setHandleMethodHeaderWithoutParamTypes(this.apigen, override); + //HandleInterfaceGenerator.setHandleMethodSuccessorParam(this, self, succ, override); + // FIXME: factor out with HandleInterfaceGenerator.setHandleMethodSuccessorParam + String nextClass = this.apigen.getSocketClassName(succ); + if (succ.isTerminal()) + { + override.addParameters(ScribSocketGenerator.ENDSOCKET_CLASS + " end"); + } + else + { + InterfaceBuilder next = getIOStateInterface(IOStateInterfaceGenerator.getIOStateInterfaceName(self, succ)); // Select/Receive/Branch + String ret = next.getName() + "<"; + //ret += "<" + next.getParameters().stream().map((p) -> "__Succ" + i).collect(Collectors.joining(", ")) + ">"; // FIXME: fragile? + boolean bar = true; + for (IOAction b : succ.getAcceptable().stream().sorted(IOStateInterfaceGenerator.IOACTION_COMPARATOR).collect(Collectors.toList())) // FIXME: factor out with getHandleInterfaceIOActionParams + { + if (bar) + { + bar = false; + } + else + { + ret += ", "; + } + EndpointState foo = succ.accept(b); + if (foo.isTerminal()) + { + ret += ScribSocketGenerator.GENERATED_ENDSOCKET_NAME; + } + else + { + ret += this.apigen.getSocketClassName(foo); + } + } + ret += ">"; + override.addParameters(ret + " schan"); + } + HandlerInterfaceGenerator.addHandleMethodOpAndPayloadParams(this.apigen, a, override); + // FIXME: factor out + String ln = "receive(("; + if (succ.isTerminal()) // factor out + { + ln += "EndSocket) end"; + } + else + { + ln += nextClass + ") schan"; + } + ln += ", op"; + String args; + if (a.mid.isOp()) // factor out + { + args = IntStream.rangeClosed(1, a.payload.elems.size()).mapToObj((i) -> "arg" + i).collect(Collectors.joining(", ")); + if (!args.equals("")) + { + args = ", " + args; + } + } + else + { + args = ", arg"; + } + ln += args + ");"; + override.addBodyLine(ln); + override.addAnnotations("@Override"); + }*/ + } + + visited.add(s); + for (EAction a : s.getDetActions()) + { + addIOStateInterfacesToStateChannels(visited, s.getDetSuccessor(a)); + } + } + + private void addSupertypeInterfaces() + { + Map subtypeifs = new HashMap<>(); + for (InterfaceBuilder ib : this.iostates.values()) + { + String name = ib.getName(); + if (!subtypeifs.containsKey(name)) + { + if (name.startsWith("Select") || name.startsWith("Handle")) + { + subtypeifs.put(name, ib); + + Map res = new HashMap<>(); + if (name.startsWith("Select")) + { + List ifs = ib.getInterfaces(); // Could also use params to integrate with Handle + List outs = ifs.stream().filter((i) -> i.startsWith("Out")) + .map((o) -> (o = o.substring(0, o.indexOf("<"))).substring(o.indexOf("_") + 1, o.length())) + .sorted((s1, s2) -> s1.compareTo(s2)) + .collect(Collectors.toList()); + buildIOStateSuperInterfaces(res, outs, "Select", "Out", "Out"); + } + else //if (base.startsWith("Handle")) + { + List params = ib.getParameters(); + List ins = params.stream().map((i) -> i.substring(i.indexOf("Succ_In_") + "Succ_In_".length())) + .sorted((s1, s2) -> s1.compareTo(s2)) + .collect(Collectors.toList()); + //buildSuperHandleInterfaces(res, ins); + buildIOStateSuperInterfaces(res, ins, "Handle", "Callback", "In"); + //buildIOStateSuperInterfaces(res, ins, "Branch", "", "In"); // No: subtyping for branch interfaces unsafe -- that's the point of handle interfaces + /*Map tmp = new HashMap<>(); + buildIOStateSuperInterfaces(tmp, ins, "Branch", "", "In"); + for (InterfaceBuilder bra : tmp.values()) + { + addBranchSupertypeInterfaceMethods(ib, bra, ins, getSelf()); + } + res.putAll(tmp);*/ + } + res.values().forEach(r -> subtypeifs.put(r.getName(), r)); + } + } + } + subtypeifs.values().forEach((r) -> this.iostates.put(r.getName(), r)); + + for (InterfaceBuilder ib : this.iostates.values()) + { + String name = ib.getName(); + if (name.startsWith("Select")) + { + List ifs = ib.getInterfaces(); + List outs = ifs.stream().filter((i) -> i.startsWith("Out")) + .map((o) -> (o = o.substring(0, o.indexOf("<"))).substring(o.indexOf("_") + 1, o.length())) + .sorted((s1, s2) -> s1.compareTo(s2)) + .collect(Collectors.toList()); + addIOStateSuperInterfaces(ib, outs, "Select", "Out"); + } + else if (name.startsWith("Handle")) + { + List params = ib.getParameters(); + List ins = params.stream().map((i) -> i.substring(i.indexOf("Succ_In_") + "Succ_In_".length())) + .sorted((s1, s2) -> s1.compareTo(s2)) + .collect(Collectors.toList()); + addIOStateSuperInterfaces(ib, ins, "Handle", "In"); + } + /*else if (name.startsWith("Branch")) // No: subtyping for branch interfaces unsafe -- that's the point of handle interfaces + { + List params = ib.getParameters(); + List ins = params.stream().map((i) -> i.substring(i.indexOf("Succ_In_") + "Succ_In_".length())) + .sorted((s1, s2) -> s1.compareTo(s2)) + .collect(Collectors.toList()); + addIOStateSuperInterfaces(ib, ins, "Branch", "In"); + }*/ + } + + /*// Generate Succ I/f supertype "to" cast methods -- moved earlier, to be supported by to-overriding pass (i.e. when a direct I/O State I/f inherits duplicate to's from Succs) + Role self = getSelf(); + for (EndpointState s : this.preds.keySet()) + { + if (s.isTerminal()) + { + continue; + } + String name = IOStateInterfaceGenerator.getIOStateInterfaceName(self, s); + if (name.startsWith("Select")) + { + + System.out.println("AAA: " + name); + + List ifs = this.iostates.get(name).getInterfaces(); + List outs = ifs.stream().filter((i) -> i.startsWith("Out")) + .map((o) -> (o = o.substring(0, o.indexOf("<"))).substring(o.indexOf("_") + 1, o.length())) + .sorted((s1, s2) -> s1.compareTo(s2)) + .collect(Collectors.toList()); + addSupertypeInterfaceToMethods(s, outs, "Select", "Out"); + } + /*else if (name.startsWith("Branch")) + { + List params = this.iostates.get(name).getParameters(); + List ins = params.stream().map((i) -> i.substring(i.indexOf("Succ_In_") + "Succ_In_".length())) + .sorted((s1, s2) -> s1.compareTo(s2)) + .collect(Collectors.toList()); + addSupertypeInterfaceToMethods(s, ins, "Branch", "In"); + }* / + }*/ + } + + // a = e.g. C_1_Int + // Pre: as sorted + private void buildIOStateSuperInterfaces(Map res, List as, String superPref, String actPref, String succPref) + { + for (String exclude : as) + { + List foo = as.stream().filter((s) -> !s.equals(exclude)).collect(Collectors.toList()); + if (foo.size() > 0) + { + String tmp = foo.stream().collect(Collectors.joining("__")); + String superName = superPref + "_" + getSelf() + "_" + tmp; + + if (!this.iostates.containsKey(superName) && !res.containsKey(superName)) + { + InterfaceBuilder ib = new InterfaceBuilder(superName); + ib.setPackage(getIOInterfacePackageName(this.gpn, getSelf())); + ib.addModifiers(JavaBuilder.PUBLIC); + int i = 1; + for (String a : foo) + { + ib.addParameters("__Succ" + i + " extends " + "Succ_" + succPref + "_" + a); + if (!superPref.equals("Branch")) // Hacky + { + ib.addInterfaces(actPref + "_" + a + "<__Succ" + i + ">"); + } + i++; + } + FieldBuilder cast = ib.newField("cast"); // FIXME: factor out + cast.addModifiers(JavaBuilder.PUBLIC, JavaBuilder.STATIC, JavaBuilder.FINAL); + cast.setType(superName + "<" + IntStream.range(0, foo.size()).mapToObj((x) -> "?").collect(Collectors.joining(", ")) + ">"); + cast.setExpression("null"); + res.put(superName, ib); + buildIOStateSuperInterfaces(res, foo, superPref, actPref, succPref); + } + } + } + } + + /*//private void addBranchSupertypeInterfaceMethods(EndpointState s, InterfaceBuilder ib, Role self) + private void addBranchSupertypeInterfaceMethods(InterfaceBuilder root, InterfaceBuilder ib, List foo, Role self) + { + //Duplicated from BranchInterfaceGenerator + /*AbstractMethodBuilder bra = ib.newAbstractMethod("branch"); + String ret = CaseInterfaceGenerator.getCasesInterfaceName(self, s) + + "<" + IntStream.range(1, as.size()+1).mapToObj((x) -> "__Succ" + x).collect(Collectors.joining(", ")) + ">"; // FIXME: factor out + bra.setReturn(ret); + bra.addParameters(SessionApiGenerator.getRoleClassName(as.iterator().next().peer) + " role"); + bra.addExceptions(StateChannelApiGenerator.SCRIBBLERUNTIMEEXCEPTION_CLASS, "java.io.IOException", "ClassNotFoundException");* / + + List params = ib.getParameters(); + List ins = params.stream().map((i) -> i.substring(i.indexOf("Succ_In_") + "Succ_In_".length())) + .sorted((s1, s2) -> s1.compareTo(s2)) + .collect(Collectors.toList()); + + String handleName = "Handle" + ib.getName().substring("Branch".length(), ib.getName().length()); + System.out.println("AAA: " + ib.getName() + ", " + handleName); + //String peer = ib.getName().substring(ib.getName().indexOf("_") + 1, ib.getName().indexOf("_", ib.getName().indexOf("_") + 1)); + String peer = ins.get(0).substring(0, ins.get(0).indexOf("_")); + + AbstractMethodBuilder bra2 = ib.newAbstractMethod("branch"); + bra2.setReturn(JavaBuilder.VOID); + bra2.addParameters(peer + " role"); + String next = handleName + "<" + IntStream.range(1, ins.size() + 1).mapToObj((i) -> "__Succ" + i).collect(Collectors.joining(", ")) + ">"; + bra2.addParameters(next + " handler"); + bra2.addExceptions(StateChannelApiGenerator.SCRIBBLERUNTIMEEXCEPTION_CLASS, "java.io.IOException", "ClassNotFoundException"); + //bra2.addBodyLine("branch(role, (" + root.getName() + ") handler);"); + + AbstractMethodBuilder bra3 = ib.newAbstractMethod("handle"); + bra3.setReturn(JavaBuilder.VOID); + bra3.addParameters(peer + " role"); + String handle = handleName + "<" + ins.stream().map((in) -> "Succ_In_" + in).collect(Collectors.joining(", ")) + ">"; + bra3.addParameters(handle + " handler"); + bra3.addExceptions(StateChannelApiGenerator.SCRIBBLERUNTIMEEXCEPTION_CLASS, "java.io.IOException", "ClassNotFoundException"); + //bra3.addBodyLine("branch(role, (" + root.getName() + ") handler);"); + + ib.addImports(SessionApiGenerator.getRolesPackageName(this.gpn) + ".*"); + // No: generating "super" branch/handle methods for supertypes is not safe + }*/ + + // a = e.g. C_1_Int + // Pre: as sorted + private void addIOStateSuperInterfaces(InterfaceBuilder ib, List as, String superPref, String succPref) + { + for (String exclude : as) + { + List foo = as.stream().filter((s) -> !s.equals(exclude)).collect(Collectors.toList()); + if (foo.size() > 0) + { + List params = new LinkedList<>(); + for (String a : foo) + { + int i = 1; + for (String param : ib.getParameters()) + { + if (param.endsWith("Succ_" + succPref + "_" + a)) + { + break; + } + i++; + } + params.add("__Succ" + i); + } + + String tmp = foo.stream().collect(Collectors.joining("__")); + String select = superPref + "_" + getSelf() + "_" + tmp + "<" + params.stream().collect(Collectors.joining(", ")) + ">"; + ib.addInterfaces(select); + } + } + } + + // Pre: s has "preds", i.e. s implements a Successor I/f + private void addSupertypeInterfaceToMethods(EState s, List as, String superPref, String succPref) + { + for (String exclude : as) + { + List foo = as.stream().filter((x) -> !x.equals(exclude)).collect(Collectors.toList()); + if (foo.size() > 0) + { + String tmp = foo.stream().collect(Collectors.joining("__")); + String superName = superPref + "_" + getSelf() + "_" + tmp; + for (InterfaceBuilder succif : this.preds.get(s)) + { + addToCastMethod(succif, superName + "<" + IntStream.range(0, foo.size()).mapToObj((f) -> "?").collect(Collectors.joining(", ")) +">"); + } + + if (!this.iostates.containsKey(superName)) + { + addSupertypeInterfaceToMethods(s, foo, superPref, succPref); + } + } + } + } + + // Pre: ib is a Successor I/f for the cast IO State I/f + // Returns MethodBuilder, or null if none built + private static MethodBuilder addToCastMethod(InterfaceBuilder ib, String ret) + { + if (ib.getDefaultMethods().stream().filter((def) -> def.getReturn().equals(ret)).count() > 0) + { + // Merge states entered from multiple paths, don't want to add cast multiple times -- still true for this case? + // But duplicate cast check cast still needed anyway? + return null; + } + MethodBuilder mb = ib.newDefaultMethod("to"); + mb.setReturn(ret); + mb.addParameters(ret + " cast"); + if (!ret.equals("EndSocket") || ib.getName().startsWith("Succ")) // HACK + { + mb.addBodyLine(JavaBuilder.RETURN + " (" + ret + ") this;"); + } + else + { + ib.addImports("org.scribble.util.RuntimeScribException"); + mb.addBodyLine("throw new RuntimeScribException(\"Invalid cast to EndSocket: \" + cast);"); + } + return mb; + } + + private static MethodBuilder addEndSocketToCastMethod(ClassBuilder cb, String ret, String body) + { + //if (ib.getMethods().stream().filter((def) -> def.getReturn().equals(ret)).count() > 0) + if (cb.hasMethodSignature(ret, ret + " ")) // Hacky + { + // Merge states entered from multiple paths, don't want to add cast multiple times -- still true for this case? + // But duplicate cast check cast still needed anyway? + return null; + } + MethodBuilder mb = cb.newMethod("to"); + mb.setReturn(ret); + mb.addParameters(ret + " cast"); + //mb.addBodyLine("throw new RuntimeScribbleException(\"Invalid cast of EndSocket: \" + cast);"); + mb.addBodyLine(body); + return mb; + } + + private final + Function getSuccName = (succ) -> + (succ.isTerminal()) + ? ScribSockGen.GENERATED_ENDSOCKET_NAME + : this.apigen.getSocketClassName(succ); + + private String getConcreteSuccessorParameters(EState s) + { + return "<" + + s.getDetActions().stream().sorted(IOStateIfaceGen.IOACTION_COMPARATOR) + .map((a) -> this.getSuccName.apply(s.getDetSuccessor(a))).collect(Collectors.joining(", ")) + + ">"; + } + + private void putPreAction(EState s, EAction a) + { + putMapSet(this.preActions, s, a); + } + + private void putBranchPostAction(EState s, EAction a) + { + putMapSet(this.branchPostActions, s, a); + } + + private static void putMapSet(Map> map, K k, V v) + { + Set tmp = map.get(k); + if (tmp == null) + { + tmp = new LinkedHashSet<>(); + map.put(k, tmp); + } + tmp.add(v); + } + + // Successor I/f's to be implemented by each I/O State I/f + private void collectPreds() + { + for (EState s : this.preActions.keySet()) + { + Set tmp = new HashSet<>(); + for (EAction a : this.preActions.get(s)) // sort? + { + if (!a.isSend() && !a.isReceive()) // TODO (connect/disconnect) + { + throw new RuntimeException("TODO: " + a); + } + tmp.add(this.succs.get(a)); + } + this.preds.put(s, tmp); + } + } + + private void collectBranchSuccs() + { + Role self = getSelf(); + for (EState s : this.branchPostActions.keySet()) + { + //String key = HandlerInterfaceGenerator.getHandlerInterfaceName(IOStateInterfaceGenerator.getIOStateInterfaceName(self, s)); + String key = HandleIfaceGen.getHandleInterfaceName(self, s); // HandleInterface name + + List curr1 = new LinkedList<>(); + this.branchPostActions.get(s).forEach((a) -> curr1.addAll(s.getDetSuccessor(a).getDetActions())); // TODO: flatmap + //List curr2 = curr1.stream().sorted(IOStateInterfaceGenerator.IOACTION_COMPARATOR).collect(Collectors.toList()); + + List tmp = this.branchSuccs.get(key); + if (tmp == null) + { + tmp = new LinkedList<>(); + //this.branchSuccs.put(key, tmp); + tmp.addAll(curr1); + } + else + { + for (EAction a : curr1) + { + long n = curr1.stream().filter((x) -> x.equals(a)).count(); + long m = tmp.stream().filter((x) -> x.equals(a)).count(); + //System.out.println("EEE: " + curr1 + ",,, " + tmp); + if (n > m) + { + for (int i = 0; i < n-m; i++) + { + tmp.add(a); + } + } + } + } + + this.branchSuccs.put(key, tmp.stream().sorted(IOStateIfaceGen.IOACTION_COMPARATOR).collect(Collectors.toList())); + //System.out.println("AAA: " + this.branchSuccs.get(key)); + + /*List tmp = this.branchSuccs.get(key); + if (tmp == null) + { + tmp = new LinkedList<>(); + this.branchSuccs.put(key, tmp); + } + //this.branchPostActions.get(s).stream()//.sorted(IOStateInterfaceGenerator.IOACTION_COMPARATOR) + //.forEach((a) -> { tmp.add(this.succs.get(a)); }); + for (IOAction a : this.branchPostActions.get(s)) // Already sorted -- guaranteed pairwise distinct (branch actions) //.sorted(IOStateInterfaceGenerator.IOACTION_COMPARATOR) + { + // Not necessarily distinct (actions of the branch successor state) + for (IOAction b : s.accept(a).getAcceptable().stream().sorted(IOStateInterfaceGenerator.IOACTION_COMPARATOR).collect(Collectors.toList())) + { + //tmp.add(this.succs.get(b)); + tmp.add(b); + } + } + tmp = tmp.stream().so*/ + } + } + + protected Role getSelf() + { + return this.apigen.getSelf(); + } + + protected static String getIOInterfacePackageName(GProtoName gpn, Role self) + { + return SessionApiGenerator.getStateChannelPackageName(gpn, self) + ".ioifaces"; + } + + protected InterfaceBuilder getIOStateInterface(String name) + { + return this.iostates.get(name); + } +} diff --git a/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/ioifaces/IOStateIfaceGen.java b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/ioifaces/IOStateIfaceGen.java new file mode 100644 index 000000000..5f48b4e65 --- /dev/null +++ b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/ioifaces/IOStateIfaceGen.java @@ -0,0 +1,154 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.codegen.java.statechanapi.ioifaces; + +import java.util.Collections; +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +import org.scribble.codegen.java.sessionapi.SessionApiGenerator; +import org.scribble.codegen.java.statechanapi.StateChannelApiGenerator; +import org.scribble.codegen.java.util.FieldBuilder; +import org.scribble.codegen.java.util.InterfaceBuilder; +import org.scribble.codegen.java.util.JavaBuilder; +import org.scribble.codegen.java.util.TypeBuilder; +import org.scribble.core.model.endpoint.EState; +import org.scribble.core.model.endpoint.actions.EAction; +import org.scribble.core.type.name.GProtoName; +import org.scribble.core.type.name.Role; +import org.scribble.util.RuntimeScribException; +import org.scribble.util.ScribException; + +// Cf. ScribSocketGenerator +// Partial I/O State I/f generator -- Successor Interfaces and cast methods added later +public abstract class IOStateIfaceGen extends IOIfaceGen +{ + public static final Comparator IOACTION_COMPARATOR = new Comparator() + { + @Override + public int compare(EAction a1, EAction a2) + { + return ActionIfaceGen.getActionInterfaceName(a1).compareTo(ActionIfaceGen.getActionInterfaceName(a2)); + } + }; + + protected final Map actions; + + protected final InterfaceBuilder ib = new InterfaceBuilder(); + + // Preds can be null + public IOStateIfaceGen(StateChannelApiGenerator apigen, Map actions, EState curr) + { + super(apigen, curr); + this.actions = Collections.unmodifiableMap(actions); + } + + @Override + public InterfaceBuilder generateType() throws ScribException + { + constructInterface(); + return this.ib; + } + + protected void constructInterface() throws ScribException + { + addHeader(); + addSuccessorParamsAndActionInterfaces(); + //addSuccessorInterfaces(); // Do later (different states may share the same IO State I/f, don't know all successors for this I/f yet (only this state) + addCastField(); + } + + protected void addHeader() + { + GProtoName gpn = this.apigen.getGProtocolName(); + Role self = this.apigen.getSelf(); + String packname = IOInterfacesGenerator.getIOInterfacePackageName(gpn, self); + String ifname = getIOStateInterfaceName(self, this.curr); + + this.ib.setName(ifname); + this.ib.setPackage(packname); + this.ib.addImports(SessionApiGenerator.getRolesPackageName(gpn) + ".*"); + this.ib.addModifiers(JavaBuilder.PUBLIC); + } + + protected void addCastField() + { + String ifname = getIOStateInterfaceName(this.apigen.getSelf(), this.curr); + //Set as = this.curr.getActions(); + List as = this.curr.getDetActions(); + + FieldBuilder cast = this.ib.newField("cast"); + cast.addModifiers(TypeBuilder.PUBLIC, TypeBuilder.STATIC, TypeBuilder.FINAL); + cast.setType(ifname + "<" + IntStream.range(1, as.size()+1).mapToObj((i) -> "?").collect(Collectors.joining(", ")) + ">"); // FIXME: factor out + cast.setExpression("null"); + } + + protected void addSuccessorParamsAndActionInterfaces() + { + int i = 1; + for (EAction a : this.curr.getDetActions().stream().sorted(IOACTION_COMPARATOR).collect(Collectors.toList())) + { + if (a.isSend() || a.isReceive()) // HACK FIXME + { + String actif = this.actions.get(a).getName(); + this.ib.addParameters("__Succ" + i + " extends " + SuccessorIfaceGen.getSuccessorInterfaceName(a)); + this.ib.addInterfaces(actif + "<__Succ" + i + ">"); + i++; + } + } + } + + /*protected void addSuccessorInterfaces() + { + if (this.preds != null) + { + System.out.println("AA: " + this.ib.getName() + ", " + this.preds.stream().map((p) -> p.getName()).collect(Collectors.toList())); + + for (InterfaceBuilder pred : this.preds) + { + this.ib.addInterfaces(pred.getName()); // Adds Successor Interfaces to this I/O State Interface + } + } + }*/ + + // Pre: s non-terminal + public static String getIOStateInterfaceName(Role self, EState s) + { + String name = null; + switch (s.getStateKind()) + { + case OUTPUT: name = "Select"; break; + case UNARY_RECEIVE: name = "Receive"; break; + case POLY_RECIEVE: name = "Branch"; break; + case TERMINAL: throw new RuntimeScribException("Shouldn't get in here: " + s); + default: throw new RuntimeException("(TODO) I/O interface generation: " + s.getStateKind()); + } + name = name + "_" + self + "_" + s.getDetActions().stream().sorted(IOACTION_COMPARATOR) + .map((a) -> ActionIfaceGen.getActionString(a)).collect(Collectors.joining("__")); + checkIOStateInterfaceNameLength(name); + return name; + } + + // 255 is Linux, Windows, etc max file name length (Java is 65535) + public static void checkIOStateInterfaceNameLength(String name) throws RuntimeScribException + { + if (name.length() > 250) // .java + { + throw new RuntimeScribException("I/O Interface name too long (max 255): " + name); + } + } +} diff --git a/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/ioifaces/ReceiveIfaceGen.java b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/ioifaces/ReceiveIfaceGen.java new file mode 100644 index 000000000..c08d16f67 --- /dev/null +++ b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/ioifaces/ReceiveIfaceGen.java @@ -0,0 +1,73 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.codegen.java.statechanapi.ioifaces; + +import java.util.Map; + +import org.scribble.codegen.java.sessionapi.SessionApiGenerator; +import org.scribble.codegen.java.statechanapi.InputFutureGen; +import org.scribble.codegen.java.statechanapi.ReceiveSockGen; +import org.scribble.codegen.java.statechanapi.ScribSockGen; +import org.scribble.codegen.java.statechanapi.StateChannelApiGenerator; +import org.scribble.codegen.java.util.InterfaceBuilder; +import org.scribble.codegen.java.util.MethodBuilder; +import org.scribble.core.model.endpoint.EState; +import org.scribble.core.model.endpoint.actions.EAction; +import org.scribble.core.type.name.GProtoName; +import org.scribble.util.ScribException; + +public class ReceiveIfaceGen extends IOStateIfaceGen +{ + public ReceiveIfaceGen(StateChannelApiGenerator apigen, Map actions, EState curr) + { + super(apigen, actions, curr); + } + + @Override + public InterfaceBuilder generateType() throws ScribException + { + if (this.curr.getActions().stream().anyMatch((a) -> !a.isReceive())) // TODO (connect/disconnect) + { + //return null; + throw new RuntimeException("TODO: " + this.curr); + } + return super.generateType(); + } + + @Override + protected void constructInterface() throws ScribException + { + super.constructInterface(); + addAsyncDiscardMethod(); + } + + protected void addAsyncDiscardMethod() + { + GProtoName gpn = this.apigen.getGProtocolName(); + EAction first = this.curr.getDetActions().iterator().next(); + + MethodBuilder mb = this.ib.newAbstractMethod(); + ReceiveSockGen.setAsyncDiscardHeaderWithoutReturnType(this.apigen, first, mb, InputFutureGen.getInputFutureName(this.apigen.getSocketClassName(this.curr))); + this.ib.addImports(SessionApiGenerator.getOpsPackageName(gpn) + ".*"); + EState succ = this.curr.getDetSuccessor(first); + if (succ.isTerminal()) + { + ScribSockGen.setNextSocketReturnType(this.apigen, mb, succ); + } + else + { + mb.setReturn("__Succ1"); // Hacky? // FIXME: factor out Succ + } + } +} diff --git a/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/ioifaces/SelectIfaceGen.java b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/ioifaces/SelectIfaceGen.java new file mode 100644 index 000000000..28f9ff2ae --- /dev/null +++ b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/ioifaces/SelectIfaceGen.java @@ -0,0 +1,41 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.codegen.java.statechanapi.ioifaces; + +import java.util.Map; + +import org.scribble.codegen.java.statechanapi.StateChannelApiGenerator; +import org.scribble.codegen.java.util.InterfaceBuilder; +import org.scribble.core.model.endpoint.EState; +import org.scribble.core.model.endpoint.actions.EAction; +import org.scribble.util.ScribException; + +public class SelectIfaceGen extends IOStateIfaceGen +{ + public SelectIfaceGen(StateChannelApiGenerator apigen, Map actions, EState curr) + { + super(apigen, actions, curr); + } + + @Override + public InterfaceBuilder generateType() throws ScribException + { + if (this.curr.getActions().stream().anyMatch((a) -> !a.isSend())) // TODO (connect/disconnect) + { + //return null; + throw new RuntimeException("TODO: " + this.curr); + } + return super.generateType(); + } +} diff --git a/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/ioifaces/SuccessorIfaceGen.java b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/ioifaces/SuccessorIfaceGen.java new file mode 100644 index 000000000..fd448bfa3 --- /dev/null +++ b/scribble-codegen/src/main/java/org/scribble/codegen/java/statechanapi/ioifaces/SuccessorIfaceGen.java @@ -0,0 +1,47 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.codegen.java.statechanapi.ioifaces; + +import org.scribble.codegen.java.statechanapi.StateChannelApiGenerator; +import org.scribble.codegen.java.util.InterfaceBuilder; +import org.scribble.codegen.java.util.JavaBuilder; +import org.scribble.core.model.endpoint.EState; +import org.scribble.core.model.endpoint.actions.EAction; + +public class SuccessorIfaceGen extends IOIfaceGen +{ + private final EAction a; + private final InterfaceBuilder ib = new InterfaceBuilder(); + + public SuccessorIfaceGen(StateChannelApiGenerator apigen, EState curr, EAction a) + { + super(apigen, curr); + this.a = a; + } + + @Override + public InterfaceBuilder generateType() + { + this.ib.setName(getSuccessorInterfaceName(this.a)); + this.ib.setPackage(IOInterfacesGenerator.getIOInterfacePackageName(this.apigen.getGProtocolName(), this.apigen.getSelf())); + this.ib.addModifiers(JavaBuilder.PUBLIC); + //this.ib.addInterfaces(ifaces);(...State...); + return ib; + } + + public static String getSuccessorInterfaceName(EAction a) + { + return "Succ_" + ActionIfaceGen.getActionInterfaceName(a); + } +} diff --git a/scribble-codegen/src/main/java/org/scribble/codegen/java/util/AbstractMethodBuilder.java b/scribble-codegen/src/main/java/org/scribble/codegen/java/util/AbstractMethodBuilder.java new file mode 100644 index 000000000..3d7784615 --- /dev/null +++ b/scribble-codegen/src/main/java/org/scribble/codegen/java/util/AbstractMethodBuilder.java @@ -0,0 +1,34 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.codegen.java.util; + +public class AbstractMethodBuilder extends MethodBuilder +{ + protected AbstractMethodBuilder() + { + addModifiers(JavaBuilder.ABSTRACT); // Redundant for interfaces, but OK + } + + @Override + public void addBodyLine(String ln) + { + throw new RuntimeException("Invalid for abstract method: " + ln); + } + + @Override + protected String buildBody(String meth) + { + return meth + ";"; + } +} diff --git a/scribble-codegen/src/main/java/org/scribble/codegen/java/util/ClassBuilder.java b/scribble-codegen/src/main/java/org/scribble/codegen/java/util/ClassBuilder.java new file mode 100644 index 000000000..22a8193c7 --- /dev/null +++ b/scribble-codegen/src/main/java/org/scribble/codegen/java/util/ClassBuilder.java @@ -0,0 +1,173 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.codegen.java.util; + +import java.util.Arrays; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.stream.Collectors; + +public class ClassBuilder extends TypeBuilder +{ + protected String superclass; // null if none explicit + + protected final List ctors = new LinkedList<>(); + + // No name par because so far useful to start constructing before setting the name + public ClassBuilder() + { + + } + + public ClassBuilder(String name) + { + super(name); + } + + public void setSuperClass(String superc) + { + setterCheck(this.superclass); + this.superclass = superc; + } + + // Each par is the String: type + " " + name -- cf. MethodBuilder + public ConstructorBuilder newConstructor(String... pars) // FIXME: ConstructorBuilder + { + ConstructorBuilder mb = new ConstructorBuilder(this.name); + mb.addParameters(pars); + this.ctors.add(mb); + return mb; + } + + public MethodBuilder newMethod() + { + MethodBuilder mb = new MethodBuilder(); + this.methods.add(mb); + return mb; + } + + public final MethodBuilder newMethod(String name) + { + MethodBuilder mb = newMethod(); + mb.setName(name); + return mb; + } + + public final boolean hasMethodSignature(String ret, String... params) + { + for (MethodBuilder mb : this.methods) + { + if (mb.getReturn().equals(ret) && equalParamSigs(Arrays.asList(params), mb.getParameters())) + { + return true; + } + } + return false; + } + + // FIXME: factor out with TypeBuilder + //private static boolean equalParamSigs(MethodBuilder mb1, MethodBuilder mb2) + private static boolean equalParamSigs(List mb1, List mb2) + { + if (mb1.size() == 0) + { + if (mb2.size() != 0) + { + return false; + } + } + else + { + Iterator params2 = mb2.iterator(); + for (String param1 : mb1) + { + if (!params2.hasNext()) + { + return false; + } + String param2 = params2.next(); + + if (param2.contains("<")) + { + param2 = param2.substring(0, param2.indexOf("<")); + } + else + { + param2 = param2.substring(0, param2.indexOf(" ")); + } + if (param1.contains("<")) + { + param1 = param1.substring(0, param1.indexOf("<")); + } + else + { + param1 = param1.substring(0, param1.indexOf(" ")); + } + if (!param1.equals(param2)) + { + return false; + } + } + } + return true; + } + + @Override + protected String buildSignature(String clazz) + { + if (!this.mods.isEmpty()) + { + clazz += this.mods.stream().collect(Collectors.joining(" ")); + clazz += " "; + } + clazz += "class " + this.name; + if (!this.params.isEmpty()) + { + clazz += "<" + this.params.stream().collect(Collectors.joining(", ")) + ">"; + } + if (this.superclass != null) + { + clazz += " extends " + this.superclass; + } + if (!this.ifaces.isEmpty()) + { + clazz += " implements "; + clazz += this.ifaces.stream().collect(Collectors.joining(", ")); + } + return clazz; + } + + @Override + public String buildBody(String clazz) + { + clazz += " {"; + clazz = buildFields(clazz); + clazz = buildConstructors(clazz); + clazz = buildMethods(clazz); + clazz = buildMemberTypes(clazz); + clazz += "\n}"; + return clazz; + } + + protected String buildConstructors(String clazz) + { + if (!this.ctors.isEmpty()) + { + clazz += "\n\n"; + clazz += this.ctors.stream().map((mb) -> mb.build()).collect(Collectors.joining("\n\n")); + } + return clazz; + } +} diff --git a/scribble-codegen/src/main/java/org/scribble/codegen/java/util/ConstructorBuilder.java b/scribble-codegen/src/main/java/org/scribble/codegen/java/util/ConstructorBuilder.java new file mode 100644 index 000000000..19f5bc382 --- /dev/null +++ b/scribble-codegen/src/main/java/org/scribble/codegen/java/util/ConstructorBuilder.java @@ -0,0 +1,36 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.codegen.java.util; + +import org.scribble.util.RuntimeScribException; + +public class ConstructorBuilder extends MethodBuilder +{ + protected ConstructorBuilder(String name) + { + super(name); + } + + @Override + public void setName(String name) + { + throw new RuntimeScribException("Invalid for constructor"); + } + + @Override + public void setReturn(String ret) + { + throw new RuntimeScribException("Invalid for constructor"); + } +} \ No newline at end of file diff --git a/scribble-codegen/src/main/java/org/scribble/codegen/java/util/EnumBuilder.java b/scribble-codegen/src/main/java/org/scribble/codegen/java/util/EnumBuilder.java new file mode 100644 index 000000000..600237d1d --- /dev/null +++ b/scribble-codegen/src/main/java/org/scribble/codegen/java/util/EnumBuilder.java @@ -0,0 +1,119 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.codegen.java.util; + +import java.util.Arrays; +import java.util.LinkedList; +import java.util.List; +import java.util.stream.Collectors; + +import org.scribble.util.RuntimeScribException; + +public class EnumBuilder extends TypeBuilder +{ + private final List vals = new LinkedList(); + + protected EnumBuilder() + { + + } + + protected EnumBuilder(String name) + { + super(name); + } + + public void addValues(String... vals) + { + this.vals.addAll(Arrays.asList(vals)); + } + + @Override + public String build() + { + String enun = ""; + enun = buildSignature(enun); + enun += " {\n"; + enun += "\t" + this.vals.stream().collect(Collectors.joining(", ")); + enun += "\n}"; + return enun; + } + + @Override + protected String buildSignature(String enun) + { + if (!this.mods.isEmpty()) + { + enun += this.mods.stream().collect(Collectors.joining(" ")); + enun += " "; + } + enun += "enum " + this.name; + if (!this.ifaces.isEmpty()) + { + enun += " implements "; + enun += this.ifaces.stream().collect(Collectors.joining(", ")); + } + return enun; + } + + // Following not necessarily invalid for Java, just for this tool set + + @Override + public void setPackage(String packname) + { + throw new RuntimeScribException("Invalid for enums"); + } + + @Override + public void addImports(String... imports) + { + throw new RuntimeScribException("Invalid for enums"); + } + + @Override + public FieldBuilder newField(String name) + { + throw new RuntimeScribException("Invalid for enums"); + } + + @Override + public AbstractMethodBuilder newAbstractMethod() + { + throw new RuntimeScribException("Invalid for enums"); + } + + @Override + public ClassBuilder newTopLevelClass() + { + throw new RuntimeScribException("Invalid for enums"); + } + + @Override + protected String buildFields(String clazz) + { + throw new RuntimeScribException("Invalid for enums"); + } + + @Override + protected String buildMethods(String clazz) + { + throw new RuntimeScribException("Invalid for enums"); + } + + @Override + protected String buildMemberTypes(String clazz) + { + throw new RuntimeScribException("Invalid for enums"); + } +} diff --git a/scribble-codegen/src/main/java/org/scribble/codegen/java/util/FieldBuilder.java b/scribble-codegen/src/main/java/org/scribble/codegen/java/util/FieldBuilder.java new file mode 100644 index 000000000..720f5dfbf --- /dev/null +++ b/scribble-codegen/src/main/java/org/scribble/codegen/java/util/FieldBuilder.java @@ -0,0 +1,72 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.codegen.java.util; + +import java.util.Arrays; +import java.util.LinkedList; +import java.util.List; +import java.util.stream.Collectors; + +public class FieldBuilder extends JavaBuilder +{ + private List mods = new LinkedList<>(); + private String type; + private String expr; // null if none + + public FieldBuilder() + { + + } + + public FieldBuilder(String name) + { + super(name); + } + + public void addModifiers(String... mods) + { + this.mods.addAll(Arrays.asList(mods)); + } + + public void setType(String type) + { + setterCheck(this.type); + this.type = type; + } + + public void setExpression(String val) + { + setterCheck(this.expr); + this.expr = val; + } + + @Override + public String build() + { + String field = ""; + field += "\t"; + if (!this.mods.isEmpty()) + { + field += this.mods.stream().collect(Collectors.joining(" ")); + field += " "; + } + field += this.type + " " + this.name; + if (this.expr != null) + { + field += " = " + this.expr; + } + field += ";"; + return field; + } +} \ No newline at end of file diff --git a/scribble-codegen/src/main/java/org/scribble/codegen/java/util/InterfaceBuilder.java b/scribble-codegen/src/main/java/org/scribble/codegen/java/util/InterfaceBuilder.java new file mode 100644 index 000000000..80b3d7e1e --- /dev/null +++ b/scribble-codegen/src/main/java/org/scribble/codegen/java/util/InterfaceBuilder.java @@ -0,0 +1,86 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.codegen.java.util; + +import java.util.LinkedList; +import java.util.List; +import java.util.stream.Collectors; + +public class InterfaceBuilder extends TypeBuilder +{ + private List defaults = new LinkedList<>(); + + public InterfaceBuilder() + { + + } + + public InterfaceBuilder(String name) + { + super(name); + } + + public MethodBuilder newDefaultMethod() + { + MethodBuilder mb = new MethodBuilder(); + mb.addModifiers(JavaBuilder.DEFAULT); + this.defaults.add(mb); + return mb; + } + + public final MethodBuilder newDefaultMethod(String name) + { + MethodBuilder mb = newDefaultMethod(); + mb.setName(name); + return mb; + } + + public final List getDefaultMethods() + { + return this.defaults; + } + + @Override + protected String buildSignature(String clazz) + { + if (!this.mods.isEmpty()) + { + clazz += this.mods.stream().collect(Collectors.joining(" ")); + clazz += " "; + } + clazz += "interface " + this.name; + if (!this.params.isEmpty()) + { + clazz += "<" + this.params.stream().collect(Collectors.joining(", ")) + ">"; + } + if (!this.ifaces.isEmpty()) + { + clazz += " extends "; + clazz += this.ifaces.stream().collect(Collectors.joining(", ")); + } + return clazz; + } + + @Override + protected String buildMethods(String clazz) + { + clazz = super.buildMethods(clazz); + if (!this.defaults.isEmpty()) + { + clazz += "\n\n"; + clazz += this.defaults.stream().map((mb) -> mb.build()).collect(Collectors.joining("\n\n")); + } + return clazz; + } +} diff --git a/scribble-codegen/src/main/java/org/scribble/codegen/java/util/JavaBuilder.java b/scribble-codegen/src/main/java/org/scribble/codegen/java/util/JavaBuilder.java new file mode 100644 index 000000000..103958199 --- /dev/null +++ b/scribble-codegen/src/main/java/org/scribble/codegen/java/util/JavaBuilder.java @@ -0,0 +1,64 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.codegen.java.util; + +public abstract class JavaBuilder +{ + public static final String ABSTRACT = "abstract"; + public static final String DEFAULT = "default"; + public static final String VOID = "void"; + public static final String THIS = "this"; + public static final String SYNCHRONIZED = "synchronized"; + public static final String SUPER = "super"; + public static final String STATIC = "static"; + public static final String RETURN = "return"; + public static final String PUBLIC = "public"; + public static final String PROTECTED = "protected"; + public static final String PRIVATE = "private"; + public static final String NEW = "new"; + public static final String FINAL = "final"; + + protected String name; + + public JavaBuilder() + { + + } + + public JavaBuilder(String name) + { + this.name = name; + } + + public abstract String build(); + + public String getName() + { + return this.name; + } + + public void setName(String name) + { + setterCheck(this.name); + this.name = name; + } + + protected void setterCheck(String s) + { + if (s != null) + { + throw new RuntimeException("Value already set: " + s); + } + } +} diff --git a/scribble-codegen/src/main/java/org/scribble/codegen/java/util/MethodBuilder.java b/scribble-codegen/src/main/java/org/scribble/codegen/java/util/MethodBuilder.java new file mode 100644 index 000000000..a8e9e02b9 --- /dev/null +++ b/scribble-codegen/src/main/java/org/scribble/codegen/java/util/MethodBuilder.java @@ -0,0 +1,153 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.codegen.java.util; + +import java.util.Arrays; +import java.util.LinkedList; +import java.util.List; +import java.util.stream.Collectors; + +public class MethodBuilder extends JavaBuilder +{ + private final List annots = new LinkedList<>(); + private final List mods = new LinkedList<>(); + private String ret; // null for constructor -- void must be set explicitly + private final List pars = new LinkedList<>(); + private final List exceptions = new LinkedList<>(); + private final List body = new LinkedList<>(); + private final List typepars = new LinkedList<>(); // generic parameters + + protected MethodBuilder() + { + + } + + protected MethodBuilder(String name) + { + super(name); + } + + public void addAnnotations(String... mods) + { + this.annots.addAll(Arrays.asList(mods)); + } + + public void addModifiers(String... mods) + { + this.mods.addAll(Arrays.asList(mods)); + } + + public void setReturn(String ret) + { + setterCheck(this.ret); + this.ret = ret; + } + + public String getReturn() + { + return this.ret; + } + + // Each par is the String: type + " " + name + public void addParameters(String... par) + { + this.pars.addAll(Arrays.asList(par)); + } + + public List getParameters() + { + return this.pars; + } + + public void addTypeParameters(String... par) + { + this.typepars.addAll(Arrays.asList(par)); + } + + public List getTypeParameters() + { + return this.typepars; + } + + public void addExceptions(String... exceptions) + { + this.exceptions.addAll(Arrays.asList(exceptions)); + } + + public void addBodyLine(String ln) + { + this.body.add(ln); + } + + public final void addBodyLine(int i, String ln) + { + for (int j = 0; j < i; j++) + { + ln = "\t" + ln; + } + addBodyLine(ln); + } + + @Override + public String build() + { + String meth = ""; + meth = buildSignature(meth); + meth = buildBody(meth); + return meth; + } + + protected String buildSignature(String meth) + { + if (!this.annots.isEmpty()) + { + meth += "\t"; + meth += this.annots.stream().collect(Collectors.joining("\n\t")) + "\n"; + } + meth += "\t"; + if (!this.mods.isEmpty()) + { + meth += this.mods.stream().collect(Collectors.joining(" ")); + meth += " "; + } + if (!this.typepars.isEmpty()) + { + meth += "<" + this.typepars.stream().collect(Collectors.joining(", ")) + "> "; + } + if (this.ret != null) + { + meth += this.ret + " "; + } + meth += name + "("; + meth += this.pars.stream().collect(Collectors.joining(", ")); + meth += ")"; + if (!this.exceptions.isEmpty()) + { + meth += " throws " + this.exceptions.stream().collect(Collectors.joining(", ")); + } + return meth; + } + + protected String buildBody(String meth) + { + meth += " {\n"; + if (!this.body.isEmpty()) + { + meth += "\t\t"; + meth += this.body.stream().collect(Collectors.joining("\n\t\t")); + } + meth += "\n\t}"; + return meth; + } +} diff --git a/scribble-codegen/src/main/java/org/scribble/codegen/java/util/TypeBuilder.java b/scribble-codegen/src/main/java/org/scribble/codegen/java/util/TypeBuilder.java new file mode 100644 index 000000000..a2029706a --- /dev/null +++ b/scribble-codegen/src/main/java/org/scribble/codegen/java/util/TypeBuilder.java @@ -0,0 +1,275 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.codegen.java.util; + +import java.util.Arrays; +import java.util.Iterator; +import java.util.LinkedHashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.stream.Collectors; + +// An abstract type declaration builder +public abstract class TypeBuilder extends JavaBuilder +{ + protected String packname; // null for non- top-level type declaration + protected final LinkedHashSet imports = new LinkedHashSet<>(); + + protected final LinkedHashSet mods = new LinkedHashSet<>(); + protected final LinkedHashSet ifaces = new LinkedHashSet<>(); + protected final List params = new LinkedList<>(); + + protected final List fields = new LinkedList<>(); + protected final List methods = new LinkedList<>(); + + protected final List topLevelTypes = new LinkedList<>(); + protected final List memberTypes = new LinkedList<>(); + + // No name par because so far useful to start constructing before setting the name + public TypeBuilder() + { + + } + + public TypeBuilder(String name) + { + super(name); + } + + public void setPackage(String packname) + { + setterCheck(this.packname); + this.packname = packname; + } + + public void addImports(String... imports) + { + this.imports.addAll(Arrays.asList(imports)); + } + + public void addModifiers(String... mods) + { + this.mods.addAll(Arrays.asList(mods)); + } + + public void addInterfaces(String... ifaces) + { + this.ifaces.addAll(Arrays.asList(ifaces)); + } + + public List getInterfaces() + { + return new LinkedList<>(this.ifaces); + } + + public void addParameters(String... params) + { + this.params.addAll(Arrays.asList(params)); + } + + public List getParameters() + { + return this.params; + } + + public FieldBuilder newField(String name) + { + FieldBuilder fb = new FieldBuilder(); + fb.setName(name); + this.fields.add(fb); + return fb; + } + + public AbstractMethodBuilder newAbstractMethod() + { + AbstractMethodBuilder mb = new AbstractMethodBuilder(); + this.methods.add(mb); + return mb; + } + + public final AbstractMethodBuilder newAbstractMethod(String name) + { + AbstractMethodBuilder mb = newAbstractMethod(); + mb.setName(name); + return mb; + } + + // HACK: up to generic erasure + public final void checkDuplicateMethods(MethodBuilder mb) + { + List toRemove = new LinkedList<>(); + X: for (MethodBuilder tmp : this.methods) + { + if (!tmp.equals(mb) && tmp.getReturn().equals(mb.getReturn())) + { + if (tmp.getParameters().size() == 0) + { + if (mb.getParameters().size() != 0) + { + continue X; + } + } + else + { + Iterator mbparams = mb.getParameters().iterator(); + for (String tmpparam : tmp.getParameters()) + { + if (!mbparams.hasNext()) + { + continue X; + } + String mbparam = mbparams.next(); + + if (mbparam.contains("<")) + { + mbparam = mbparam.substring(0, mbparam.indexOf("<")); + } + else + { + mbparam = mbparam.substring(0, mbparam.indexOf(" ")); + } + if (tmpparam.contains("<")) + { + tmpparam = tmpparam.substring(0, tmpparam.indexOf("<")); + } + else + { + tmpparam = tmpparam.substring(0, tmpparam.indexOf(" ")); + } + if (!tmpparam.equals(mbparam)) + { + continue X; + } + } + } + toRemove.add(mb); + } + } + this.methods.removeAll(toRemove); + } + + public EnumBuilder newMemberEnum(String name) + { + EnumBuilder eb = new EnumBuilder(); + eb.setName(name); + this.memberTypes.add(eb); + return eb; + } + + // Name may not be suitable -- inner? + public ClassBuilder newMemberClass(String name) + { + ClassBuilder cb = new ClassBuilder(name); + this.memberTypes.add(cb); + return cb; + } + + // Name may not be suitable -- inner? + public InterfaceBuilder newMemberInterface(String name) + { + InterfaceBuilder ib = new InterfaceBuilder(name); + this.memberTypes.add(ib); + return ib; + } + + public ClassBuilder newTopLevelClass() + { + ClassBuilder cb = new ClassBuilder(); + this.topLevelTypes.add(cb); + return cb; + } + + // No validation here: javac is for that + @Override + public String build() + { + String clazz = ""; + clazz = buildHeader(clazz); + clazz = buildSignature(clazz); + clazz = buildBody(clazz); + clazz = buildTopLevelTypes(clazz); + return clazz; + } + + protected String buildBody(String clazz) + { + clazz += " {"; + clazz = buildFields(clazz); + clazz = buildMethods(clazz); + clazz = buildMemberTypes(clazz); + clazz += "\n}"; + return clazz; + } + + protected String buildHeader(String clazz) + { + if (this.packname != null) + { + clazz += "package " + packname + ";"; + } + if (!this.imports.isEmpty()) + { + clazz += "\n\nimport "; + clazz += this.imports.stream().collect(Collectors.joining(";\nimport ")); + clazz += ";"; + } + if (this.packname != null || !this.imports.isEmpty()) + { + clazz += "\n\n"; + } + return clazz; + } + + protected abstract String buildSignature(String clazz); + + protected String buildFields(String clazz) + { + if (!this.fields.isEmpty()) + { + clazz += "\n"; + clazz += this.fields.stream().map(fb -> fb.build()).collect(Collectors.joining("\n")); + } + return clazz; + } + + protected String buildMethods(String clazz) + { + if (!this.methods.isEmpty()) + { + clazz += "\n\n"; + clazz += this.methods.stream().map(mb -> mb.build()).collect(Collectors.joining("\n\n")); + } + return clazz; + } + + protected String buildMemberTypes(String clazz) + { + if (!this.memberTypes.isEmpty()) + { + clazz += "\n\n"; + clazz += this.memberTypes.stream().map(tb -> tb.build()).collect(Collectors.joining("\n\n")); + } + return clazz; + } + + protected String buildTopLevelTypes(String clazz) + { + if (!this.topLevelTypes.isEmpty()) + { + clazz += "\n\n"; + clazz += this.topLevelTypes.stream().map(tb -> tb.build()).collect(Collectors.joining("\n\n")); + } + return clazz; + } +} diff --git a/scribble-codegen/src/main/java/org/scribble/codegen/statetype/STActionBuilder.java b/scribble-codegen/src/main/java/org/scribble/codegen/statetype/STActionBuilder.java new file mode 100644 index 000000000..15107eb99 --- /dev/null +++ b/scribble-codegen/src/main/java/org/scribble/codegen/statetype/STActionBuilder.java @@ -0,0 +1,44 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.codegen.statetype; + +import org.scribble.core.model.endpoint.EState; +import org.scribble.core.model.endpoint.actions.EAction; + +public abstract class STActionBuilder +{ + public abstract String getActionName(STStateChanAPIBuilder api, EAction a); + public abstract String buildArgs(EAction a); + public abstract String buildBody(STStateChanAPIBuilder api, EState curr, EAction a, EState succ); + + public String getReturnType(STStateChanAPIBuilder api, EState curr, EState succ) + { + return api.getStateChanName(succ); + } + + public String buildReturn(STStateChanAPIBuilder api, EState curr, EState succ) + { + return api.buildActionReturn(this, curr, succ); + } + + public String build(STStateChanAPIBuilder api, EState curr, EAction a) + { + return api.buildAction(this, curr, a); // Because action builder hierarchy not suitable (extended by action kinds, not by target language) + } + + public String getStateChanType(STStateChanAPIBuilder api, EState curr, EAction a) + { + return api.getStateChanName(curr); + } +} diff --git a/scribble-codegen/src/main/java/org/scribble/codegen/statetype/STBranchActionBuilder.java b/scribble-codegen/src/main/java/org/scribble/codegen/statetype/STBranchActionBuilder.java new file mode 100644 index 000000000..6640af262 --- /dev/null +++ b/scribble-codegen/src/main/java/org/scribble/codegen/statetype/STBranchActionBuilder.java @@ -0,0 +1,19 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.codegen.statetype; + +public abstract class STBranchActionBuilder extends STActionBuilder +{ + +} diff --git a/scribble-codegen/src/main/java/org/scribble/codegen/statetype/STBranchStateBuilder.java b/scribble-codegen/src/main/java/org/scribble/codegen/statetype/STBranchStateBuilder.java new file mode 100644 index 000000000..a60e2a424 --- /dev/null +++ b/scribble-codegen/src/main/java/org/scribble/codegen/statetype/STBranchStateBuilder.java @@ -0,0 +1,37 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.codegen.statetype; + +import org.scribble.core.model.endpoint.EState; + +public abstract class STBranchStateBuilder extends STStateChanBuilder +{ + protected final STBranchActionBuilder bb; + + public STBranchStateBuilder(STBranchActionBuilder bb) + { + this.bb = bb; + } + + @Override + public String build(STStateChanAPIBuilder api, EState s) + { + String out = getPreamble(api, s); + + out += "\n\n"; + out += this.bb.build(api, s, s.getDetActions().get(1)); // Getting 1 checks non-unary + + return out; + } +} diff --git a/scribble-codegen/src/main/java/org/scribble/codegen/statetype/STCaseActionBuilder.java b/scribble-codegen/src/main/java/org/scribble/codegen/statetype/STCaseActionBuilder.java new file mode 100644 index 000000000..e9030d608 --- /dev/null +++ b/scribble-codegen/src/main/java/org/scribble/codegen/statetype/STCaseActionBuilder.java @@ -0,0 +1,19 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.codegen.statetype; + +public abstract class STCaseActionBuilder extends STActionBuilder +{ + +} diff --git a/scribble-codegen/src/main/java/org/scribble/codegen/statetype/STCaseBuilder.java b/scribble-codegen/src/main/java/org/scribble/codegen/statetype/STCaseBuilder.java new file mode 100644 index 000000000..76de329b9 --- /dev/null +++ b/scribble-codegen/src/main/java/org/scribble/codegen/statetype/STCaseBuilder.java @@ -0,0 +1,51 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.codegen.statetype; + +import org.scribble.core.model.endpoint.EState; +import org.scribble.core.model.endpoint.actions.EAction; +import org.scribble.core.model.endpoint.actions.ERecv; + +public abstract class STCaseBuilder extends STStateChanBuilder // Is a distinct type but not a state -- OK for now +{ + protected final STCaseActionBuilder cb; + + public STCaseBuilder(STCaseActionBuilder cb) + { + this.cb = cb; + } + + @Override + public String build(STStateChanAPIBuilder api, EState s) + { + String out = getPreamble(api, s); + + for (EAction a : s.getDetActions()) + { + out += "\n\n"; + if (a instanceof ERecv) // FIXME: factor out action kind + { + out += this.cb.build(api, s, a); + } + else + { + throw new RuntimeException("Shouldn't get in here: " + a); + } + } + + return out; + } + + public abstract String getCaseStateChanName(STStateChanAPIBuilder api, EState s); +} diff --git a/scribble-codegen/src/main/java/org/scribble/codegen/statetype/STEndStateBuilder.java b/scribble-codegen/src/main/java/org/scribble/codegen/statetype/STEndStateBuilder.java new file mode 100644 index 000000000..89abfb1c8 --- /dev/null +++ b/scribble-codegen/src/main/java/org/scribble/codegen/statetype/STEndStateBuilder.java @@ -0,0 +1,30 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.codegen.statetype; + +import org.scribble.core.model.endpoint.EState; + +public abstract class STEndStateBuilder extends STStateChanBuilder +{ + public STEndStateBuilder() + { + + } + + @Override + public String build(STStateChanAPIBuilder api, EState s) + { + return getPreamble(api, s); + } +} diff --git a/scribble-codegen/src/main/java/org/scribble/codegen/statetype/STOutputStateBuilder.java b/scribble-codegen/src/main/java/org/scribble/codegen/statetype/STOutputStateBuilder.java new file mode 100644 index 000000000..1f4a62ca2 --- /dev/null +++ b/scribble-codegen/src/main/java/org/scribble/codegen/statetype/STOutputStateBuilder.java @@ -0,0 +1,62 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.codegen.statetype; + +import org.scribble.core.model.endpoint.EState; +import org.scribble.core.model.endpoint.actions.EAction; +import org.scribble.core.model.endpoint.actions.EDisconnect; +import org.scribble.core.model.endpoint.actions.EReq; +import org.scribble.core.model.endpoint.actions.ESend; + +public abstract class STOutputStateBuilder extends STStateChanBuilder +{ + protected final STSendActionBuilder sb; + + public STOutputStateBuilder(STSendActionBuilder sb) + { + this.sb = sb; + } + + @Override + public String build(STStateChanAPIBuilder api, EState s) + { + String out = getPreamble(api, s); + /*"package " + getPackage(gpn) + + "\n" + + "type " + getSTStateName(gpn, role, s) + " struct{}";*/ + + for (EAction a : s.getDetActions()) + { + out += "\n\n"; + if (a instanceof ESend) // FIXME: factor out action kind + { + out += this.sb.build(api, s, a); + } + else if (a instanceof EReq) + { + throw new RuntimeException("TODO: " + a); + } + else if (a instanceof EDisconnect) + { + throw new RuntimeException("TODO: " + a); + } + else + { + throw new RuntimeException("Shouldn't get in here: " + a); + } + } + + return out; + } +} diff --git a/scribble-codegen/src/main/java/org/scribble/codegen/statetype/STReceiveActionBuilder.java b/scribble-codegen/src/main/java/org/scribble/codegen/statetype/STReceiveActionBuilder.java new file mode 100644 index 000000000..10d930ab3 --- /dev/null +++ b/scribble-codegen/src/main/java/org/scribble/codegen/statetype/STReceiveActionBuilder.java @@ -0,0 +1,19 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.codegen.statetype; + +public abstract class STReceiveActionBuilder extends STActionBuilder +{ + +} diff --git a/scribble-codegen/src/main/java/org/scribble/codegen/statetype/STReceiveStateBuilder.java b/scribble-codegen/src/main/java/org/scribble/codegen/statetype/STReceiveStateBuilder.java new file mode 100644 index 000000000..d18309954 --- /dev/null +++ b/scribble-codegen/src/main/java/org/scribble/codegen/statetype/STReceiveStateBuilder.java @@ -0,0 +1,45 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.codegen.statetype; + +import java.util.List; + +import org.scribble.core.model.endpoint.EState; +import org.scribble.core.model.endpoint.actions.EAction; + +public abstract class STReceiveStateBuilder extends STStateChanBuilder +{ + protected final STReceiveActionBuilder rb; + + public STReceiveStateBuilder(STReceiveActionBuilder rb) + { + this.rb = rb; + } + + @Override + public String build(STStateChanAPIBuilder api, EState s) + { + String out = getPreamble(api, s); + + List as = s.getDetActions(); + if (as.size() > 1) + { + throw new RuntimeException("Shouldn't get in here: " + as); + } + out += "\n\n"; + out += this.rb.build(api, s, as.get(0)); + + return out; + } +} diff --git a/scribble-codegen/src/main/java/org/scribble/codegen/statetype/STSendActionBuilder.java b/scribble-codegen/src/main/java/org/scribble/codegen/statetype/STSendActionBuilder.java new file mode 100644 index 000000000..39ccf481b --- /dev/null +++ b/scribble-codegen/src/main/java/org/scribble/codegen/statetype/STSendActionBuilder.java @@ -0,0 +1,19 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.codegen.statetype; + +public abstract class STSendActionBuilder extends STActionBuilder +{ + +} diff --git a/scribble-codegen/src/main/java/org/scribble/codegen/statetype/STStateChanAPIBuilder.java b/scribble-codegen/src/main/java/org/scribble/codegen/statetype/STStateChanAPIBuilder.java new file mode 100644 index 000000000..493429f30 --- /dev/null +++ b/scribble-codegen/src/main/java/org/scribble/codegen/statetype/STStateChanAPIBuilder.java @@ -0,0 +1,118 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.codegen.statetype; + +import java.util.HashMap; +import java.util.LinkedHashSet; +import java.util.Map; +import java.util.Set; + +import org.scribble.core.model.endpoint.EGraph; +import org.scribble.core.model.endpoint.EState; +import org.scribble.core.model.endpoint.actions.EAction; +import org.scribble.core.type.name.GProtoName; +import org.scribble.core.type.name.Role; +import org.scribble.job.Job; + +public abstract class STStateChanAPIBuilder +{ + public final Job job; + + public final GProtoName gpn; + public final Role role; + public final EGraph graph; + + public final STOutputStateBuilder ob; + public final STReceiveStateBuilder rb; + public final STBranchStateBuilder bb; + public final STCaseBuilder cb; + public final STEndStateBuilder eb; + + private Map names = new HashMap<>(); + + protected STStateChanAPIBuilder(Job job, GProtoName gpn, Role role, + EGraph graph, STOutputStateBuilder ob, STReceiveStateBuilder rb, + STBranchStateBuilder bb, STCaseBuilder cb, STEndStateBuilder eb) + { + this.job = job; + + this.gpn = gpn; + this.role = role; + this.graph = graph; + + this.ob = ob; + this.rb = rb; + this.bb = bb; + this.cb = cb; + this.eb = eb; + } + + public abstract Map buildSessionAPI(); // filepath -> source // FIXME: factor out + + public Map build() // filepath -> source + { + Map api = new HashMap<>(); + Set states = new LinkedHashSet<>(); + states.add(this.graph.init); + states.addAll(this.graph.init.getReachableStates()); + for (EState s : states) + { + switch (s.getStateKind()) + { + case ACCEPT: throw new RuntimeException("TODO"); + case OUTPUT: api.put(getFilePath(getStateChanName(s)), this.ob.build(this, s)); break; + case POLY_RECIEVE: + { + api.put(getFilePath(getStateChanName(s)), this.bb.build(this, s)); + api.put(getFilePath(this.cb.getCaseStateChanName(this, s)), this.cb.build(this, s)); // FIXME: factor out + break; + } + case TERMINAL: api.put(getFilePath(getStateChanName(s)), this.eb.build(this, s)); break; // FIXME: without subpackages, all roles share same EndSocket + case UNARY_RECEIVE: + { + api.put(getFilePath(getStateChanName(s)), this.rb.build(this, s)); + //api.put(getFilePath(getStateChanName(s) + "_Cases"), this.cb.build(this, s)); // FIXME: factor out + break; + } + case SERVER_WRAP: throw new RuntimeException("TODO"); + default: throw new RuntimeException("Shouldn't get in here: " + s); + } + } + return api; + } + + public abstract String getFilePath(String name); + + public abstract String getPackage(); + + public String getStateChanName(EState s) + { + String name = this.names.get(s.id); + if (name == null) + { + name = makeSTStateName(s); + this.names.put(s.id, name); + } + return name; + } + + // Should only be called from getSTStateName + protected abstract String makeSTStateName(EState s); + + public abstract String buildAction(STActionBuilder ab, EState curr, EAction a); + + public abstract String getChannelName(STStateChanAPIBuilder api, EAction a); + + public abstract String buildActionReturn(STActionBuilder ab, EState curr, EState succ); // FIXME: refactor action builders as interfaces and use generic parameter for kind +} diff --git a/scribble-codegen/src/main/java/org/scribble/codegen/statetype/STStateChanBuilder.java b/scribble-codegen/src/main/java/org/scribble/codegen/statetype/STStateChanBuilder.java new file mode 100644 index 000000000..aeca376a1 --- /dev/null +++ b/scribble-codegen/src/main/java/org/scribble/codegen/statetype/STStateChanBuilder.java @@ -0,0 +1,22 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.codegen.statetype; + +import org.scribble.core.model.endpoint.EState; + +public abstract class STStateChanBuilder +{ + public abstract String getPreamble(STStateChanAPIBuilder api, EState s); + public abstract String build(STStateChanAPIBuilder api, EState s); +} diff --git a/bundles/org.scribble.common/LICENSE.txt b/scribble-core/LICENSE.txt similarity index 100% rename from bundles/org.scribble.common/LICENSE.txt rename to scribble-core/LICENSE.txt diff --git a/scribble-core/pom.xml b/scribble-core/pom.xml new file mode 100644 index 000000000..8ca744096 --- /dev/null +++ b/scribble-core/pom.xml @@ -0,0 +1,26 @@ + + 4.0.0 + + + scribble-core + jar + + + + org.antlr + antlr-runtime + + + + + org.scribble + parent + 0.5.1-SNAPSHOT + ../pom.xml + + + + scribble-core + + diff --git a/scribble-core/src/main/java/org/scribble/core/job/Core.java b/scribble-core/src/main/java/org/scribble/core/job/Core.java new file mode 100644 index 000000000..33e3493ac --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/job/Core.java @@ -0,0 +1,726 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.job; + +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +import org.scribble.core.lang.global.GProtocol; +import org.scribble.core.lang.local.LProjection; +import org.scribble.core.model.ModelFactory; +import org.scribble.core.model.endpoint.EGraph; +import org.scribble.core.model.endpoint.EModelFactoryImpl; +import org.scribble.core.model.endpoint.EState; +import org.scribble.core.model.global.SGraph; +import org.scribble.core.model.global.SModelFactoryImpl; +import org.scribble.core.model.visit.local.NonDetPayChecker; +import org.scribble.core.type.kind.Global; +import org.scribble.core.type.kind.Local; +import org.scribble.core.type.name.ModuleName; +import org.scribble.core.type.name.ProtoName; +import org.scribble.core.type.name.Role; +import org.scribble.core.type.session.STypeFactory; +import org.scribble.core.type.session.global.GSeq; +import org.scribble.core.type.session.local.LSeq; +import org.scribble.core.visit.STypeVisitorFactory; +import org.scribble.core.visit.STypeVisitorFactoryImpl; +import org.scribble.core.visit.gather.ProtoDepsCollector; +import org.scribble.core.visit.gather.RoleGatherer; +import org.scribble.core.visit.global.GTypeVisitorFactoryImpl; +import org.scribble.core.visit.local.LDoPruner; +import org.scribble.core.visit.local.LRoleDeclAndDoArgPruner; +import org.scribble.core.visit.local.LTypeVisitorFactoryImpl; +import org.scribble.core.visit.local.SubprotoExtChoiceSubjFixer; +import org.scribble.util.ScribException; + + +// A "compiler job" front-end that supports operations comprising visitor passes over the AST and/or local/global models +public class Core +{ + public final CoreConfig config; // Immutable + + private final CoreContext context; // Mutable (Visitor passes replace modules) + + public Core(ModuleName mainFullname, Map args, + //Map modcs, + Set imeds, STypeFactory tf) + { + this.config = newCoreConfig(mainFullname, args, tf); + this.context = newCoreContext(//modcs, + imeds); // Single instance per Core and should never be shared + } + + protected STypeVisitorFactory newSTypeVisitorFactory() + { + return new STypeVisitorFactoryImpl(new GTypeVisitorFactoryImpl(), + new LTypeVisitorFactoryImpl()); + } + + protected ModelFactory newModelFactory() + { + return new ModelFactory(EModelFactoryImpl::new, + SModelFactoryImpl::new); + } + + // A Scribble extension should override newCoreConfig/Context/etc as appropriate + protected CoreConfig newCoreConfig(ModuleName mainFullname, + Map args, STypeFactory tf) + { + STypeVisitorFactory vf = newSTypeVisitorFactory(); + ModelFactory mf = newModelFactory(); + return new CoreConfig(mainFullname, args, tf, vf, mf); + // CHECKME: combine E/SModelFactory? + } + + // A Scribble extension should override newCoreConfig/Context/etc as appropriate + protected CoreContext newCoreContext(//Map modcs, + Set imeds) + { + return new CoreContext(this, //modcs, + imeds); + } + + public void runPasses() throws ScribException + { + // Passes populate JobContext on-demand by each individual getter + runSyntaxTransformPasses(); + runGlobalSyntaxWfPasses(); + runProjectionPasses(); // CHECKME: can try before validation (i.e., including syntactic WF), to promote greater tool feedback? (cf. CommandLine output "barrier") + runProjectionSyntaxWfPasses(); + runEfsmBuildingPasses(); // Currently, unfair-transform graph building must come after syntactic WF --- TODO fix graph building to prevent crash ? + runLocalModelCheckingPasses(); + runGlobalModelCheckingPasses(); + } + + // Populates JobContext -- although patten is to do on-demand via (first) getter, so (partially) OK to delay population + protected void runSyntaxTransformPasses() // No ScribException, no errors expected + { + verbosePrintPass("Inlining subprotocols for all globals..."); + for (ProtoName fullname : this.context.getParsedFullnames()) + { + GProtocol inlined = this.context.getInlined(fullname); + verbosePrintPass( + "Inlined subprotocols: " + fullname + "\n" + inlined); + } + + verbosePrintPass( + "Unfolding all recursions once for all inlined globals..."); + for (ProtoName fullname : this.context.getParsedFullnames()) + { + // TODO: currently, unfolded not actually stored by Context -- unfoldAllOnce repeated manually when needed, e.g., runSyntaxWfPasses + GProtocol unf = this.context.getOnceUnfolded(fullname); // CHECKME: twice unfolding? instead of "unguarded"-unfolding? + verbosePrintPass( + "Unfolded all recursions once: " + unf.fullname + "\n" + unf); + } + } + + protected void runGlobalSyntaxWfPasses() throws ScribException + { + verbosePrintPass( + "Checking for unused role decls on all inlined globals..."); + for (ProtoName fullname : this.context.getParsedFullnames()) + { + // CHECKME: relegate to "warning" ? -- some downsteam operations may depend on this though (e.g., graph building?) + Set used = this.context.getInlined(fullname).def + .gather(new RoleGatherer()::visit) + .collect(Collectors.toSet()); + Set unused = this.context.getIntermediate(fullname).roles + // imeds have original role decls (inlined's are pruned) + .stream().filter(x -> !used.contains(x)).collect(Collectors.toSet()); + if (!unused.isEmpty()) + { + throw new ScribException( + "Unused roles in " + fullname + ": " + unused); + } + } + + verbosePrintPass("Checking role enabling on all inlined globals..."); + for (ProtoName fullname : this.context.getParsedFullnames()) + { + GProtocol unf = this.context.getOnceUnfolded(fullname); + if (unf.isAux()) + { + continue; + } + unf.checkRoleEnabling(this); + //e.g., C->D captured under an A->B choice after unfolding, cf. bad.wfchoice.enabling.twoparty.Test01b; + // TODO: get unfolded from Context + } + + verbosePrintPass( + "Checking consistent external choice subjects on all inlined globals..."); + for (ProtoName fullname : this.context.getParsedFullnames()) + { + GProtocol inlined = this.context.getInlined(fullname); + if (inlined.isAux()) + { + continue; + } + inlined.checkExtChoiceConsistency(this); + } + + verbosePrintPass( + "Checking connectedness on all inlined globals..."); + for (ProtoName fullname : this.context.getParsedFullnames()) + { + GProtocol unf = this.context.getOnceUnfolded(fullname); + if (unf.isAux()) + { + continue; + } + unf.checkConnectedness(this, !unf.isExplicit()); + //e.g., rec X { connect A to B; continue X; } + } + } + + // Due to Projector not being a subprotocol visitor, so "external" subprotocols may not be visible in ModuleContext building for the projections of the current root Module + // SubprotocolVisitor it doesn't visit the target Module/ProtocolDecls -- that's why the old Projector maintained its own dependencies and created the projection modules after leaving a Do separately from SubprotocolVisiting + // So Projection should not be an "inlining" SubprotocolVisitor, it would need to be more a "DependencyVisitor" + protected void runProjectionPasses() // No ScribException, no errors expected + { + verbosePrintPass("Projecting all inlined globals..."); + for (ProtoName fullname : this.context.getParsedFullnames()) + { + GProtocol inlined = this.context.getInlined(fullname); + for (Role self : inlined.roles) + { + // pruneRecs already done (see runContextBuildingPasses) + // CHECKME: projection and inling commutative? + LProjection iproj = this.context.getProjectedInlined(inlined.fullname, + self); + verbosePrintPass("Projected inlined onto " + self + ": " + + inlined.fullname + "\n" + iproj); + } + } + + // Pre: inlined already projected -- used for Do projection + // N.B. no "fixing" passes done within here -- need breadth-first passes to be sequentialised for subproto visiting (see below) + verbosePrintPass("Projecting all intermediate globals..."); + for (ProtoName fullname : this.context.getParsedFullnames()) + { + GProtocol imed = this.context.getIntermediate(fullname); + for (Role self : imed.roles) + { + LProjection proj = this.context.getProjection(fullname, self); + verbosePrintPass("Projected intermediate onto " + self + ": " + + imed.fullname + "\n" + proj); + } + } + + verbosePrintPass("Pruning do-args on all projected intermediates..."); + LRoleDeclAndDoArgPruner v1 = this.config.vf.local.LDoArgPruner(this); // Reusable + List done1 = new LinkedList<>(); + for (ProtoName fullname : this.context.getParsedFullnames()) + { + GProtocol imed = this.context.getIntermediate(fullname); + for (Role self : imed.roles) + { + LProjection proj = this.context.getProjection(fullname, self); + LProjection fixed = (LProjection) proj.pruneRoleDeclsAndDoArgs(v1); // TODO: refactor as LProjection/LProto meth, cf. GProto + done1.add(fixed); // N.B. replaces existing projection + verbosePrintPass( + "Pruned do-args on projected intermediate: " + + fixed.fullname + ":\n" + fixed); + } + } + done1.forEach(x -> this.getContext().setProjection(x)); + // Update after all visited, to prevent visiting an already pruned projdecl from breaking the pruning of a subsequent one (e.g., mutually recursive proto refs) + + verbosePrintPass("Do-pruning all projected intermediates..."); + LDoPruner v2 = this.config.vf.local.LDoPruner(this); // Reusable + List done2 = new LinkedList<>(); + for (ProtoName fullname : this.context.getParsedFullnames()) + { + GProtocol imed = this.context.getIntermediate(fullname); + for (Role self : imed.roles) + { + LProjection proj = this.context.getProjection(fullname, self); + LProjection fixed = (LProjection) proj.pruneDos(v2); // TODO: refactor as LProjection/LProto meth, cf. GProto + done2.add(fixed); // N.B. replaces existing projection + verbosePrintPass( + "Do-pruned projected intermediate: " + + fixed.fullname + ":\n" + fixed); + } + } + done2.forEach(x -> this.getContext().setProjection(x)); + // Update after all visited, to prevent visiting an already pruned projdecl from breaking the pruning of a subsequent one (e.g., mutually recursive proto refs) + + verbosePrintPass( + "Fixing external choice subjects for all projected intermediates..."); + SubprotoExtChoiceSubjFixer v3 = this.config.vf.local + .SubprotoExtChoiceSubjFixer(this); // Reusable (via top-level visitProtocol) + for (ProtoName fullname : this.context.getParsedFullnames()) + { + GProtocol imed = this.context.getIntermediate(fullname); + for (Role self : imed.roles) + { + LProjection proj = this.context.getProjection(fullname, self); + LProjection fixed = (LProjection) proj.fixExtChoiceSubjs(v3); + this.context.setProjection(fixed); // N.B. replaces existing projection + verbosePrintPass( + "Fixed external choice subjects for projected intermediate: " + + fixed.fullname + ":\n" + fixed); + } + } + } + + // Pre: runGlobalSyntaxWfPasses + protected void runProjectionSyntaxWfPasses() throws ScribException + { + verbosePrintPass("Checking reachability on all projected inlineds..."); + for (ProtoName fullname : this.context.getParsedFullnames()) + { + GProtocol inlined = this.context.getInlined(fullname); + if (inlined.isAux()) // CHECKME: also check for aux? e.g., bad.reach.globals.gdo.Test01b + { + continue; + } + for (Role self : inlined.roles) + { + LProjection iproj = this.context.getProjectedInlined(fullname, self); + iproj.checkReachability(this); + } + } + } + + // Pre: runGlobalSyntaxWfPasses -- unfair EFSM building depends on WF (role enabling, e.g., bad.wfchoice.enabling.threeparty.Test02) for building algorithm to work... + // ...or patch unfair-transform graph building to not crash? + protected void runEfsmBuildingPasses() + { + verbosePrintPass("Building EFSMs for all projected inlineds..."); + for (ProtoName fullname : this.context.getParsedFullnames()) + { + GProtocol inlined = this.context.getInlined(fullname); + for (Role self : inlined.roles) + { + // Seems to be OK even if runSyntaxWfPasses does not succeed (cf. unfair transform) + EGraph graph = this.context.getEGraph(fullname, self); + verbosePrintPass("Built EFSM: " + inlined.fullname + "@" + self + + "\n" + graph.toDot()); + } + } + + if (!this.config.args.get(CoreArgs.FAIR)) + { + verbosePrintPass( + "Building \"unfair\" EFSMs for all projected inlineds..."); + for (ProtoName fullname : this.context.getParsedFullnames()) + { + GProtocol inlined = this.context.getInlined(fullname); + for (Role self : inlined.roles) + { + // Pre: runGlobalSyntaxWfPasses -- e.g., bad.wfchoice.enabling.threeparty.Test02 + EGraph graph = this.context.getUnfairEGraph(inlined.fullname, self); + verbosePrintPass("Built \"unfair\" EFSM: " + inlined.fullname + + "@" + self + ":\n" + graph.toDot()); + } + } + } + } + + protected void runLocalModelCheckingPasses() throws ScribException + { + verbosePrintPass("Checking non-deterministic messaging action payloads..."); + for (ProtoName fullname : this.context.getParsedFullnames()) + { + GProtocol inlined = this.context.getInlined(fullname); + if (inlined.isAux()) // CHECKME: also check for aux? e.g., bad.reach.globals.gdo.Test01b + { + continue; + } + for (Role self : inlined.roles) + { + EState init = this.context.getEGraph(fullname, self).init; + init.traverse(new NonDetPayChecker()); + } + } + } + + protected void runGlobalModelCheckingPasses() throws ScribException + { + verbosePrintPass("Building and checking global models from projected inlineds..."); // CHECKME: separate and move model building earlier? + // CHECKME: refactor more/whole validation into lang.GProtocol ? + for (ProtoName fullname : this.context.getParsedFullnames()) + { + if (this.context.getIntermediate(fullname).isAux()) + { + continue; + } + validateByScribble(fullname, true); + if (!this.config.args.get(CoreArgs.FAIR)) + { + //verbosePrintPass("Validating by Scribble with \"unfair\" output choices: " + fullname); + validateByScribble(fullname, false); // TODO: only need to check progress, not "full" validation + } + } + } + + protected void validateByScribble(ProtoName fullname, boolean fair) + throws ScribException + { + SGraph graph = fair + ? this.context.getSGraph(fullname) + : this.context.getUnfairSGraph(fullname); + if (this.config.args.containsKey(CoreArgs.VERBOSE)) + { + String dot = graph.init.toDot(); + String[] lines = dot.split("\\R"); + verbosePrintPass( + //"(" + fullname + ") Built global model...\n" + graph.init.toDot() + "\n(" + fullname + ") ..." + graph.states.size() + " states"); + "Built " + (!fair ? "\"unfair\" " : "") + "global model (" + + graph.states.size() + " states): " + fullname + "\n" + + ((lines.length > 50) // CHECKME: factor out constant? + ? "...[snip]... (model text over 50 lines, try -[u]model[png])" + : dot)); + } + + verbosePrintPass("Checking " + (!fair ? "\"unfair\" " : "") + + "global model: " + fullname); + this.config.mf.global.SModel(graph).validate(this); + } + + // Pre: checkWellFormedness + // TODO: refactor projection, choice-subj fixing, do-pruning, do-arg fixing, etc. fully to Job (and drop this.projs from here) + public Map, LProjection> getProjections( + ProtoName fullname, Role self) throws ScribException + { + Map, LProjection> res = new HashMap<>(); + //Set> nonprotos = new LinkedHashSet<>(); + LProjection root = this.context.getProjection(fullname, self); + + List> todo = new LinkedList<>(); + todo.add(root.fullname); + while (!todo.isEmpty()) + { + ProtoName pfullname = todo.remove(0); + LProjection proj = this.context.getProjection(pfullname); + res.put(pfullname, proj); + proj.def.gather(new ProtoDepsCollector()::visit).distinct() + .filter(x -> !res.containsKey(x) && !todo.contains(x)) + .forEachOrdered(x -> todo.add(x)); + /*proj.def.gather(new NonProtoDepsGatherer()::visit) + .forEachOrdered(x -> nonprotos.add(x));*/ + } + + /*if (!nonprotos.isEmpty()) + // CHECKME: best way to handle mixtured of proto and nonproto dependencies? + // nonprotos should refer to source global module? i.e., projection modules should import globals? maybe consistent with "projects" clause + { + throw new RuntimeException( + "[TODO] Non-proto dependencies: " + nonprotos + "\n\t" + root); + }*/ + return res; + } + + public CoreContext getContext() + { + return this.context; + } + + public boolean isVerbose() + { + return this.config.args.get(CoreArgs.VERBOSE); + } + + public void verbosePrintln(String s) + { + if (isVerbose()) + { + System.out.println(s); + } + } + + private void verbosePrintPass(String s) + { + verbosePrintln("\n[Core] " + s); + } + + public void warningPrintln(String s) + { + System.err.println("[Warning] " + s); + } +} + + + + + + + + + + + + + + + + + + + /*// TODO: deprecate, caller should go through config + // A Scribble extension should override newCoreConfig/Context/etc as appropriate + public SGraphBuilderUtil newSGraphBuilderUtil() + { + return this.config.mf.newSGraphBuilderUtil(); + }*/ + + /*// TODO: deprecate, caller should go through config // CHECKME: refactor more uniformly with mf.newSGraphBuilderUtil ? + // A Scribble extension should override newCoreConfig/Context/etc as appropriate + public EGraphBuilderUtil newEGraphBuilderUtil() + { + return new EGraphBuilderUtil(this.config.mf); + }*/ + + /*public Map generateSessionApi(GProtocolName fullname) throws ScribbleException + { + debugPrintPass("Running " + SessionApiGenerator.class + " for " + fullname); + SessionApiGenerator sg = new SessionApiGenerator(this, fullname); + Map map = sg.generateApi(); // filepath -> class source + return map; + } + + // FIXME: refactor an EndpointApiGenerator -- ? + public Map generateStateChannelApi(GProtocolName fullname, Role self, boolean subtypes) throws ScribbleException + { + /*if (this.jcontext.getEndpointGraph(fullname, self) == null) + { + buildGraph(fullname, self); + }* / + debugPrintPass("Running " + StateChannelApiGenerator.class + " for " + fullname + "@" + self); + StateChannelApiGenerator apigen = new StateChannelApiGenerator(this, fullname, self); + IOInterfacesGenerator iogen = null; + try + { + iogen = new IOInterfacesGenerator(apigen, subtypes); + } + catch (RuntimeScribbleException e) // FIXME: use IOInterfacesGenerator.skipIOInterfacesGeneration + { + //System.err.println("[Warning] Skipping I/O Interface generation for protocol featuring: " + fullname); + warningPrintln("Skipping I/O Interface generation for: " + fullname + "\n Cause: " + e.getMessage()); + } + // Construct the Generators first, to build all the types -- then call generate to "compile" all Builders to text (further building changes will not be output) + Map api = new HashMap<>(); // filepath -> class source // Store results? + api.putAll(apigen.generateApi()); + if (iogen != null) + { + api.putAll(iogen.generateApi()); + } + return api; + } + //*/ + + /* // TODO FIXME: refactor following methods (e.g., non-static?) + public static void validateBySpin(Core core, GProtoName fullname) + throws ScribException + { + CoreContext corec = core.getContext(); + GProtocol gpd = corec.getInlined(fullname); + + List rs = gpd.roles.stream() + .sorted(Comparator.comparing(Role::toString)) + .collect(Collectors.toList()); + + Set> mids = gpd.def.//getMessageIds(); + gather(new MessageIdGatherer()::visit) + .collect(Collectors.toSet()); + + //..........FIXME: get mids from SType, instead of old AST Collector + + String pml = ""; + pml += "mtype {" + mids.stream().map(mid -> mid.toString()) + .collect(Collectors.joining(", ")) + "};\n"; + + // TODO CHECKME: explicit ? + + pml += "\n"; + List pairs = new LinkedList<>(); + for (Role r1 : rs) + { + for (Role r2 : rs) + { + if (!r1.equals(r2)) + { + pairs.add(new Role[] {r1, r2}); + } + } + } + //for (Role[] p : (Iterable) () -> pairs.stream().sorted().iterator()) + for (Role[] p : pairs) + { + pml += "chan s_" + p[0] + "_" + p[1] + " = [1] of { mtype };\n" + + "chan r_" + p[0] + "_" + p[1] + " = [1] of { mtype };\n" + + "bool empty_" + p[0] + "_" + p[1] + " = true;\n" + + "active proctype chan_" + p[0] + "_" + p[1] + "() {\n" + + "mtype m;\n" + + "end_chan_" + p[0] + "_" + p[1] + ":\n" + + "do\n" + + "::\n" + + "atomic { s_" + p[0] + "_" + p[1] + "?m; empty_" + p[0] + "_" + p[1] + + " = false }\n" + + "atomic { r_" + p[0] + "_" + p[1] + "!m; empty_" + p[0] + "_" + p[1] + + " = true }\n" + + "od\n" + + "}\n"; + } + + for (Role r : rs) + { + pml += "\n\n" + corec.getEGraph(fullname, r).toPml(r); + } + if (core.config.args.get(CoreArgs.VERBOSE)) + { + System.out.println("[-spin]: Promela processes\n" + pml + "\n"); + } + + List clauses = new LinkedList<>(); + for (Role r : rs) + { + Set tmp = new HashSet<>(); + EGraph g = corec.getEGraph(fullname, r); + tmp.add(g.init); + tmp.addAll(g.init.getReachableStates()); + if (g.term != null) + { + tmp.remove(g.term); + } + tmp.forEach( // Throws exception, cannot use flatMap + s -> clauses.add("!<>[]" + r + "@label" + r + s.id) // FIXME: factor out + ); + } + // * / + /*String roleProgress = ""; // This way is not faster + for (Role r : rs) + { + Set tmp = new HashSet<>(); + EGraph g = jc.getEGraph(fullname, r); + tmp.add(g.init); + tmp.addAll(MState.getReachableStates(g.init)); + if (g.term != null) + { + tmp.remove(g.term); + } + roleProgress += (((roleProgress.isEmpty()) ? "" : " || ") + + tmp.stream().map(s -> r + "@label" + r + s.id).collect(Collectors.joining(" || "))); + } + roleProgress = "!<>[](" + roleProgress + ")"; + clauses.add(roleProgress);* / + String eventualStability = ""; + for (Role[] p : pairs) + { + //eventualStability += (((eventualStability.isEmpty()) ? "" : " && ") + "empty_" + p[0] + "_" + p[1]); + eventualStability += (((eventualStability.isEmpty()) ? "" : " && ") + "<>empty_" + p[0] + "_" + p[1]); + } + //eventualStability = "[]<>(" + eventualStability + ")"; + eventualStability = "[](" + eventualStability + ")"; // FIXME: current "eventual reception", not eventual stability + clauses.add(eventualStability); + + //int batchSize = 10; // FIXME: factor out + int batchSize = 6; // FIXME: factor out // FIXME: dynamic batch sizing based on previous batch duration? + for (int i = 0; i < clauses.size(); ) + { + int j = (i+batchSize < clauses.size()) ? i+batchSize : clauses.size(); + String batch = clauses.subList(i, j).stream().collect(Collectors.joining(" && ")); + String ltl = "ltl {\n" + batch + "\n" + "}"; + if (core.config.args.get(CoreArgs.VERBOSE)) + { + System.out.println("[-spin] Batched ltl:\n" + ltl + "\n"); + } + if (!GProtocol.runSpin(fullname.toString(), pml + "\n\n" + ltl)) + { + throw new ScribException("Protocol not valid:\n" + gpd); + } + i += batchSize; + } + } + + // TODO:: relocate (also Context.runAut) + public static boolean runSpin(String prefix, String pml) //throws ScribbleException + { + File tmp; + try + { + tmp = File.createTempFile(prefix, ".pml.tmp"); + try + { + String tmpName = tmp.getAbsolutePath(); + ScribUtil.writeToFile(tmpName, pml); + String[] res = ScribUtil.runProcess("spin", "-a", tmpName); + res[0] = res[0].replaceAll("(?m)^ltl.*$", ""); + res[1] = res[1].replace( + "'gcc-4' is not recognized as an internal or external command,\noperable program or batch file.", + ""); + res[1] = res[1].replace( + "'gcc-3' is not recognized as an internal or external command,\noperable program or batch file.", + ""); + res[0] = res[0].trim(); + res[1] = res[1].trim(); + if (!res[0].trim().isEmpty() || !res[1].trim().isEmpty()) + { + //throw new RuntimeException("[scrib] : " + Arrays.toString(res[0].getBytes()) + "\n" + Arrays.toString(res[1].getBytes())); + throw new RuntimeException("[-spin] [spin]: " + res[0] + "\n" + res[1]); + } + int procs = 0; + for (int i = 0; i < pml.length(); procs++) + { + i = pml.indexOf("proctype", i); + if (i == -1) + { + break; + } + i++; + } + int dnfair = (procs <= 6) ? 2 : 3; // FIXME + res = ScribUtil.runProcess("gcc", "-o", "pan", "pan.c", "-DNFAIR=" + dnfair); + res[0] = res[0].trim(); + res[1] = res[1].trim(); + if (!res[0].isEmpty() || !res[1].isEmpty()) + { + throw new RuntimeException("[-spin] [gcc]: " + res[0] + "\n" + res[1]); + } + res = ScribUtil.runProcess("pan", "-a", "-f"); + res[1] = res[1].replace("warning: no accept labels are defined, so option -a has no effect (ignored)", ""); + res[0] = res[0].trim(); + res[1] = res[1].trim(); + if (res[0].contains("error,") || !res[1].isEmpty()) + { + throw new RuntimeException("[-spin] [pan]: " + res[0] + "\n" + res[1]); + } + int err = res[0].indexOf("errors: "); + boolean valid = (res[0].charAt(err + 8) == '0'); + if (!valid) + { + System.err.println("[-spin] [pan] " + res[0] + "\n" + res[1]); + } + return valid; + } + catch (ScribException e) + { + throw new RuntimeException(e); + } + finally + { + tmp.delete(); + } + } + catch (IOException e) + { + throw new RuntimeException(e); + } + } + //*/ \ No newline at end of file diff --git a/scribble-core/src/main/java/org/scribble/core/job/CoreArgs.java b/scribble-core/src/main/java/org/scribble/core/job/CoreArgs.java new file mode 100644 index 000000000..562ab28cb --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/job/CoreArgs.java @@ -0,0 +1,54 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.job; + +public enum CoreArgs +{ + VERBOSE, + FAIR, + SPIN, + NO_VALIDATION, + NO_PROGRESS, // TODO: deprecate + MIN_EFSM, // Currently only affects EFSM output (i.e. -fsm, -dot) and API gen -- doesn't affect model checking + + OLD_WF, // TODO: deprecate + NO_LCHOICE_SUBJ_CHECK, // For debugging only? + NO_ACC_CORRELATION_CHECK, // Currently unused + ; + + /*public final boolean debug; + public final boolean useOldWf; + public final boolean noProgress; // TODO: deprecate + public final boolean minEfsm; // Currently only affects EFSM output (i.e. -fsm, -dot) and API gen -- doesn't affect model checking + public final boolean fair; + public final boolean noLocalChoiceSubjectCheck; + public final boolean noAcceptCorrelationCheck; // Currently unused + public final boolean noValidation; + public final boolean spin; + +//boolean debug, boolean useOldWF, boolean noLiveness, boolean minEfsm, boolean fair, boolean noLocalChoiceSubjectCheck, boolean noAcceptCorrelationCheck, boolean noValidation, boolean spin + public LangArgs(Set args) + { + this.debug = debug; + this.useOldWf = useOldWf; + this.noProgress = noLiveness; + this.minEfsm = minEfsm; + this.fair = fair; + this.noLocalChoiceSubjectCheck = noLocalChoiceSubjectCheck; + this.noAcceptCorrelationCheck = noAcceptCorrelationCheck; + this.noValidation = noValidation; + this.spin = spin; + }*/ + +} diff --git a/scribble-core/src/main/java/org/scribble/core/job/CoreConfig.java b/scribble-core/src/main/java/org/scribble/core/job/CoreConfig.java new file mode 100644 index 000000000..4551274cd --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/job/CoreConfig.java @@ -0,0 +1,44 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.job; + +import java.util.Collections; +import java.util.Map; + +import org.scribble.core.model.ModelFactory; +import org.scribble.core.type.name.ModuleName; +import org.scribble.core.type.session.STypeFactory; +import org.scribble.core.visit.STypeVisitorFactory; + +// The "static" (constant) info for Jobs -- cf. JobContext "dynamic" state +public class CoreConfig +{ + public final ModuleName main; // Full name + public final Map args; // CHECKME: verbose/debug printing parameter ? + + public final STypeFactory tf; + public final STypeVisitorFactory vf; + public final ModelFactory mf; + + // N.B. MainContext is in a different non-visible (by Maven) package + public CoreConfig(ModuleName main, Map args, + STypeFactory tf, STypeVisitorFactory vf, ModelFactory mf) + { + this.main = main; + this.args = Collections.unmodifiableMap(args); + this.tf = tf; + this.vf = vf; + this.mf = mf; + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/job/CoreContext.java b/scribble-core/src/main/java/org/scribble/core/job/CoreContext.java new file mode 100644 index 000000000..596b32af4 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/job/CoreContext.java @@ -0,0 +1,386 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.job; + +import java.io.File; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +import org.scribble.core.lang.global.GProtocol; +import org.scribble.core.lang.local.LProjection; +import org.scribble.core.model.endpoint.AutGraphParser; +import org.scribble.core.model.endpoint.EGraph; +import org.scribble.core.model.endpoint.EState; +import org.scribble.core.model.global.SGraph; +import org.scribble.core.model.global.SGraphBuilder; +import org.scribble.core.type.kind.Global; +import org.scribble.core.type.kind.Local; +import org.scribble.core.type.name.GProtoName; +import org.scribble.core.type.name.LProtoName; +import org.scribble.core.type.name.ProtoName; +import org.scribble.core.type.name.Role; +import org.scribble.core.visit.global.GTypeInliner; +import org.scribble.core.visit.global.GTypeUnfolder; +import org.scribble.core.visit.global.InlinedProjector; +import org.scribble.util.Pair; +import org.scribble.util.ScribException; +import org.scribble.util.ScribUtil; + +// Global "static" context information for a Job -- single instance per Job, should not be shared between Jobs +// Mutable: projections, graphs, etc are added mutably later -- replaceModule also mutable setter -- "users" get this from the Job and expect to setter mutate "in place" +public class CoreContext +{ + private final Core core; + + // Keys are full names + // CHECKME: not currently used by core? -- core fully independent of modules, etc., because full disamb already done? (by imed translation) + //private final Map modcs; + + // "Directly" translated global protos, i.e., separate proto decls without any inlining/unfolding/etc + // Protos retain original decl role list (and args) + // Keys are full names (though GProtocol already includes full name) -- parameterised name mainly tracks back to Do.proto not being "specialised" + private final Map, GProtocol> imeds; + + // N.B. protos have pruned role decls -- CHECKME: prune args? + // Mods are preserved + // Keys are full names + private final Map, GProtocol> inlined = new HashMap<>(); + private final Map, GProtocol> unfs = new HashMap<>(); + + // CHECKME: rename projis? + private final Map, LProjection> iprojs = new HashMap<>(); // Projected from inlined; keys are full names + + // CHECKME: refactor to Job ? + // Projected from intermediates + // N.B. unlike iprojs, initial projections not pruned/fixed at all -- do-arg pruning, do-pruning, ext-choice-subj fixing all done incrementally + // LProtocolName is the full local protocol name (module name is the prefix) // LProtocolName key is LProtocol value fullname (i.e., redundant) + private final Map, LProjection> projs = new HashMap<>(); + // FIXME: choice-subj fixing, do-pruning -- factor out to Job and do there via AstVisitor? -- make testing compare the two sides + // TODO: refactor projection, choice-subj fixing, do-pruning, do-arg fixing, etc. fully to Job (and drop this.projs from here) + + // Built from projected inlined + private final Map, EGraph> fEGraphs = new HashMap<>(); + private final Map, EGraph> uEGraphs = new HashMap<>(); + private final Map, EGraph> mEGraphs = new HashMap<>(); + // Toolchain currently depends on single instance of each graph (state id equality), e.g. cannot re-build or re-minimise, would not be the same graph instance + // FIXME: currently only minimising "fair" graph, need to consider minimisation orthogonally to fairness -- NO: minimising (of fair) is for API gen only, unfair-transform does not use minimisation (regardless of user flag) for WF + + private final Map, SGraph> fSGraphs = new HashMap<>(); + private final Map, SGraph> uSGraphs = new HashMap<>(); + + protected CoreContext(Core core, //Map modcs, + Set imeds) + { + this.core = core; + //this.modcs = Collections.unmodifiableMap(modcs); + this.imeds = imeds.stream() + .collect(Collectors.toMap(x -> x.fullname, x -> x)); + } + + // Used by Core for pass running + // Safer to return names and require user to get the target value by name, to make sure the value is created + public Set> getParsedFullnames() + { + return this.imeds.keySet().stream().collect(Collectors.toSet()); + } + + /*// Pre: getProjectedInlined done for all... -- or directly derive these from the global names? + // N.B. uses this.*i*projs (more "important" than this.projs?) + public Set getProjectedFullnames() + { + return this.iprojs.keySet().stream().collect(Collectors.toSet()); + }*/ + + public GProtocol getIntermediate(ProtoName fullname) + { + return this.imeds.get(fullname); + } + + /*// OK for prevoius CoreContext with more basic getters/setters -- now values created on-demand by individual getters, so a collective getter is less suitable + public Set getIntermediates() + { + return this.imeds.values().stream().collect(Collectors.toSet()); + }*/ + + public GProtocol getInlined(ProtoName fullname) + { + GProtocol inlined = this.inlined.get(fullname); + if (inlined == null) + { + GTypeInliner v = this.core.config.vf.global.GTypeInliner(this.core); // Factor out? + inlined = this.imeds.get(fullname).getInlined(v); // Protocol.getInlined does pruneRecs + addInlined(fullname, inlined); + } + return inlined; + } + + protected void addInlined(ProtoName fullname, GProtocol g) + { + this.inlined.put(fullname, g); + } + + /*// OK for prevoius CoreContext with more basic getters/setters -- now values created on-demand by individual getters, so a collective getter is less suitable + public Set getInlineds() + { + return this.inlined.values().stream().collect(Collectors.toSet()); + }*/ + + public GProtocol getOnceUnfolded(ProtoName fullname) + { + GProtocol unf = this.unfs.get(fullname); + if (unf == null) + { + GTypeUnfolder v = this.core.config.vf.global.GTypeUnfolder(this.core); + unf = this.inlined.get(fullname).unfoldAllOnce(v); // Protocol.getInlined does pruneRecs + addOnceUnfolded(fullname, unf); + } + return unf; + } + + protected void addOnceUnfolded(ProtoName fullname, GProtocol g) + { + this.unfs.put(fullname, g); + } + + // Projected from inlined + public LProjection getProjectedInlined(ProtoName fullname, Role self) + { + LProtoName projFullname = InlinedProjector.getFullProjectionName(fullname, + self); + LProjection iproj = this.iprojs.get(projFullname); + if (iproj == null) + { + iproj = getInlined(fullname).projectInlined(this.core, self); + addProjectedInlined(iproj); + } + return iproj; + } + + /*public LProjection getProjectedInlined(LProtoName fullname) + { + LProjection iproj = this.iprojs.get(fullname); + if (iproj == null) + { + // FIXME: need global inlined to build (reverse derive from fullname?) + throw new RuntimeException("[TODO]: " + fullname); + } + return iproj; + }*/ + + /*// OK for prevoius CoreContext with more basic getters/setters -- now values created on-demand by individual getters, so a collective getter is less suitable + public Map getProjectedInlineds() + { + return Collections.unmodifiableMap(this.iprojs); + } + //*/ + + protected void addProjectedInlined(LProjection iproj) + { + this.iprojs.put(iproj.fullname, iproj); + } + + // Projected from intermediate + // Core gives LProjection -- projection Modules should be by Job + public LProjection getProjection(ProtoName fullname, Role self) + { + LProtoName projFullname = InlinedProjector.getFullProjectionName(fullname, + self); + LProjection proj = this.projs.get(projFullname); + if (proj == null) + { + proj = getIntermediate(fullname).project(this.core, self); + addProjection(proj); + } + return proj; + } + + // Pre: addProjectedInlined (i.e., getProjection(ProtoName, Role)) + public LProjection getProjection(ProtoName fullname) + { + LProjection proj = this.projs.get(fullname); + if (proj == null) + { + // FIXME: need global imed to build (reverse derive from fullname?) + throw new RuntimeException("[TODO]: " + fullname); + } + return proj; + } + + protected void addProjection(LProjection proj) + { + this.projs.put(proj.fullname, proj); + } + + // N.B. mutates this.projected -- used by "fixing" passes + // TODO refactor (overall, into Job) + public void setProjection(LProjection proj) + { + this.projs.put(proj.fullname, proj); + } + + // N.B. graphs built from inlined (not unfolded) + public EGraph getEGraph(ProtoName fullname, Role self) + { + LProtoName projFullname = InlinedProjector.getFullProjectionName(fullname, self); + EGraph graph = this.fEGraphs.get(projFullname); + if (graph == null) + { + LProjection inlined = getProjectedInlined(fullname, self); + graph = inlined.toEGraph(this.core); + addEGraph(inlined.fullname, graph); // inlined.fullname.equals(projFullname) + } + return graph; + } + + protected void addEGraph(ProtoName fullname, EGraph graph) + { + this.fEGraphs.put(fullname, graph); + } + + // Pre: Core.runSyntacticWfPasses + public EGraph getUnfairEGraph(ProtoName fullname, Role role) + { + return getUnfairEGraph( + InlinedProjector.getFullProjectionName(fullname, role)); + } + + // Pre: Core.runSyntacticWfPasses + // Pre: getEGraph(Global, Role) -- currently (CHECKME: revise ?) + public EGraph getUnfairEGraph(ProtoName fullname) + { + EGraph unfair = this.uEGraphs.get(fullname); + if (unfair == null) + { + EGraph fair = this.fEGraphs.get(fullname); // Getting fair EGraph directly by projected fullname (cf. getEGraph(GProtoName, Role)) + if (fair == null) + { + throw new RuntimeException( + "Call getEGraph(Global, Role) before getUnfairEGraph: " + fullname); + // CHECKME: refactor ? + } + Pair p = fair.init.unfairTransform(this.core.config.mf); //.toGraph(); + unfair = new EGraph(p.left, p.right); + addUnfairEGraph(fullname, unfair); + } + return unfair; + } + + protected void addUnfairEGraph(ProtoName fullname, EGraph graph) + { + this.uEGraphs.put(fullname, graph); + } + + public SGraph getSGraph(ProtoName fullname) throws ScribException + { + SGraph graph = this.fSGraphs.get(fullname); + if (graph == null) + { + Map egraphs = getEGraphsForSGraphBuilding(fullname, true); + boolean explicit = this.imeds.get(fullname).isExplicit(); + GProtoName cast = (GProtoName) fullname; // Could also reconstruct if really needed + graph = new SGraphBuilder(this.core).build(egraphs, explicit, cast); + addSGraph(fullname, graph); + } + return graph; + } + + private Map getEGraphsForSGraphBuilding( + ProtoName fullname, boolean fair) throws ScribException + { + Map egraphs = new HashMap<>(); + for (Role self : this.imeds.get(fullname).roles) + { + egraphs.put(self, fair + ? getEGraph(fullname, self) + : getUnfairEGraph(fullname, self)); + } + return egraphs; + } + + protected void addSGraph(ProtoName fullname, SGraph graph) + { + this.fSGraphs.put(fullname, graph); + } + + public SGraph getUnfairSGraph(ProtoName fullname) throws ScribException + { + SGraph graph = this.uSGraphs.get(fullname); + if (graph == null) + { + Map egraphs = getEGraphsForSGraphBuilding(fullname, false); + boolean explicit = this.imeds.get(fullname).isExplicit(); + GProtoName cast = (GProtoName) fullname; // Could also reconstruct if really needed + graph = new SGraphBuilder(this.core).build(egraphs, explicit, cast); + addUnfairSGraph(fullname, graph); + } + return graph; + } + + protected void addUnfairSGraph(ProtoName fullname, SGraph graph) + { + this.uSGraphs.put(fullname, graph); + } + + public EGraph getMinimisedEGraph(ProtoName fullname, Role role) + throws ScribException + { + LProtoName fulllpn = InlinedProjector.getFullProjectionName(fullname, role); + + EGraph minimised = this.mEGraphs.get(fulllpn); + if (minimised == null) + { + String aut = runAut(getEGraph(fullname, role).init.toAut(), + fulllpn + ".aut"); + minimised = new AutGraphParser(this.core).parse(aut); + addMinimisedEGraph(fulllpn, minimised); + } + return minimised; + } + + protected void addMinimisedEGraph(ProtoName fullname, EGraph graph) + { + this.mEGraphs.put(fullname, graph); + } + + // TODO: relocate + // Duplicated from CommandLine.runDot -- TODO: update to use createTmpFile (cf. runDot) + // Minimises the FSM up to bisimulation + // N.B. ltsconvert will typically re-number the states + private static String runAut(String fsm, String aut) throws ScribException + { + String tmpName = aut + ".tmp"; + File tmp = new File(tmpName); + if (tmp.exists()) // Factor out with CommandLine.runDot (file exists check) + { + throw new RuntimeException("Cannot overwrite: " + tmpName); + } + try + { + ScribUtil.writeToFile(tmpName, fsm); + String[] res = ScribUtil.runProcess("ltsconvert", "-ebisim", "-iaut", + "-oaut", tmpName); + if (!res[1].isEmpty()) + { + throw new RuntimeException(res[1]); + } + return res[0]; + } + finally + { + tmp.delete(); + } + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/job/Todo.java b/scribble-core/src/main/java/org/scribble/core/job/Todo.java new file mode 100644 index 000000000..54f105e3d --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/job/Todo.java @@ -0,0 +1,181 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.job; + + +// FIXME: project modifiers? + + +// Generally: need framework to correlate source AST nodes to canonical/inlined/unfolded representations, so that analyses can do done on representations and corresponding transformations applied on the AST +// e.g. keep a point to the corresponding original AST node in the cloned AST being visited +// via del may be good -- ASTs are always cloned, but same del can be inherited + + +//.. consider a "less expressive" version of subprotocol declaration that does not allow same rec labels for "non-compatible" states after inlining/unfolding (not sure how to compute though) +// -- i.e. limit subprotocols to corresponds to standard rec-continue structure +// -- this is a limitation of relying on protocol name + role arg config as ("unique") state identifiers +// -- No? recursive subprotocols should inherently be same as standard rec-continue? -- maybe non-unfiorm rec naming scheme is fine (use inner most?), and just graph building is wrong? +// -- FIXED: was a graph building problem + + +//.. Global model WF +// +//.. analyse inlined unfolded for max buffer size -- no: one-slot buffer seems sufficient, given located choice +//.. add term branches for infinite loops (termination hack), for checking mixed finite and infinite role behaviours (see Test.scr **TERM) +//.. don't need termination hack, just need to cut off state building on bad states -- no: it's needed (buffered message may be blocked now but valid later), or a terminal set analysis +//.. choice subject enabling needed for non-mixed states (inherently relevant to deadlock) -- although for one-slot asynchrony to work, it's just the A->B constructor: there's always syntactically at least one receiver, and any potential deadlock between parallel senders due to bounded buffer will be caught as the counterpart paralel receiver deadlock +//.. check role-based starvation/liveness (loop hack) -- no: terminal set analysis +//.. refactor orphans as generalised message liveness? though orphans are more natural as a termination/deadlock property? +//.. reconsider liveness loop hack (subsumes safety?) +//.. +//.. "introduces" should just work (dynamically add/remove buffer structures) -- no: that's connectedness, introduces on top? (should still be a finite state space extension) +//.. +//.. multicast: generalise model actions -- but how about asynchrony? introduce output buffers? -- output/input buffer intuition for "single-step" asynchrony +//.. +//.. model checked assertion annotations -- and API gen +// +//.. global model actions +//.. error state traces (and error process system) +//.. check junit harness and unit tests, add new tests +//.. CL ouput even if ScribbleException +//.. option to return all errors or just the first +// +//.. integrate reachability check and graph building? or move reachability earlier? EFSM building now done before reachability pass +// +//.. move connectedness checks into model checking, rather than syntactic + + +// FIXME: ambiguous choice subject (i.e. > 1 candidate) is checked subsequently by ProjectedChoiceSubjectFixer -- should be better integrated (e.g. reuse ChoiceUnguardedSubprotocolChecker, rather than adhoc LInteractionNode.inferLocalChoiceSubject) -- NOTE: but cannot do all pruning and fixing in one pass, as fixing the subject roles here will interfere with the pruning algorithm (currently it looks for dummy role choices) +//.. "semantic" test suite: e.g. looking for duplicate tests by global model +//.. subcategorise tests by number of roles + + +/* +.. disallow self comm +.. check role decl used +.. test mvn install +.. fix script +.. individual test ignores (cf. whole directory) -- good for package testing + +.. unguarded choice-rec in conjunction with unguarded continue needs to be ruled out in WF or fixed in FSM generation +*/ + + // FIXME: refactor EnvVisitors merge/compose routines -- check enter/leave merging isn't duplicating parent info (e.g. path visiting, recursion has to clear Env so child paths don't start with parent prefixes) + + // default G/LNode getKind methods won't work properly until Eclipse updated with fix, cf. G/LInteractionSeq + + // FIXME: protocoldecl header to check used roles (so projection roledecl filtering doesn't give empty roledecllist -- relax to check only that at least 1 or 2 roles are used?) -- should be checked wrt. role occurrences obtained from subprotocol visiting + // FIXME: parameter checking along with roles? + // FIXME: check do-call argument kinding (sig/type args/params), arity, etc + // bound qualified sig/type names (disambiguation check of qualified names, not just ambiguous) + // duplicate protocol/role decls etc + //.. do call type checking as well as basic name binding + // name collisions? e.g. message sig names and ops (M1 and M1() -- maybe ok) -- is rec var shadowing ok? (currently inconsistent to disallow due to shadowed recs in subprotocols and NameDisambiguator is not an inlined or subprotocol visitor) + + //.. guarded recursive subprotocols -- guarded recursion vars not needed? handled by projection -- subprotocols need unused roledecl check + //.. generalise dependencies for duplicate-role projection + //.. do projection should filter unused subprotocol role params -- also non role params? -- but scoped subprotocols may need extra name mangling + + // pointer equality for testing if AST subtrees already visited in e.g. InlinedWFChoiceChecker (and thus UnfoldingVisitor) maybe not good + // move roledecllist etc projection to dels + // could parameterise recvar to be global/local + + // self comm (wf, projection) + // multicast (enforce sending same value -- can "compile" to assertions for separate ops) + // TODO: deadlock analysis: for parallel, and even just choice if one process will play multiple roles (e.g. choice at A { A->B; A->C } or { A->C; A->B }) -- separate par from unordered + // FIXME: api generation for parallel/interruptible -- branch needs to report on op and role (depending on input queue semantics) + // api gen: explicit end for implicit skipping tail inputs but without failing the sender due to closing the transport -- actually, disable async for term-leading states? -- or perhaps implicit in using-close + //.. FIXME: singleton constants in subpackages, constant references from session class -- work out scrib package/module correspondence with java package/classes + + //.. fix projection env to take projection output type as Parameter + // dels should be kinded as well? -- maybe by node type? or too restrictive + + // some import/package name issues aren't tested in test suite because never in root package (issues when full and simple name coincide) + // roldedecl used validation only checked for global; projection runs roledecl fixing after role collection (although check should be redundant after projection roledecl fixing?) -- maybe separate roledecl validation to follow after context building + + // Inconsistencies? some visitOverride methods override base visit (i.e. including enter/exit) while others just override the visitChildren part + // also: sometimes super.visit is used, other times child.accept(this), etc + + //.. factor out main module resource loading in front end from main context -- front end should take main argument, check existence, and pass MainContext the abstract resource identifier to load the main + //.. ^^ alternatively keep ResourceLocator specific to file systems -- "DirectoryResourceLocator" just uses the import paths + +// Done +//.. gchoice use Collections.disjoint (not retain) +//.. add headerparamdecllist and rolearglist disamb tests +//.. public reconstructs; copy del assignment; remove unnecessary wildcard bounds (and sort out mixed collections under wildcards? -- where it runtime type checking gets involved) -- done: but chosen no to copy del assignment +//.. refactor inlined/unfolding visitor and del names +//.. make headerparamdecl into paramdecl directly, i.e. and then role is a specialised param kind -- headerparamdecl is super of role and nonrole decls +//.. get simple/compound name node and name classes into shape -- done: factored out base classes uniform with ast hierarchy, and using default methods for shared simple/compound behaviours +//.. fix del parameterized return type (take class as arg) -- maybe also copy -- done: generic node casts after visiting, generic env push/pop, protected shallow copy pattern +//.. remove scoped subprotocols for now +//.. consider refactoring all uses of AbstractProtocolDecl to be able to get global/local directly (would need global/local as a generic parameter) -- e.g. Do.getTargetProtocolDecl -- partly: using global/local kinds, don't need extra interface along with abstract protocoldecl class +// - streamline visitor pattern calls (e.g. accept) -- done: using total/partial (enter/leave) visit override patterns to customise e.g. subprotocol and projection visiting +// - visitor pattern, delegates, envs (root, creating and assigning, merging, super calls), subprotocol visiting -- done: sorted visitor hierarchy, added inlined/unfolded visiting, swapped env/subprotocol visitor positions, factored out offsetsubprotocolvisitor +// - streamline vistitor/del env references -- and del enter/leave env setter on visitors -- done: sorted out del immutability except for envs, visitor env generic parameter, and env generic parameter +//.. fix ReachabilityEnv merge; do enter/leave reachability check for recursion/continue/parallel/etc; check reachability pass visits all projected modules -- reachability checking now done on unfolded inlined protocols +//.. fix modelfactory simple name node parameterization (take class instead of enum) +//.. fix global/local do delegate context build loop -- use lambda +//.. AntlrNonRoleParamDeclList -- generic typing error -- generally fix nonroleparam decl/list/... -- fixed: cast justified by immutable ast nodes -- related generic typing (mixed colection types under a wildcard) +//.. fix parameterdecllist generics (not fixed to one kind) -- done: using base non-role parameter kind as the "concrete kind" (see above) +//.. both projector and graphbuilder are env visitors but not subprotocol visitors now, so swap visitor hierarchy? +//.. added unfolded visitor -- for: wf-c should in some cases attempt an unfolding on reaching a continue if not satisfied yet -- or do by "recording" cache for recs, as for subprotocolsigs +//.. added unfolded visitor -- for: changed fsmbuilder from offsetsubprot visitor to inlined visitor to reduce state label accumulation to rec only -- but this introduces a problem in wfc-checking for "unguarded" recursive-do-as-continue in choice blocks -- current offset visitor is also hacked to follow up just "1 level" +//.. projection as subprotocol visitor (or maybe by some other hack, e.g. check each gdo for special cases) to handle repeat role args e.g. do(A, B, A) -- done: by factoring out role occurrences into context info and adding another projection pass +//.. need public deep clone methods to support syntax manipulations e.g. unfolding (if using pointer equality for ast nodes in the same syntactic position, not just same text value) +//.. public reconstructs -- was previously using public-ified reconstruct of just interactionseq and recursion to do cloning for unfolding -- not a deep clone though, e.g. interaction seq reuses original block -- need to make sure dels/envs being treated properly +//.. factor out global/local inlining/unfolding better +//.. factor out some global/local del routines from compound/simple classes using default interface methods +//.. relax strictclasscheck visits -- partly: in just the places where nodes are currently expected to change (ambiguousnamenode, interactionseq, continue for unfolding) -- visitchildren shouldn't use check class on visited nodes so strictly, e.g. name disambiguation changes ambignodes to other nodes +//.. make all protected ast node fields private? make all field accesses by getters? -- partly: made all the mutable collection fields private +//.. tidy up inlinedwfchoice check in gchoicedel +//.. fix ldodel projection role fix gproto name hack -- Lprojectiondecl subclass records source gprotocol (and self role) +//.. role filtering for protocoldecl/do-projection in 2nd projection pass +//.. refactor global/local simple/compound dels +//.. refactor jobs (inlining/unfolding) +//.. offset/subprotocol visitor factoring +// - separate protocol names into global/local -- use generic parameter for name kinds rather than subclasses +// - wf-choice: a role should be enabled by the same role in all blocks +// - get rid of argument instantiation -- renamed, but otherwise structurally the same (unlike name/param decls, arg nodes are not kinded) +// - refactor simple/compound names to just names; and simple name nodes to be subtypes of compound -- simple/compound distinction only relevant to name nodes (i.e. syntax); type names are all uniform (compound) +// - generalise dependency building to support local protocols -- though only global dependencies used so far, for projection +// - make module/protocol delegate state (module context, protocol dependencies) setting uniform -- related to (non-)immutablity of delegates (where to store "context" state) +// - remove job/module contexts from Envs (refer from visitor -- can be updated during visitor pass and reassigned to root module on leave) +// - enter doesn't need to return visitor, not using visitor immutability? (or visitor replacement flexibility) +// - use Path API (though path separators not taken from nio api) +// - import path should be a CL parameter, not MainContext + +// ? - fix projected choice subj fixing for (single?) continue-only block +// ? - generalise recursion projection filtering +// ? - check projection/merge of role-subset recursion paths, and projection of non-relevant choice blocks + + +// Not done +//.. maybe make an UnkindedName superclass of Name, use for e.g. parameters or ambiguous -- parameters and ambiguous have their own kinds +// - perhaps refactor to have choice/recursion/etc as packages with global/local/del/etc in each -- no: going with kind generic parameter factoring instead +// - ArgumentNode is not kinded -- argument interface is about not knowing what kind of argument it is; e.g. AmbiguousNameNode has both DataType and Sig kind interfaces +// - FIXME: factor out a project method (like a reconstruct) to GlobalModelNode (and use the below for recording/assembling the projections) -- no, leave in delegate +// - change InteractionNode interface to a base class -- no, better for interaction nodes to extend simple/compound as base +// - make a createDelegate method in ModelNode -- no, leave association of delegates to model nodes in factory -- then replacing a delegate requires changing the factory only +// - substitute to delegate? -- no, better to have as a simple node operation that uses the protected reconstruct pattern directly (a del operation is more indirect with no advantages) +// - fix instanceof in projector and reachability checker -- only partly: moved main code to delegates but the "root" instanceof needs to stay inside the visitors to "override" the base subprotocol visitInSubprotocols pattern +// - override del in each ModelNode to cast -- no: leave as base del for most flexibility in case of replacement +// - Job takes MainContext as argument -- no: recursive maven dependencies between cli-core-parser + +public class Todo +{ + public Todo() + { + + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/lang/Constants.java b/scribble-core/src/main/java/org/scribble/core/lang/Constants.java new file mode 100644 index 000000000..59494288f --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/lang/Constants.java @@ -0,0 +1,25 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.lang; + +@Deprecated +public class Constants +{ + + public Constants() + { + // TODO Auto-generated constructor stub + } + +} diff --git a/scribble-core/src/main/java/org/scribble/core/lang/ProtoMod.java b/scribble-core/src/main/java/org/scribble/core/lang/ProtoMod.java new file mode 100644 index 000000000..ac251d7fe --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/lang/ProtoMod.java @@ -0,0 +1,55 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.lang; + +public enum ProtoMod +{ + AUX, + EXPLICIT; + + @Override + public String toString() + { + switch (this) + { + case AUX: return "aux"; + case EXPLICIT: return "explicit"; + default: throw new RuntimeException("Unknown modifier: " + this); + } + } +} + + + + + + + + + + + + + + + /*// TODO: refactor to scrib-lang -- param should be ProtocolMod, not CommonTree + public static ProtocolMod fromAst(CommonTree ast)//org.scribble.ast.ProtocolMod ast) + { + switch (ast.toString()) + { + case "aux": return AUX; + case "explicit": return EXPLICIT; + default: throw new RuntimeException("Unknown modifier: " + ast); + } + }*/ \ No newline at end of file diff --git a/scribble-core/src/main/java/org/scribble/core/lang/Protocol.java b/scribble-core/src/main/java/org/scribble/core/lang/Protocol.java new file mode 100644 index 000000000..a35db0824 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/lang/Protocol.java @@ -0,0 +1,163 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.lang; + +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; + +import org.antlr.runtime.tree.CommonTree; +import org.scribble.core.type.kind.NonRoleParamKind; +import org.scribble.core.type.kind.ProtoKind; +import org.scribble.core.type.name.DataName; +import org.scribble.core.type.name.MemberName; +import org.scribble.core.type.name.ProtoName; +import org.scribble.core.type.name.Role; +import org.scribble.core.type.name.SigName; +import org.scribble.core.type.session.Seq; +import org.scribble.core.visit.STypeInliner; +import org.scribble.core.visit.STypeUnfolder; +import org.scribble.util.Constants; + +public abstract class Protocol + , B extends Seq> + implements SNode +{ + private final CommonTree source; // CHECKME: factor out with SType(Base) ? + + public final List mods; + public final N fullname; + public final List roles; // Ordered role params; pre: size >= 2 + public final List> params; + // N.B. there is no Data/SigParamName // CHECKME: always simple names? + // NonRoleParamKind, not NonRoleArgKind, because latter includes AmbigKind due to parsing requirements + // CHECKME: make a ParamName? or at least SimpleName? + public final B def; + + public Protocol(CommonTree source, List mods, N fullname, + List roles, List> params, + B def) + { + this.source = source; // CHECKME: factor out with SType(Base) ? + this.mods = Collections.unmodifiableList(mods); + this.fullname = fullname; + this.roles = Collections.unmodifiableList(roles); + this.params = Collections.unmodifiableList(params); + this.def = def; + } + + // N.B. LProtocol has an additional "self" field, reconstruct pattern not perfect + public abstract Protocol reconstruct(CommonTree source, + List mods, N fullname, List roles, + List> params, B def); + + public boolean isAux() + { + return this.mods.contains(ProtoMod.AUX); + } + + public boolean isExplicit() + { + return this.mods.contains(ProtoMod.EXPLICIT); + } + + public abstract Protocol getInlined(STypeInliner v); + public abstract Protocol unfoldAllOnce(STypeUnfolder v); + + public boolean hasSource() // i.e., was parsed + { + return this.source != null; + } + + // CHECKME: factor out with SType(Base) ? + public CommonTree getSource() // Pre: hasSource + { + return this.source; + } + + @Override + public String toString() + { + return "protocol " + this.fullname.getSimpleName() + + paramsToString() + + rolesToString() + + " {\n" + this.def + "\n}"; + } + + protected String rolesToString() + { + return "(" + + this.roles.stream().map(x -> Constants.ROLE_KW + " " + x.toString()) + .collect(Collectors.joining(", ")) + + ")"; + } + + protected String paramsToString() + { + return "<" + this.params.stream() // CHECKME: drop empty "<>" ? + .map(x -> + { + String k; + if (x instanceof DataName) // CHECKME: refactor? + { + k = Constants.TYPE_KW; + } + else if (x instanceof SigName) + { + k = Constants.SIG_KW; + } + else + { + throw new RuntimeException(); + } + return k + x; + }) + .collect(Collectors.joining(", ")) + + ">"; + } + + // CHECKME: only should/need to use fullname? + @Override + public int hashCode() + { + int hash = 7; + hash = 31 * hash + super.hashCode(); + hash = 31 * hash + this.mods.hashCode(); + hash = 31 * hash + this.fullname.hashCode(); + hash = 31 * hash + this.roles.hashCode(); + hash = 31 * hash + this.params.hashCode(); + hash = 31 * hash + this.def.hashCode(); + return hash; + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof Protocol)) + { + return false; + } + Protocol them = (Protocol) o; + return them.canEquals(this) + && this.mods.equals(them.mods) && this.fullname.equals(them.fullname) + && this.roles.equals(them.roles) && this.params.equals(them.params) + && this.def.equals(them.def); + } + + public abstract boolean canEquals(Object o); +} diff --git a/scribble-core/src/main/java/org/scribble/core/lang/SNode.java b/scribble-core/src/main/java/org/scribble/core/lang/SNode.java new file mode 100644 index 000000000..d0c5cfdec --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/lang/SNode.java @@ -0,0 +1,23 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.lang; + +import org.antlr.runtime.tree.CommonTree; +import org.scribble.core.type.kind.ProtoKind; + +public interface SNode +{ + boolean hasSource(); // i.e., was parsed + CommonTree getSource(); // Pre: hasSource +} diff --git a/scribble-core/src/main/java/org/scribble/core/lang/SubprotoSig.java b/scribble-core/src/main/java/org/scribble/core/lang/SubprotoSig.java new file mode 100644 index 000000000..742920bc0 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/lang/SubprotoSig.java @@ -0,0 +1,127 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.lang; + +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; + +import org.scribble.core.lang.global.GProtocol; +import org.scribble.core.lang.local.LProtocol; +import org.scribble.core.type.kind.NonRoleParamKind; +import org.scribble.core.type.name.DataName; +import org.scribble.core.type.name.MemberName; +import org.scribble.core.type.name.ProtoName; +import org.scribble.core.type.name.Role; +import org.scribble.core.type.name.SigName; +import org.scribble.core.type.session.Arg; + +// CHECKME: relocate? +// Immutable +public class SubprotoSig +{ + public final ProtoName fullname; + public final List roles; // i.e., roles (and args) are ordered + public final List> args; + // NonRoleParamKind, not NonRoleArgKind, because latter includes AmbigKind due to parsing requirements + // Arg, not MemberName, because need to include MessageSigs (sig literals) + + // CHECKME: refactor as factory methods on Protocol/Do ? + public SubprotoSig(ProtoName fullname, + List roles, List> args) + { + this.fullname = fullname; + this.roles = Collections.unmodifiableList(roles); + this.args = Collections.unmodifiableList(args); + } + + public SubprotoSig(GProtocol n) + { + this(n.fullname, n.roles, paramsToArgs(n.params)); + } + + public SubprotoSig(LProtocol n) + { + this(n.fullname, n.roles.stream().map(x -> x.equals(n.self) ? Role.SELF : x) + // N.B. role decls (cf. do-args) don't feature self (cf. LSelfDecl), even after pruning/fixing + // FIXME: (implicit) self role mess + .collect(Collectors.toList()), paramsToArgs(n.params)); + } + + private static List> paramsToArgs( + List> params) + { + // Convert MemberName params to Args -- cf. NonRoleArgList::getParamKindArgs + return params.stream().map(x -> paramToArg(x)).collect(Collectors.toList()); + } + + // TODO: refactor, into params? + public static Arg paramToArg( + MemberName n) // Omit " extends NonRoleParamKind" on param, more flexible without major harm + { + if (n instanceof DataName) + { + return (DataName) n; + } + else if (n instanceof SigName) + { + return (SigName) n; + } + else + { + throw new RuntimeException("[TODO] : " + n.getClass() + "\n\t" + n); + } + } + + @Override + public int hashCode() + { + int hash = 1093; + hash = 31 * hash + this.fullname.hashCode(); + hash = 31 * hash + this.roles.hashCode(); + hash = 31 * hash + this.args.hashCode(); + return hash; + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof SubprotoSig)) + { + return false; + } + SubprotoSig subsig = (SubprotoSig) o; + return this.fullname.equals(subsig.fullname) + && this.roles.equals(subsig.roles) && this.args.equals(subsig.args); + } + + @Override + public String toString() + { + return + this.fullname + + "<" + + this.args.stream().map(x -> x.toString()) + .collect(Collectors.joining(", ")) + + ">" + + "(" + + this.roles.stream().map(x -> x.toString()) + .collect(Collectors.joining(", ")) + + ")"; + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/lang/context/ModuleContext.java b/scribble-core/src/main/java/org/scribble/core/lang/context/ModuleContext.java new file mode 100644 index 000000000..7aa3db298 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/lang/context/ModuleContext.java @@ -0,0 +1,140 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.lang.context; + +import java.util.Map; + +import org.scribble.core.type.kind.Global; +import org.scribble.core.type.kind.Kind; +import org.scribble.core.type.kind.ProtoKind; +import org.scribble.core.type.kind.SigKind; +import org.scribble.core.type.name.DataName; +import org.scribble.core.type.name.GProtoName; +import org.scribble.core.type.name.LProtoName; +import org.scribble.core.type.name.SigName; +import org.scribble.core.type.name.ModuleName; +import org.scribble.core.type.name.Name; +import org.scribble.core.type.name.ProtoName; +import org.scribble.util.ScribException; + +// Context information specific to each module as a root (wrt. to visitor passes) +// CHECKME: currently unused within core -- refactor out to lang package? +public class ModuleContext +{ + public final ModuleName root; // full name // The root Module for this ModuleContext -- cf. separate to the "main" module + + // All transitive name dependencies of this module: all names fully qualified + // The ScribNames maps are basically just used as sets (identity map) + // Cf. ProtocolDeclContext protocol dependencies from protocoldecl as root + private final ScribNames deps; + + // The modules and member names that are visible from this Module -- mapped to "cannonical" (fully qualified) names + // visible names -> fully qualified names + // Directly visible names from this module + private final ScribNames visible; + + // Made by ModuleContextBuilder + // ModuleContext is the root context + public ModuleContext(ModuleName root, ScribNames deps, ScribNames visible) + throws ScribException + { + this.root = root; + this.deps = deps; + this.visible = visible; + } + + /*public boolean isDataTypeDependency(DataType typename) + { + return this.deps.data.keySet().contains(typename); + } + + public boolean isMessageSigNameDependency(Name signame) + { + return this.deps.sigs.containsKey(signame); + }*/ + + // TODO: deprecate -- now redundant: proto should already be full name by namedisamb (and this.deps only stores full names) + // Refactored as a "check" for now (although still redundant, not actually checking anything) + public ProtoName checkProtocolDeclDependencyFullName( + ProtoName proto) + { + return getProtocolDeclFullName(this.deps, proto); + } + + public boolean isDataTypeVisible(DataName typename) + { + return this.visible.data.keySet().contains(typename); + } + + public boolean isMessageSigNameVisible(Name signame) + { + return this.visible.sigs.containsKey(signame); + } + + public DataName getVisibleDataTypeFullName(DataName visname) + { + return getFullName(this.visible.data, visname); + } + + public boolean isVisibleDataType(DataName visname) + { + return this.visible.isVisibleDataType(visname); + } + + public SigName getVisibleMessageSigNameFullName(SigName visname) + { + return getFullName(this.visible.sigs, visname); + } + + public ProtoName getVisibleProtocolDeclFullName( + ProtoName visname) + { + return getProtocolDeclFullName(this.visible, visname); + } + + public boolean isVisibleProtocolDeclName( + ProtoName visname) + { + return this.visible.isVisibleProtocolDeclName(visname); + } + + public static ProtoName getProtocolDeclFullName( + ScribNames names, ProtoName proto) + { + ProtoName pn = (proto.getKind() + .equals(Global.KIND)) + ? getFullName(names.globals, (GProtoName) proto) + : getFullName(names.locals, (LProtoName) proto); + @SuppressWarnings("unchecked") + ProtoName tmp = (ProtoName) pn; + return tmp; + } + + private static , K extends Kind> T getFullName( + Map map, T visname) + { + if (!map.containsKey(visname)) + { + // FIXME: runtime exception bad -- make a guard method + throw new RuntimeException("Unknown name: " + visname); + } + return map.get(visname); + } + + @Override + public String toString() + { + return "[deps=" + this.deps + ", visible=" + this.visible + "]"; + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/lang/context/ScribNames.java b/scribble-core/src/main/java/org/scribble/core/lang/context/ScribNames.java new file mode 100644 index 000000000..247cacfd2 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/lang/context/ScribNames.java @@ -0,0 +1,56 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.lang.context; + +import java.util.HashMap; +import java.util.Map; + +import org.scribble.core.type.name.DataName; +import org.scribble.core.type.name.GProtoName; +import org.scribble.core.type.name.LProtoName; +import org.scribble.core.type.name.SigName; +import org.scribble.core.type.name.ModuleName; +import org.scribble.core.type.name.ProtoName; + +// TODO: fix mutable public collection fields -- currently hacked for ModuleContext(Collector) internal use +// TODO: rename better +public class ScribNames +{ + // names -> fully qualified names + public final Map modules = new HashMap<>(); + public final Map data = new HashMap<>(); + public final Map sigs = new HashMap<>(); + public final Map globals = new HashMap<>(); + public final Map locals = new HashMap<>(); + + @Override + public String toString() + { + return "(modules=" + + this.modules + ", types=" + this.data + ", sigs=" + this.sigs + + ", globals=" + this.globals + ", locals=" + this.locals + + ")"; + } + + public boolean isVisibleProtocolDeclName(ProtoName visname) + { + return this.globals.containsKey(visname) + || this.locals.containsKey(visname); + } + + public boolean isVisibleDataType(DataName visname) + { + return this.data.containsKey(visname); + } +} \ No newline at end of file diff --git a/scribble-core/src/main/java/org/scribble/core/lang/global/GNode.java b/scribble-core/src/main/java/org/scribble/core/lang/global/GNode.java new file mode 100644 index 000000000..06ff9a5eb --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/lang/global/GNode.java @@ -0,0 +1,23 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.lang.global; + +import org.scribble.core.lang.SNode; +import org.scribble.core.type.kind.Global; + +// Mainly for GDel.translate return (to include GProtocol) +public interface GNode extends SNode +{ + +} diff --git a/scribble-core/src/main/java/org/scribble/core/lang/global/GProtocol.java b/scribble-core/src/main/java/org/scribble/core/lang/global/GProtocol.java new file mode 100644 index 000000000..38ba23faf --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/lang/global/GProtocol.java @@ -0,0 +1,205 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.lang.global; + +import java.util.Arrays; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +import org.antlr.runtime.tree.CommonTree; +import org.scribble.core.job.Core; +import org.scribble.core.lang.Protocol; +import org.scribble.core.lang.ProtoMod; +import org.scribble.core.lang.SubprotoSig; +import org.scribble.core.lang.local.LProjection; +import org.scribble.core.type.kind.Global; +import org.scribble.core.type.kind.Local; +import org.scribble.core.type.kind.NonRoleParamKind; +import org.scribble.core.type.name.GProtoName; +import org.scribble.core.type.name.LProtoName; +import org.scribble.core.type.name.MemberName; +import org.scribble.core.type.name.RecVar; +import org.scribble.core.type.name.Role; +import org.scribble.core.type.session.global.GRecursion; +import org.scribble.core.type.session.global.GSeq; +import org.scribble.core.type.session.local.LSeq; +import org.scribble.core.visit.STypeInliner; +import org.scribble.core.visit.STypeUnfolder; +import org.scribble.core.visit.Substitutor; +import org.scribble.core.visit.gather.RoleGatherer; +import org.scribble.core.visit.global.ConnectionChecker; +import org.scribble.core.visit.global.ExtChoiceConsistencyChecker; +import org.scribble.core.visit.global.InlinedProjector; +import org.scribble.core.visit.global.RoleEnablingChecker; +import org.scribble.util.ScribException; + +public class GProtocol extends Protocol + implements GNode // Mainly for GDel.translate return (to include GProtocol) +{ + public GProtocol(CommonTree source, List mods, + GProtoName fullname, List roles, + List> params, GSeq def) + { + super(source, mods, fullname, roles, params, def); + } + + @Override + public GProtocol reconstruct(CommonTree source, + List mods, GProtoName fullname, List roles, + List> params, GSeq def) + { + return new GProtocol(source, mods, fullname, roles, params, def); + } + + // Cf. (e.g.) checkRoleEnabling, that takes Core + // CHECKME: drop from Protocol (after removing Protocol from SType?) + // Pre: stack.peek is the sig for the calling Do (or top-level entry), i.e., it gives the roles/args at the call-site + @Override + public GProtocol getInlined(STypeInliner v) + { + SubprotoSig sig = new SubprotoSig(this); + v.pushSig(sig); + + Substitutor subs = v.core.config.vf.Substitutor(this.roles, sig.roles, + this.params, sig.args); + GSeq inlined = v.visitSeq(subs.visitSeq(this.def)); + RecVar rv = v.getInlinedRecVar(sig); + GRecursion rec = v.core.config.tf.global.GRecursion(null, rv, inlined); // CHECKME: or protodecl source? + GSeq seq = v.core.config.tf.global.GSeq(null, Arrays.asList(rec)); + GSeq def = v.core.config.vf.RecPruner().visitSeq(seq); + Set used = def.gather(new RoleGatherer()::visit) + .collect(Collectors.toSet()); + List rs = this.roles.stream().filter(x -> used.contains(x)) // Prune role decls -- CHECKME: what is an example? was this from before unused role checking? + .collect(Collectors.toList()); + return //new GProtocol + reconstruct(getSource(), this.mods, this.fullname, rs, + this.params, def); + } + + @Override + public GProtocol unfoldAllOnce(STypeUnfolder v) + { + GSeq unf = v.visitSeq(this.def); + return reconstruct(getSource(), this.mods, this.fullname, this.roles, + this.params, unf); + } + + // Cf. (e.g.) getInlined, that takes the Visitor (not Core) + public void checkRoleEnabling(Core core) throws ScribException + { + Set rs = this.roles.stream().collect(Collectors.toSet()); + RoleEnablingChecker v = core.config.vf.global.RoleEnablingChecker(rs); + this.def.visitWith(v); + } + + public void checkExtChoiceConsistency(Core core) throws ScribException + { + Map rs = this.roles.stream() + .collect(Collectors.toMap(x -> x, x -> x)); + ExtChoiceConsistencyChecker v = core.config.vf.global + .ExtChoiceConsistencyChecker(rs); + this.def.visitWith(v); + } + + public void checkConnectedness(Core core, boolean implicit) + throws ScribException + { + Set rs = this.roles.stream().collect(Collectors.toSet()); + ConnectionChecker v = core.config.vf.global.ConnectionChecker(rs, implicit); + this.def.visitWith(v); + } + + // Currently assuming inlining (or at least "disjoint" protodecl projection, without role fixing) + public LProjection projectInlined(Core core, Role self) + { + LSeq def = core.config.vf.global.InlinedProjector(core, self) + .visitSeq(this.def); + LSeq fixed = core.config.vf.local.InlinedExtChoiceSubjFixer().visitSeq(def); + return projectAux(core, self, this.roles, fixed); + } + + // Does rec and role pruning + private LProjection projectAux(Core core, Role self, List decls, + LSeq def) + { + LSeq pruned = core.config.vf.RecPruner().visitSeq(def); + LProtoName fullname = InlinedProjector + .getFullProjectionName(this.fullname, self); + Set used = pruned.gather(new RoleGatherer()::visit) + .collect(Collectors.toSet()); + List roles = decls.stream() + .filter(x -> x.equals(self) || used.contains(x)) + .collect(Collectors.toList()); + List> params = + new LinkedList<>(this.params); // CHECKME: filter params by usage? + return new LProjection(this.mods, fullname, roles, self, params, + this.fullname, pruned); // CHECKME: add/do via tf? + } + + // N.B. no "fixing" passes done here -- need breadth-first passes to be sequentialised for subproto visiting + public LProjection project(Core core, Role self) + { + LSeq def = core.config.vf.global.Projector(core, self).visitSeq(this.def); + // N.B. not using projectAux, because don't want to prune role decls using RoleGatherer: it doesn't follow subprotos, so can over-prune roledecls (e.g., bad.efsm.grecursion.unfair.Test06, C) + // Instead, retain full global role decls for now -- and prune later, via LDoArgPruner + LSeq pruned = core.config.vf.RecPruner().visitSeq(def); + LProtoName fullname = InlinedProjector + .getFullProjectionName(this.fullname, self); + List> params = + new LinkedList<>(this.params); // CHECKME: filter params by usage? + // N.B. also not using PreRoleCollector here for role decl pruning (cf. LRoleDeclAndDoArgPruner), "initial" projection pass not complete yet, so cannot traverse all needed subprotos + LProjection proj = new LProjection(this.mods, fullname, this.roles, self, + params, this.fullname, pruned); + // TODO: fully refactor ext choice subj fixing, do pruning, etc to Job and use AstVisitor? + return proj; + } + + @Override + public String toString() + { + return this.mods.stream().map(x -> x.toString() + " ") + .collect(Collectors.joining()) + "global " + super.toString(); + } + + @Override + public int hashCode() + { + int hash = 11; + hash = 31 * hash + super.hashCode(); + return hash; + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof GProtocol)) + { + return false; + } + return super.equals(o); // Does canEquals + } + + @Override + public boolean canEquals(Object o) + { + return o instanceof GProtocol; + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/lang/local/LNode.java b/scribble-core/src/main/java/org/scribble/core/lang/local/LNode.java new file mode 100644 index 000000000..33164fe2f --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/lang/local/LNode.java @@ -0,0 +1,22 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.lang.local; + +import org.scribble.core.lang.SNode; +import org.scribble.core.type.kind.Local; + +public interface LNode extends SNode +{ + +} diff --git a/scribble-core/src/main/java/org/scribble/core/lang/local/LProjection.java b/scribble-core/src/main/java/org/scribble/core/lang/local/LProjection.java new file mode 100644 index 000000000..18c5c5122 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/lang/local/LProjection.java @@ -0,0 +1,115 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.lang.local; + +import java.util.List; +import java.util.stream.Collectors; + +import org.antlr.runtime.tree.CommonTree; +import org.scribble.core.lang.ProtoMod; +import org.scribble.core.type.kind.Local; +import org.scribble.core.type.kind.NonRoleParamKind; +import org.scribble.core.type.name.GProtoName; +import org.scribble.core.type.name.LProtoName; +import org.scribble.core.type.name.MemberName; +import org.scribble.core.type.name.Role; +import org.scribble.core.type.session.local.LSeq; +import org.scribble.core.visit.STypeInliner; + +public class LProjection extends LProtocol +{ + public final GProtoName global; + + public LProjection(List mods, LProtoName fullname, + List roles, Role self, + List> params, GProtoName global, + LSeq body) + { + super(null, mods, fullname, roles, self, params, body); + this.global = global; + } + + @Override + public LProjection reconstruct(CommonTree source, + List mods, LProtoName fullname, List roles, + Role self, List> params, LSeq body) + { + return new LProjection(mods, fullname, roles, this.self, params, + this.global, body); + } + + /*@Override + public LType substitute(Substitutions subs) + { + *List roles = this.roles.stream().map(x -> subs.subsRole(x)) + .collect(Collectors.toList()); + return reconstruct(getSource(), this.mods, this.fullname, roles, + this.def.substitute(subs)); + }*/ + + // Pre: stack.peek is the sig for the calling Do (or top-level entry) + // i.e., it gives the roles/args at the call-site + @Override + public LProjection getInlined(STypeInliner v) + { + throw new RuntimeException("[TODO]: " + this); + } + + /*@Override + public LProtocolDecl getSource() + { + return (LProtocolDecl) super.getSource(); + }*/ + + @Override + public String toString() + { + return this.mods.stream().map(x -> x.toString() + " ") + .collect(Collectors.joining()) + + "local protocol " + this.fullname.getSimpleName() + + paramsToString() + + rolesToString() + + " projects " + this.global + + " {\n" + this.def + "\n}"; + } + + @Override + public int hashCode() + { + int hash = 3167; + hash = 31 * hash + super.hashCode(); + hash = 31 * hash + this.global.hashCode(); + return hash; + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof LProjection)) + { + return false; + } + return super.equals(o); // Does canEquals + } + + @Override + public boolean canEquals(Object o) + { + return o instanceof LProjection; + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/lang/local/LProtocol.java b/scribble-core/src/main/java/org/scribble/core/lang/local/LProtocol.java new file mode 100644 index 000000000..d0c0d2872 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/lang/local/LProtocol.java @@ -0,0 +1,189 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.lang.local; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; + +import org.antlr.runtime.tree.CommonTree; +import org.scribble.core.job.Core; +import org.scribble.core.lang.Protocol; +import org.scribble.core.lang.ProtoMod; +import org.scribble.core.lang.SubprotoSig; +import org.scribble.core.model.endpoint.EGraph; +import org.scribble.core.model.endpoint.EState; +import org.scribble.core.type.kind.Local; +import org.scribble.core.type.kind.NonRoleParamKind; +import org.scribble.core.type.name.LProtoName; +import org.scribble.core.type.name.MemberName; +import org.scribble.core.type.name.RecVar; +import org.scribble.core.type.name.Role; +import org.scribble.core.type.session.local.LRecursion; +import org.scribble.core.type.session.local.LSeq; +import org.scribble.core.visit.STypeInliner; +import org.scribble.core.visit.STypeUnfolder; +import org.scribble.core.visit.Substitutor; +import org.scribble.core.visit.local.EGraphBuilder; +import org.scribble.core.visit.local.LDoPruner; +import org.scribble.core.visit.local.LRoleDeclAndDoArgPruner; +import org.scribble.core.visit.local.SubprotoExtChoiceSubjFixer; +import org.scribble.util.Constants; +import org.scribble.util.ScribException; + +public class LProtocol extends Protocol + implements LNode +{ + public final Role self; + + public LProtocol(CommonTree source, List mods, + LProtoName fullname, List roles, Role self, + List> params, LSeq def) + { + super(source, mods, fullname, roles, params, def); + this.self = self; + } + + @Override + public LProtocol reconstruct(CommonTree source, + List mods, LProtoName fullname, List roles, + //Role self, // CHECKME: reconstruct pattern not working here? + List> params, LSeq def) + { + return reconstruct(source, mods, fullname, roles, this.self, params, def); // N.B. this.self + } + + public LProtocol reconstruct(CommonTree source, + List mods, LProtoName fullname, List roles, + Role self, List> params, LSeq def) + { + return new LProtocol(source, mods, fullname, roles, self, params, def); + } + + // CHECKME: drop from Protocol (after removing Protocol from SType?) + // Pre: stack.peek is the sig for the calling Do (or top-level entry) + // i.e., it gives the roles/args at the call-site + @Override + public LProtocol getInlined(STypeInliner v) + { + SubprotoSig sig = new SubprotoSig(this); + v.pushSig(sig); + + Substitutor subs = v.core.config.vf.Substitutor(this.roles, sig.roles, + this.params, sig.args); + LSeq inlined = v.visitSeq(subs.visitSeq(this.def)); + RecVar rv = v.getInlinedRecVar(sig); + LRecursion rec = v.core.config.tf.local.LRecursion(null, rv, inlined); // CHECKME: or protodecl source? + LSeq seq = v.core.config.tf.local.LSeq(null, Arrays.asList(rec)); + LSeq def = v.core.config.vf.RecPruner().visitSeq(seq); + /*//CHECKME: necessary for LProtocol/Projection? cf. global + Set used = def.gather(new RoleGatherer()::visit) + .collect(Collectors.toSet()); + List rs = this.roles.stream().filter(x -> used.contains(x)) // Prune role decls + .collect(Collectors.toList());*/ + return reconstruct(getSource(), this.mods, this.fullname, this.roles, + this.self, this.params, def); // CHECKME: or null source? + } + + @Override + public LProtocol unfoldAllOnce(STypeUnfolder v) + { + LSeq unf = v.visitSeq(this.def); + return reconstruct(getSource(), this.mods, this.fullname, this.roles, + this.self, this.params, unf); + } + + public void checkReachability(Core core) throws ScribException + { + this.def.visitWith(core.config.vf.local.ReachabilityChecker()); + } + + // Implicitly means Subproto visitor + public LProtocol pruneRoleDeclsAndDoArgs(LRoleDeclAndDoArgPruner v) + { + return v.visitLProtocol(this); + } + + // Implicitly means Subproto visitor + public LProtocol pruneDos(LDoPruner v) + { + return v.visitLProtocol(this); + } + + public LProtocol fixExtChoiceSubjs(SubprotoExtChoiceSubjFixer v) + { + return (LProtocol) v.visitProtocol(this); + } + + public EGraph toEGraph(Core core) + { + if (this.def.isEmpty()) // Empty Seq special case for top-level -- in general, Seq must be non-empty, cf. LSeq::buildGraph entry/exit + { + EState s = core.config.mf.local.EState(Collections.emptySet()); + return new EGraph(s, s); // TODO: refactor constructor inside mf + } + EGraphBuilder b = core.config.vf.local.EGraphBuilder(core); + this.def.visitWithNoThrow(b); + return b.finalise(); + } + + @Override + public String toString() + { + return this.mods.stream().map(x -> x.toString() + " ") + .collect(Collectors.joining(" ")) + "local " + super.toString(); + } + + @Override + protected String rolesToString() + { + return "(" + + this.roles.stream() + .map(x -> (x.equals(this.self) + ? Constants.SELF_KW + : Constants.ROLE_KW) + " " + x) + .collect(Collectors.joining(", ")) + + ")"; + } + + @Override + public int hashCode() + { + int hash = 11; + hash = 31 * hash + super.hashCode(); + hash = 31 * hash + this.self.hashCode(); + return hash; + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof LProtocol)) + { + return false; + } + return super.equals(o); // Does canEquals + } + + @Override + public boolean canEquals(Object o) + { + return o instanceof LProtocol; + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/model/GraphBuilderUtil.java b/scribble-core/src/main/java/org/scribble/core/model/GraphBuilderUtil.java new file mode 100644 index 000000000..e15128d39 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/model/GraphBuilderUtil.java @@ -0,0 +1,57 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.model; + +import org.scribble.core.type.kind.ProtoKind; + +// Helper class for (Endpoint)GraphBuilder -- can access the protected setters of S +public abstract class GraphBuilderUtil + , // Action type: labels on edges + S extends MState, // State type + K extends ProtoKind> // Global/local actions/states -- Need to quantify K explicitly +{ + public final ModelFactory mf; // N.B. new states should be made by this.newState, not this.ef.newEState + + // Doesn't call reset + protected GraphBuilderUtil(ModelFactory mf) + { + this.mf = mf; + } + + protected abstract void reset(); + + //public abstract S newState(L labs); // Doesn't factor out well with SState, doesn't use L and takes an SConfig + + protected void addEntryLabAux(S s, L lab) + { + s.addLabel(lab); + } + + public void addEdge(S s, A a, S succ) + { + addEdgeAux(s, a, succ); + } + + // Just a visibility workaround helper -- cf. addEdge: public method that may be overridden + protected final void addEdgeAux(S s, A a, S succ) + { + s.addEdge(a, succ); + } + + protected void removeEdgeAux(S s, A a, S succ) //throws ScribException // Exception necessary? + { + s.removeEdge(a, succ); + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/model/MAction.java b/scribble-core/src/main/java/org/scribble/core/model/MAction.java new file mode 100644 index 000000000..333829144 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/model/MAction.java @@ -0,0 +1,82 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.model; + +import org.scribble.core.type.kind.ProtoKind; +import org.scribble.core.type.name.MsgId; +import org.scribble.core.type.name.Role; +import org.scribble.core.type.session.Payload; + +public abstract class MAction +{ + /*private static int count = 0; + + public final int id; // Was using for trace enumeration, but breaks isAcceptable -- but would be better for non-det models?*/ + + public final Role obj; + public final MsgId mid; + public final Payload payload; // Payload.EMPTY_PAYLOAD for SigName mid + + protected MAction(Role obj, MsgId mid, Payload payload) + { + //this.id = ModelAction.count++; + + this.obj = obj; + this.mid = mid; + this.payload = payload; + } + + @Override + public String toString() + { + return this.obj + getCommSymbol() + this.mid + this.payload; + } + + // Used by toAut + public String toStringWithMsgIdHack() + { + String m = this.mid.isSigName() ? "^" + this.mid : this.mid.toString(); // HACK + return this.obj + getCommSymbol() + m + this.payload; + } + + protected abstract String getCommSymbol(); + + @Override + public int hashCode() + { + int hash = 919; + hash = 31 * hash + this.obj.hashCode(); + hash = 31 * hash + this.mid.hashCode(); + hash = 31 * hash + this.payload.hashCode(); + return hash; + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof MAction)) + { + return false; + } + MAction them = (MAction) o; // Refactor as "compatible" + return them.canEquals(this) && this.obj.equals(them.obj) + && this.mid.equals(them.mid) && this.payload.equals(them.payload); + } + + public abstract boolean canEquals(Object o); +} diff --git a/scribble-core/src/main/java/org/scribble/core/model/MPrettyPrint.java b/scribble-core/src/main/java/org/scribble/core/model/MPrettyPrint.java new file mode 100644 index 000000000..d15a1aae1 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/model/MPrettyPrint.java @@ -0,0 +1,20 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.model; + +public interface MPrettyPrint +{ + String toDot(); + String toAut(); // FIXME: should not be a pretty print method? +} diff --git a/scribble-core/src/main/java/org/scribble/core/model/MPrettyState.java b/scribble-core/src/main/java/org/scribble/core/model/MPrettyState.java new file mode 100644 index 000000000..0afe951d5 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/model/MPrettyState.java @@ -0,0 +1,157 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.model; + +import java.util.HashSet; +import java.util.Iterator; +import java.util.Set; +import java.util.stream.Collectors; + +import org.scribble.core.type.kind.ProtoKind; + +public abstract class MPrettyState + , S extends MPrettyState, K extends ProtoKind> + extends MState + implements MPrettyPrint +{ + public MPrettyState(Set labs) // Immutable singleton node + { + super(labs); + } + + public String toVerboseString() + { + String s = "\"" + this.id + "\":["; + Iterator ss = this.succs.iterator(); + s += this.actions.stream().map(x -> x + "=\"" + ss.next().id + "\"") + .collect(Collectors.joining(", ")); + return s + "]"; + } + + // Move up to MState? + @Override + public final String toDot() + { + StringBuilder b = new StringBuilder(); + b.append("digraph G {\n"); // rankdir=LR;\n + b.append("compound = true;\n"); + b.append(toStateDot() + "\n"); + Set ss = getReachableStates(); + ss.remove(this); // Avoids generic cast of alternative, ss.add((S) this) -- or else do Set> + ss.forEach(x -> b.append(x.toStateDot() + "\n")); + b.append("}"); + return b.toString(); + } + + protected final String toStateDot() + { + StringBuilder b = new StringBuilder(); + b.append(toNodeDot()); + Iterator as = getActions().iterator(); + Iterator ss = getSuccs().iterator(); + while (as.hasNext()) + { + A na = as.next(); + S ns = ss.next(); + b.append("\n" + toEdgeDot(na, ns)); + } + return b.toString(); + } + + // dot node declaration + // Override to change drawing declaration of "this" node + protected String toNodeDot() + { + return getDotNodeId() + " [ " + getNodeLabel() + " ];"; + } + + protected String getDotNodeId() + { + return "\"" + this.id + "\""; + } + + protected String getNodeLabel() + { + String labs = this.labs.toString(); + return "label=\"" + this.id + ": " + labs.substring(1, labs.length() - 1) + + "\""; + // TODO: revise ? + } + + // Override to change edge drawing from "this" as src + protected String toEdgeDot(A msg, S next) + { + return toEdgeDot(getDotNodeId(), next.getDotNodeId(), + next.getEdgeLabel(msg)); // CHECKME: next.getEdgeLabel or this.? + } + + // "this" is the dest node of the edge + // Override to change edge drawing to "this" as dest + protected String getEdgeLabel(A msg) + { + return "label=\"" + msg + "\""; + } + + protected String toEdgeDot(String src, String dest, String lab) + { + return src + " -> " + dest + " [ " + lab + " ];"; + } + + // Move up to MState? + @Override + public final String toAut() + { + Set> all = new HashSet<>(); + all.add(this); + all.addAll(getReachableStates()); // The only way to avoid generic cast? not ideal though + String aut = ""; + int edges = 0; + for (MPrettyState s : all) + { + Iterator as = s.getActions().iterator(); + Iterator succs = s.getSuccs().iterator(); + for (; as.hasNext(); edges++) + { + A a = as.next(); + S succ = succs.next(); + String msg = a.toStringWithMsgIdHack(); // HACK + aut += "\n(" + s.id + ",\"" + msg + "\"," + succ.id + ")"; + } + } + return "des (" + this.id + "," + edges + "," + all.size() + ")" + + aut + "\n"; + } + + @Override + public int hashCode() + { + int hash = 71; + hash = 31 * hash + super.hashCode(); + return hash; + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof MPrettyState)) + { + return false; + } + return super.equals(o); // Checks canEquals + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/model/MState.java b/scribble-core/src/main/java/org/scribble/core/model/MState.java new file mode 100644 index 000000000..d44d0d3c7 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/model/MState.java @@ -0,0 +1,362 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.model; + +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; +import java.util.stream.Collectors; + +import org.scribble.core.type.kind.ProtoKind; +import org.scribble.util.RuntimeScribException; + +public abstract class MState +< + L, // Node label type (cosmetic) + A extends MAction, // Edge type + S extends MState, // State type + K extends ProtoKind // Global/Local -- CHECKME: useful? +> +{ + private static int count = 1; // A shared index counter for every single MState (and subclass) instance + + public final int id; + + // Labels and edges are mutable (via protected methods) + protected final Set labs; // Was RecVar and SubprotocolSigs, now using inlined protocol for FSM building so just RecVar + protected final List actions; + protected final List succs; + + public MState(Set labs) + { + this.id = MState.count++; + this.labs = new HashSet<>(labs); + this.actions = new LinkedList<>(); + this.succs = new LinkedList<>(); + } + + // Mutating setter + protected final void addLabel(L lab) + { + this.labs.add(lab); + } + + public final Set getLabels() + { + return Collections.unmodifiableSet(this.labs); + } + + // Mutating setter (can also overwrite edges) + protected void addEdge(A a, S s) + { + /*if (this.equals(s)) + { + // CHECKME: refactor unfair transform to eliminate this special case -- or better to have? generalise to all "identical" non-det paths?... + // ...special case was previously for all non-det "this-a->s" for the same "s", but also works when specialised to recursive such cases, i.e., this.equals(s) (because only recursion is relevant to unfair transform) + // + // Needed? -- seems so, for the unfair transform (specifically for recursive non-det paths of length 1, see good.efsm.gchoice.Test09) + // Cf. EState.unfairTransform... ? -- if (curr.getStateKind() == EStateKind.OUTPUT && curr.getActions().size() > 1) // >1 is what makes this algorithm terminating + // ...because of unfairClone, na.equals(a) && ns.equals(succ) -- a pair of non-det (a, s) edges will *both* be added in the unfair-clone, instead of pruned down to one output-case, so above >1 termination condition never reached + Iterator as = this.actions.iterator(); + Iterator ss = this.succs.iterator(); + while (as.hasNext()) // Duplicate edges preemptively pruned here, but could leave to later minimisation + { + A na = as.next(); // N.B. cannot "inline" into below if-condition, due to short circuiting + S ns = ss.next(); + if (na.equals(a) && ns.equals(s)) + { + return; + } + } + }*/ + this.actions.add(a); + this.succs.add(s); + } + + // Pre: (this, a, s) is a current edge -- mutating setter + protected final void removeEdge(A a, S s) + //throws ScribException // CHECKME: used? -- cf., Hack? EFSM building on bad-reachability protocols now done before actual reachability check + { + Iterator as = this.actions.iterator(); + Iterator ss = this.succs.iterator(); + while (as.hasNext()) + { + A na = as.next(); // N.B. cannot "inline" into below if-condition, due to short circuiting + S ns = ss.next(); + if (na.equals(a) && ns.equals(s)) + { + as.remove(); // Must follow next + ss.remove(); + return; + } + } + throw new RuntimeException("No such transition: " + a + "->" + s); + } + + public final List getActions() + { + return Collections.unmodifiableList(this.actions); + } + + public final boolean hasAction(A a) + { + return this.actions.contains(a); + } + + public final List getSuccs() + { + return Collections.unmodifiableList(this.succs); + } + + public final List getSuccs(A a) + { + Iterator as = this.actions.iterator(); + Iterator ss = this.succs.iterator(); + List res = new LinkedList<>(); + while (as.hasNext()) + { + A na = as.next(); + S ns = ss.next(); + if (na.equals(a)) + { + res.add(ns); + } + } + return res; + } + + // Variant of getActions with implicit run-time check on determinism -- currently used by codegen utils (that have that assumption) + // (Pre: actions are deterministic) + public final List getDetActions() + { + Set as = new HashSet<>(this.actions); + if (as.size() != this.actions.size()) + { + throw new RuntimeScribException("[TODO] Non-deterministic state: " + + this.actions + " (Try -minlts if available)"); + // This getter checks for determinism -- mainly affects API generation + } + return getActions(); + } + + // Variant with implicit run-time check on determinism + // (Pre: actions are deterministic) + public S getDetSuccessor(A a) + { + Set as = new HashSet<>(this.actions); + if (as.size() != this.actions.size()) + { + throw new RuntimeException("[FIXME] : " + this.actions); + } + return getSuccs(a).get(0); + } + + public final boolean isTerminal() + { + return this.actions.isEmpty(); + } + + public S getTerminal() + { + //getReachableStates().stream().filter(x -> x.isTerminal()).findFirst(); + Set terms = getReachableStates().stream() + .filter(s -> s.isTerminal()).collect(Collectors.toSet()); + if (terms.size() > 1) + { + throw new RuntimeException("Shouldn't get in here: " + terms); + } + return terms.isEmpty() //.isPresent() + ? null : terms.iterator().next(); // CHECKME: return empty Set instead of null? null used by EState.toGraph + } + + // CHECKME: add "caching" versions to, e.g., Graphs? + // N.B. doesn't implicitly include start (only if start is reachable from start by at least one transition) + // Concrete subclass implementation should call, e.g., getReachableStatesAux(this) -- for S param, putting "this" into Map + public abstract Set getReachableStates(); + + // N.B. doesn't implicitly include start (only if start is explicitly reachable from start by at least one transition) + protected Set getReachableStatesAux(S start) + { + Map all = new HashMap<>(); + Map todo = new LinkedHashMap<>(); // Linked unnecessary, but to follow the iteration pattern + todo.put(this.id, start); // Suppressed: assumes ModelState subclass correctly instantiates S parameter + while (!todo.isEmpty()) + { + Iterator> i = todo.entrySet().iterator(); + Entry next = i.next(); + i.remove(); // Must follow next + for (S s : next.getValue().getSuccs()) + { + if (!all.containsKey(s.id)) + { + all.put(s.id, s); + todo.put(s.id, s); + } + } + } + return new HashSet<>(all.values()); // Often will want to add this + } + + public Set getReachableActions() + { + return getReachableStates().stream().flatMap(x -> x.getActions().stream()) + .collect(Collectors.toSet()); + } + + public boolean canReach(MState s) + { + return getReachableStates().contains(s); + } + + @Override + public String toString() + { + return Integer.toString(this.id); // CHECKME: ? + } + + @Override + public int hashCode() + { + int hash = 73; + hash = 31 * hash + this.id; // N.B. using state ID only + return hash; + } + + // N.B. Based only on state ID + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof MState)) + { + return false; + } + MState them = (MState) o; + return them.canEquals(this) && this.id == them.id; + // Convenient to use id, due to edge mutability + } + + protected abstract boolean canEquals(MState s); +} + + + + + + + + + + + + + + /* + public final List getDetSuccessors() + { + Set as = new HashSet<>(this.actions); + if (as.size() != this.actions.size()) + { + throw new RuntimeScribException("[TODO] Non-deterministic state: " + + this.actions + " (Try -minlts if available)"); + // This getter checks for determinism -- affects e.g. API generation + } + return getSuccessors(); + } + + // TODO: make protected + public static , S extends MState, K extends ProtoKind> + S getTerminal(S start) + { + if (start.isTerminal()) + { + return start; + } + Set terms = start.getReachableStates().stream() + .filter(s -> s.isTerminal()).collect(Collectors.toSet()); + if (terms.size() > 1) + { + throw new RuntimeException("Shouldn't get in here: " + terms); + } + return (terms.isEmpty()) ? null : terms.iterator().next(); // FIXME: return empty Set instead of null? + } + + // Note: doesn't implicitly include start (only if start is explicitly reachable from start, of course) + /*public static , S extends ModelState, K extends ProtocolKind> + Set getAllReachable(S start)* / + // TODO: make protected + // CHECKME: cache results? + @SuppressWarnings("unchecked") + public static , S extends MState, K extends ProtoKind> + Set getReachableStates(MState start) + { + Map all = new HashMap<>(); + Map todo = new LinkedHashMap<>(); + todo.put(start.id, (S) start); // Suppressed: assumes ModelState subclass correctly instantiates S parameter + while (!todo.isEmpty()) + { + Iterator i = todo.values().iterator(); + S next = i.next(); + todo.remove(next.id); + /*if (all.containsKey(next.id)) + { + continue; + } + all.put(next.id, next);* / + for (S s : next.getAllSuccessors()) + { + /*if (!all.containsKey(s.id) && !todo.containsKey(s.id)) + { + todo.put(s.id, s); + }* / + if (!all.containsKey(s.id)) + { + all.put(s.id, s); + //if (!todo.containsKey(s.id)) // Redundant + { + todo.put(s.id, s); + } + } + } + } + return new HashSet<>(all.values()); + } + + @SuppressWarnings("unchecked") + // TODO: make protected + // CHECKME: cache results? + public static , S extends MState, K extends ProtoKind> + //Set getAllReachableActions(S start) + Set getReachableActions(MState start) + { + Set all = new HashSet<>(); + all.add((S) start); // Suppressed: assumes ModelState subclass correctly instantiates S parameter + all.addAll(MState.getReachableStates(start)); + Set as = new HashSet<>(); + for (S s : all) + { + as.addAll(s.getAllActions()); + } + return as; + }*/ \ No newline at end of file diff --git a/scribble-core/src/main/java/org/scribble/core/model/ModelFactory.java b/scribble-core/src/main/java/org/scribble/core/model/ModelFactory.java new file mode 100644 index 000000000..d39c6ab6a --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/model/ModelFactory.java @@ -0,0 +1,34 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.model; + +import java.util.function.Function; + +import org.scribble.core.model.endpoint.EModelFactory; +import org.scribble.core.model.global.SModelFactory; + +public class ModelFactory +{ + public final EModelFactory local; + public final SModelFactory global; + + // Args should be constructor refs that that ModelFactory single arg + // (Workaround to set mutually referential ModelFactory and E/SModelFactory final fields) + public ModelFactory(Function ef, + Function sf) + { + this.local = ef.apply(this); + this.global = sf.apply(this); + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/model/ModelFactoryBase.java b/scribble-core/src/main/java/org/scribble/core/model/ModelFactoryBase.java new file mode 100644 index 000000000..ee8adf6dd --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/model/ModelFactoryBase.java @@ -0,0 +1,26 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.model; + +// Base class for all *E/SModelFactoryImpl* +// N.B. this class does *not* itself implement the top-level ModelFactory wrapper (nor vice versa) +public abstract class ModelFactoryBase +{ + protected ModelFactory mf = null; + + public ModelFactoryBase(ModelFactory mf) + { + this.mf = mf; + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/model/endpoint/AutGraphParser.java b/scribble-core/src/main/java/org/scribble/core/model/endpoint/AutGraphParser.java new file mode 100644 index 000000000..a840d9ca9 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/model/endpoint/AutGraphParser.java @@ -0,0 +1,306 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.model.endpoint; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.StringReader; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +import org.scribble.core.job.Core; +import org.scribble.core.model.ModelFactory; +import org.scribble.core.model.endpoint.actions.EAction; +import org.scribble.core.type.name.DataName; +import org.scribble.core.type.name.MsgId; +import org.scribble.core.type.name.SigName; +import org.scribble.core.type.name.Op; +import org.scribble.core.type.name.Role; +import org.scribble.core.type.session.Payload; + +// Relocate to util? +public class AutGraphParser +{ + private final Core core; + + public AutGraphParser(Core core) + { + this.core = core; + } + + public EGraph parse(String aut) + { + ModelFactory ef = this.core.config.mf; + + //Map> edges = new HashMap<>(); + Map> as = new HashMap<>(); + Map> succs = new HashMap<>(); + int init = -1; + try + { + BufferedReader br = new BufferedReader(new StringReader(aut)); + String line = br.readLine(); + if (line == null || !line.startsWith("des (") || !line.endsWith(")")) + { + throw new RuntimeException("Unexpected first line: " + line); + } + String[] first = line.substring("des (".length(), line.length() - 1).split(","); + if (first.length != 3) + { + throw new RuntimeException("Unexpected first line: " + line); + } + init = Integer.parseInt(first[0]); + //int trans = Integer.parseInt(first[1]); + //int states = Integer.parseInt(first[2]); + while ((line = br.readLine()) != null) + { + if (!line.startsWith("(") || !line.endsWith(")")) + { + throw new RuntimeException("Unexpected line: " + line); + } + //String[] read = line.substring(1, line.length()-1).split(","); + String[] read = new String[] { + line.substring(1, line.indexOf(',')), + line.substring(line.indexOf(',')+1, line.lastIndexOf(',')), + line.substring(line.lastIndexOf(',')+1, line.length()-1) + }; + int s = Integer.parseInt(read[0]); + String a = read[1].substring(1, read[1].length()-1); + int succ = Integer.parseInt(read[2]); + //Map tmp = edges.get(s); + List tmp1 = as.get(s); + List tmp2 = succs.get(s); + if (tmp1 == null) + { + //tmp = new HashMap<>(); + //edges.put(s, tmp); + tmp1 = new LinkedList<>(); + as.put(s, tmp1); + tmp2 = new LinkedList<>(); + succs.put(s, tmp2); + } + //tmp.put(a, succ); + tmp1.add(a); + tmp2.add(succ); + } + } + catch (IOException e) + { + throw new RuntimeException(e); + } + //Set allSuccs = edges.values().stream().flatMap((j) -> j.values().stream()).collect(Collectors.toSet()); + Set allSuccs = succs.values().stream().flatMap((j) -> j.stream()).collect(Collectors.toSet()); + int term = -1; + //Set terms = allSuccs.stream().filter((j) -> !edges.containsKey(j)).collect(Collectors.toSet()); + Set terms = allSuccs.stream().filter((j) -> !succs.containsKey(j)).collect(Collectors.toSet()); + if (terms.size() > 0) + { + term = terms.iterator().next(); + } + //EGraphBuilderUtil util = new EGraphBuilderUtil(ef); + //EGraphBuilderUtil util = this.job2.newEGraphBuilderUtil2(); + EGraphBuilderUtil util = this.core.config.mf.local.EGraphBuilderUtil(); + //util.init(null); // FIXME: arg is deprecated + Map map = new HashMap<>(); + map.put(init, util.getEntry()); + if (term != -1) + { + map.put(term, util.getExit()); + } + map.put(init, util.getEntry()); + //for (int i : edges.keySet()) + for (int i : as.keySet()) + { + if (i != init && i != term) + { + map.put(i, util.mf.local.EState(Collections.emptySet())); + } + } + //for (int i : succs) + for (int i : succs.keySet()) + { + if (!map.containsKey(i) && i != init && i != term) + { + map.put(i, util.mf.local.EState(Collections.emptySet())); + } + } + //for (int i : edges.keySet()) + for (int i : as.keySet()) + { + EState s = map.get(i); + //Map tmp = edges.get(i); + List tmp1 = as.get(i); + List tmp2 = succs.get(i); + //if (tmp != null) + if (tmp1 != null) + { + //for (String a : tmp.keySet()) + Iterator is = tmp2.iterator(); + for (String a : tmp1) + { + int succ = is.next(); + //builder.addEdge(s, parseIOAction(a), map.get(tmp.get(a))); + util.addEdge(s, parseIOAction(ef, a), map.get(succ)); + } + } + } + return util.finalise(); // Redundant, except that it creates the EGraph + //return new EGraph(util.getEntry(), util.getExit()); + } + + // Cf. getCommSymbol of IOActions + // FIXME: simply do a match for getCommSymbol? + private static EAction parseIOAction(ModelFactory ef, String a) + { + String peer; + String action; + String msg; // Could be an Op or a MessageSigName (affects API generation) + String[] paySplit = null; + + /*int i = a.indexOf("!"); + i = (i == -1) ? a.indexOf("?") : i; + int j = i+1; + String tmp = a.substring(j, j+1); + if (tmp.equals("!") || tmp.equals("?")) + { + j++; + } + action = a.substring(i, j);*/ + int i, j; + if ((i = a.indexOf("!")) != -1) + { + j = i+1; + if (a.charAt(j) == '!') + { + j++; + if (a.charAt(i-1) == '(') + { + if (a.charAt(j+1) != ')') + { + throw new RuntimeException("Shouldn't get in here: " + a); + } + i--; + j++; + } + } + } + else if ((i = a.indexOf("?")) != -1) + { + j = i+1; + if (a.charAt(j) == '?') + { + j++; + if (a.charAt(i-1) == '(') + { + if (a.charAt(j+1) != ')') + { + throw new RuntimeException("Shouldn't get in here: " + a); + } + i--; + j++; + } + } + } + else if ((i = a.indexOf('/')) != -1) + { + if (a.charAt(i-1) != '-' || a.charAt(i+1) != '-') + { + throw new RuntimeException("Shouldn't get in here: " + a); + } + j = i+2; + i--; + } + else + { + throw new RuntimeException("[TODO] aut parsing not supported for: " + a); + } + action = a.substring(i, j); + + peer = a.substring(0, i); + int k = a.indexOf("("); + msg = a.substring(j, k); + String p = a.substring(k+1, a.length()-1); + if (!p.isEmpty()) + { + paySplit = p.split(","); + } + switch (action) + { + case "!": + { + Payload pay = (paySplit != null) + ? new Payload(Arrays.asList(paySplit).stream() + .map((pe) -> new DataName(pe)).collect(Collectors.toList())) + : Payload.EMPTY_PAYLOAD; + return ef.local.ESend(new Role(peer), getMessageIdHack(msg), pay); // FIXME: how about MessageSigNames? -- currently OK, treated as empty payload (cf. ModelAction) + } + case "?": + { + Payload pay = (paySplit != null) + ? new Payload(Arrays.asList(paySplit).stream() + .map((pe) -> new DataName(pe)).collect(Collectors.toList())) + : Payload.EMPTY_PAYLOAD; + return ef.local.ERecv(new Role(peer), getMessageIdHack(msg), pay); // FIXME: how about MessageSigNames?) + } + case "!!": + { + //return new Connect(new Role(peer)); + Payload pay = (paySplit != null) + ? new Payload(Arrays.asList(paySplit).stream() + .map((pe) -> new DataName(pe)).collect(Collectors.toList())) + : Payload.EMPTY_PAYLOAD; + return ef.local.EReq(new Role(peer), getMessageIdHack(msg), pay); + } + case "??": + { + //return new Accept(new Role(peer)); + Payload pay = (paySplit != null) + ? new Payload(Arrays.asList(paySplit).stream() + .map((pe) -> new DataName(pe)).collect(Collectors.toList())) + : Payload.EMPTY_PAYLOAD; + return ef.local.EAcc(new Role(peer), getMessageIdHack(msg), pay); + } + case "(!!)": + { + return ef.local.EClientWrap(new Role(peer)); + } + case "(??)": + { + return ef.local.EServerWrap(new Role(peer)); + } + case "-/-": + { + return ef.local.EDisconnect(new Role(peer)); + } + default: + { + throw new RuntimeException( + "[TODO] aut parsing not supported for: " + msg); + } + } + } + + // Cf. ModelState.toAut, ModelAction.toStringWithMessageIdHack + private static MsgId getMessageIdHack(String msg) + { + return (msg.startsWith("^")) ? new SigName(msg.substring(1)) : new Op(msg); + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/model/endpoint/EFsm.java b/scribble-core/src/main/java/org/scribble/core/model/endpoint/EFsm.java new file mode 100644 index 000000000..288521005 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/model/endpoint/EFsm.java @@ -0,0 +1,121 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.model.endpoint; + +import java.util.List; +import java.util.stream.Collectors; + +import org.scribble.core.model.endpoint.actions.EAction; + +// Factor out with SModel? +public class EFsm +{ + public final EGraph graph; + public final EState curr; + + protected EFsm(EGraph graph) + { + this(graph, graph.init); + } + + protected EFsm(EGraph graph, EState curr) + { + this.graph = graph; + this.curr = curr; + } + + // CHECKME: Set? List is for non-det actions, but is that relevant to EFsm's? + // N.B. this just means "follow an edge", it is agnostic to an "actual semantics" (e.g., queues, queue sizes, etc.), cf. "fire" + public List getSuccs(EAction a) + { + return this.curr.getSuccs(a).stream().map(x -> new EFsm(this.graph, x)) + .collect(Collectors.toList()); + } + + // CHECKME: check if unfolded initial accept is possible, and if it breaks anything + public boolean isInitial() + { + return this.curr.equals(this.graph.init); // i.e., "literally" in the initial state (not "semantically") + } + + @Override + public final int hashCode() + { + int hash = 1049; + hash = 31 * hash + this.graph.init.hashCode(); + hash = 31 * hash + this.curr.hashCode(); + return hash; + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof EFsm)) + { + return false; + } + EFsm them = (EFsm) o; + return this.graph.equals(them.graph) && this.curr.equals(them.curr); + } + + @Override + public String toString() + { + return Integer.toString(this.curr.id); + } +} + + + + + + + + + + + + + + + + + /*public boolean isTerminated() + { + return this.curr.isTerminal(); + } + + public EStateKind getStateKind() + { + return this.curr.getStateKind(); + } + + public List getActions() + { + return this.curr.getActions(); + } + + public boolean hasAction(EAction a) + { + return this.curr.hasAction(a); + } + + public boolean isRequesttOrClientWrapOnly() + { + return this.curr.isRequestOrClientWrapOnly(); + }*/ diff --git a/scribble-core/src/main/java/org/scribble/core/model/endpoint/EGraph.java b/scribble-core/src/main/java/org/scribble/core/model/endpoint/EGraph.java new file mode 100644 index 000000000..0aacf17a6 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/model/endpoint/EGraph.java @@ -0,0 +1,76 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.model.endpoint; + +import org.scribble.core.model.MPrettyPrint; + +public class EGraph implements MPrettyPrint +{ + public final EState init; + public final EState term; + + //protected EGraph(EState init, EState term) // Use factory? + public EGraph(EState init, EState term) + { + this.init = init; + this.term = term; + } + + public EFsm toFsm() // CHECKME: refactor to mf? + { + return new EFsm(this); + } + + @Override + public String toDot() + { + return this.init.toDot(); + } + + @Override + public String toAut() + { + return this.init.toAut(); + } + + @Override + public String toString() + { + return this.init.toString(); + } + + @Override + public final int hashCode() + { + int hash = 1051; + hash = 31 * hash + this.init.hashCode(); // Use init state only, OK since state IDs globally unique + return hash; + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof EGraph)) + { + return false; + } + EGraph them = (EGraph) o; + return this.init.equals(them.init); + // && this.term.equals(them.term); // N.B. EState.equals checks state ID only, but OK because EStates have globally unique IDs -- any need to do a proper graph equality? + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/model/endpoint/EGraphBuilderUtil.java b/scribble-core/src/main/java/org/scribble/core/model/endpoint/EGraphBuilderUtil.java new file mode 100644 index 000000000..a413541a1 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/model/endpoint/EGraphBuilderUtil.java @@ -0,0 +1,353 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.model.endpoint; + +import java.util.Collections; +import java.util.Deque; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +import org.scribble.core.model.GraphBuilderUtil; +import org.scribble.core.model.ModelFactory; +import org.scribble.core.model.endpoint.actions.EAction; +import org.scribble.core.type.kind.Local; +import org.scribble.core.type.name.RecVar; + +// EGraphBuilderUtil usage contract (1): all states must be made via newState +// EGraphBuilderUtil usage contract (2): this.entry on leaving a node is the same as on entering +// Tailored to support graph building from syntactic local protocol choice and recursion +public class EGraphBuilderUtil + extends GraphBuilderUtil +{ + protected EState entry; // GraphBuilderUtil usage contract: entry on leaving a node is the same as on entering -- cf., EGraphBuilderUtil.visitSeq restores the original entry on leaving + protected EState exit; // Tracking exit is convenient for merges (otherwise have to generate dummy merge nodes) + + // N.B. new states should be made by this.newState, not this.mf.newEState + private final Set states = new HashSet<>(); + + // Entry state for each recursion + private final Map> recEntries = new HashMap<>(); // CHECKME: Deque is for shadowing? + + // Record enacting per-recvar, since a state could have multi-recvars -- CHECKME: caters for shadowing? (cf. recording only per unique recvar) + // CHECKME: for a given state, the enacting list is the same for each recvar? + private final Map> enacting = new HashMap<>(); + + // Temporary storage of enacting while collecting in progress + // First action(s) inside a rec scope ("enacting" means how to enact an unguarded choice-continue) + // These are collected by: + // - On each recursion entry, push a new list for its entry state -- list pushing/popping mainly for handling choices (see below) + // - (N.B. only need to do per state, not per rec(var) -- all recvars of a given state equivalently identify that state) + // - General idea: via addEdge, record the first action encountered for all "*open*" rec states, i.e., add the action to all current lists that are *still empty* + // - For choice: + // -- On choice entry, first push a new list for *all* rec states for recording the choice cases (all, including "non-open", because inconvenient to distinguish open/non-open from nested contexts) + // -- On block entry, push another new list for *all* rec states for recording the current block + // -- (Record, via addEdge, the first action of the current block for all open rec states) + // -- On block exit, pop the block list into the parent choice list for *all* rec states + // - On choice exit, pop the choice list into the parent (recursion/choice-block) list for all *open* rec states, i.e., if the parent list is *still empty* + // - On recursion exit, pop the list into the enacting map for the rec entry state + private final Map>> collecting = new HashMap<>(); + + protected EGraphBuilderUtil(ModelFactory mf) + { + super(mf); + reset(); + } + + // N.B. called before every "new visit", including first (so util is reusable) -- called by constructor and finalise + @Override + protected void reset() + { + //clear(); + this.entry = newState(Collections.emptySet()); + this.exit = newState(Collections.emptySet()); + } + + /*protected void clear() // CHECKME: redundant? -- ideally builder should be implemented so that it is redundant? + { + this.states.clear(); + this.recEntries.clear(); + this.enacting.clear(); + this.collecting.clear(); + }*/ + + // For the util to additionally record states -- use this, don't use this.mf.newEState + public EState newState(Set labs) + { + EState s = this.mf.local.EState(labs); + this.states.add(s); + return s; + } + + // Records 's' as predecessor state, and 'a' as previous action and the "enacting action" for "fresh" recursion scopes + @Override + public void addEdge(EState s, EAction a, EState succ) + { + super.addEdge(s, a, succ); + for (Deque> ens : this.collecting.values()) + { + List tmp = ens.peek(); // enterRecursion always adds an initial List to the Deque + if (tmp.isEmpty()) + { + tmp.add(a); + } + } + } + + /* + * Dealing with Choice contexts + */ + public void enterChoice() + { + for (EState entry : this.collecting.keySet()) + { + Deque> deq = this.collecting.get(entry); + deq.push(new LinkedList<>()); // Initially empty to record nested enablings in choice blocks + } + } + + public void leaveChoice() + { + for (EState entry : this.collecting.keySet()) + { + List pop = this.collecting.get(entry).pop(); + List peek = this.collecting.get(entry).peek(); + if (peek.isEmpty()) // Cf. addEdge + { + peek.addAll(pop); + } + } + } + + public void enterChoiceBlock() + { + for (EState entry : this.collecting.keySet()) + { + Deque> deq = this.collecting.get(entry); + deq.push(new LinkedList<>()); + } + } + + public void leaveChoiceBlock() + { + for (EState entry : this.collecting.keySet()) + { + List block = this.collecting.get(entry).pop(); + List blocks = this.collecting.get(entry).peek(); // Parent choice List + blocks.addAll(block); + } + } + + /* + * Dealing with Recursion contexts + */ + public void enterRecursion(RecVar rv, EState entry) + { + // Update this.recEntries + Deque recdeq = this.recEntries.get(rv); + if (recdeq == null) + { + recdeq = new LinkedList<>(); + this.recEntries.put(rv, recdeq); + } + recdeq.push(entry); // Same as this.entry + + // Udpate this.collecting, if necessary + if (this.collecting.containsKey(entry) || this.enacting.containsKey(entry)) + // Already doing/done this rec state for another of its recvar + // Does checking this.enacting do anything? + { + return; + } + Deque> coldeq = new LinkedList<>(); // New Deque for this recvar + this.collecting.put(entry, coldeq); // !this.collecting.containsKey(entry), leaveRecursion does remove -- necessary for addEdge/Choice to correctly add to this.collecting + coldeq.push(new LinkedList<>()); // Push new List onto deq + } + + public void leaveRecursion(RecVar rv) + { + // Update this.recEntries + EState entry = this.recEntries.get(rv).pop(); // Pop the entry of this rec + // Same as this.entry + // Because contract for GraphBuilderUtil is entry on leaving a node is the same as on entry, cf., EGraphBuilder.visitSeq restores original entry on leaving + // (And visitRecursion just does visitSeq for the recursion body, with the current entry/exit) + if (this.recEntries.get(rv).isEmpty()) + { + this.recEntries.remove(rv); // To keep util clean, e.g., for reuse + } + + // Udpate this.collecting, if necessary + if (!this.collecting.containsKey(entry)) + { + // This state already done -- i.e., already popped another recvar for this same state, e.g., good.efsm.gcontinue.choiceunguarded.Test05b + // (For a given state, the enacting for all associated recvars is the same (the recvars are "equivalently" identify the state) -- so only need to record per state) + return; + } + List coll = this.collecting.get(entry).pop(); + if (this.collecting.get(entry).isEmpty()) // All Lists popped from the stack of this recvar -- could just clear instead + { + this.collecting.remove(entry); + // N.B. we pushed on entry of *outermost rec*, but above popped on exit of *innermost* rec (due to checking entry in this.collecting) + // This remove is necessary to prevent above containsKey check also succeeding when leaving the outer rec, e.g., good.efsm.gcontinue.choiceunguarded.Test05b + // Also necessary to prevent continued updating of this.collecting after leaving a rec (because this.collecting still has entry), e.g., good.efsm.gchoice.Test10 + } + this.enacting.put(entry, coll); + // !this.enacting.containsKey(entry) -- if it did contain (remove enacting check from enterRecursion), this.enacting.get(entry).equals(coll) + } + + /* + * Edge construction for Continues + */ + public void fixContinueEdge(EState pred, EAction a, EState curr, RecVar rv) + { + removeEdgeAux(pred, a, curr); // N.B. "a" could be an enacting, that's fine (removeEdgeAux doesn't change that) + EState entry = getRecursionEntry(rv); + addEdge(pred, a, entry); + } + + // Choice-unguarded continues -- fixed in finalise pass + public void addUnguardedContinueEdge(EState s, RecVar rv) // Intermed continue edge makes its own dummy action + { + EState entry = getRecursionEntry(rv); + addEdgeAux(s, new UnguardedContinueEdge(this.mf, rv), entry); + } + + /*// CHECKME: update enacting? (cf. this.addEdge) + public void removeEdge(EState s, EAction a, EState succ) + throws ScribException + { + removeEdgeAux(s, a, succ); + }*/ + + public EState getRecursionEntry(RecVar recvar) + { + return this.recEntries.get(recvar).peek(); + } + + // Returns List (not Set), cf. getSuccs/Actions + public List getPreds(EState s) + { + // Easier to recompute than "cache" (this.preds), due to removeEdge(Aux)? Cf. addEdge (Or due to maintaining this.collecting/enacting) + // (Only currently used by visitContinue, so cost OK) + return this.states.stream().filter(x -> x.getSuccs().contains(s)) + .collect(Collectors.toList()); + } + + /* + * Finalise graph by treating IntermediateContinueEdges. + * Calls reset() on completion. + */ + public EGraph finalise() + { + EState entryClone = this.entry.cloneNode(this.mf, this.entry.getLabels()); + EState exitClone = this.exit.cloneNode(this.mf, this.exit.getLabels()); + Map clones = new HashMap<>(); // Will be mostly populated by fixUnguardedContinueEdges + clones.put(this.entry, entryClone); + clones.put(this.exit, exitClone); + Set seenOrig = new HashSet<>(); + fixUnguardedContinueEdges(seenOrig, clones, this.entry, entryClone); + if (!seenOrig.contains(this.exit)) + { + exitClone = null; + } + reset(); + return new EGraph(entryClone, exitClone); + } + + protected void fixUnguardedContinueEdges(Set seenOrig, + Map clones, EState currOrig, EState currClone) + { + if (seenOrig.contains(currOrig)) + { + return; + } + seenOrig.add(currOrig); + Iterator as = currOrig.getActions().iterator(); // Actions are immutable (no orig/clone) + Iterator succsOrig = currOrig.getSuccs().iterator(); + while (as.hasNext()) + { + EAction a = as.next(); + EState succOrig = succsOrig.next(); + if (!(a instanceof UnguardedContinueEdge)) + { + EState succClone = getClone(clones, succOrig); + addEdgeAux(currClone, a, succClone); + fixUnguardedContinueEdges(seenOrig, clones, succOrig, succClone); + } + else // Choice--unguardedcontedge-->succOrig, i.e., curr is a Choice, succOrig is a rec entry state + { + EState recEntry = succOrig; + for (EAction e : this.enacting.get(recEntry)) // recEntry--enacting-->succEntry + { + for (EState succEntry : recEntry.getSuccs(e)) + { + EState succEntryClone = getClone(clones, succEntry); // succEntryClone is a (cloned) successor of recEntry + addEdgeAux(currClone, e, succEntryClone); + // Choice--enacting-->succSuccClone, where succSuccClone is succ(rec-entry, enacting) (rec-entry is SuccOrig) + // i.e., skip recEntry + fixUnguardedContinueEdges(seenOrig, clones, recEntry, // Carry on from recEntry, that's where this edge was going "morally" + getClone(clones, recEntry)); + + // CHECKME: "transitive" (nested?) unguarded-continue-edge rewriting possible? supported? + // ...CHECKME: incomplete -- won't fully correctly handle situations involving, e.g., transitive continue-edge fixing? + + } + } + } + } + } + + private EState getClone(Map clones, EState orig) + { + if (clones.containsKey(orig)) + { + return clones.get(orig); + } + EState res = orig.cloneNode(this.mf, orig.getLabels()); + clones.put(orig, res); + return res; + } + + public void addEntryLabel(RecVar lab) + { + addEntryLabAux(this.entry, lab); + } + + public EState getEntry() + { + return this.entry; + } + + public void setEntry(EState entry) + { + this.entry = entry; + } + + public EState getExit() + { + return this.exit; + } + + public void setExit(EState exit) + { + this.exit = exit; + } +} + + diff --git a/scribble-core/src/main/java/org/scribble/core/model/endpoint/EModelFactory.java b/scribble-core/src/main/java/org/scribble/core/model/endpoint/EModelFactory.java new file mode 100644 index 000000000..1bd023d0c --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/model/endpoint/EModelFactory.java @@ -0,0 +1,46 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.model.endpoint; + +import java.util.Set; + +import org.scribble.core.model.endpoint.actions.EAcc; +import org.scribble.core.model.endpoint.actions.EClientWrap; +import org.scribble.core.model.endpoint.actions.EDisconnect; +import org.scribble.core.model.endpoint.actions.ERecv; +import org.scribble.core.model.endpoint.actions.EReq; +import org.scribble.core.model.endpoint.actions.ESend; +import org.scribble.core.model.endpoint.actions.EServerWrap; +import org.scribble.core.type.name.MsgId; +import org.scribble.core.type.name.RecVar; +import org.scribble.core.type.name.Role; +import org.scribble.core.type.session.Payload; + +public interface EModelFactory +{ + EGraphBuilderUtil EGraphBuilderUtil(); + + // protected constructors (MState mutable) + EState EState(Set labs); + //EFsm new EFsm(...) + + // public constructors (subpackage, immutable) + ESend ESend(Role peer, MsgId mid, Payload pay); + ERecv ERecv(Role peer, MsgId mid, Payload pay); + EReq EReq(Role peer, MsgId mid, Payload pay); + EAcc EAcc(Role peer, MsgId mid, Payload pay); + EDisconnect EDisconnect(Role peer); + EClientWrap EClientWrap(Role peer); + EServerWrap EServerWrap(Role peer); +} diff --git a/scribble-core/src/main/java/org/scribble/core/model/endpoint/EModelFactoryImpl.java b/scribble-core/src/main/java/org/scribble/core/model/endpoint/EModelFactoryImpl.java new file mode 100644 index 000000000..552b5facd --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/model/endpoint/EModelFactoryImpl.java @@ -0,0 +1,94 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.model.endpoint; + +import java.util.Set; + +import org.scribble.core.model.ModelFactory; +import org.scribble.core.model.ModelFactoryBase; +import org.scribble.core.model.endpoint.actions.EAcc; +import org.scribble.core.model.endpoint.actions.EClientWrap; +import org.scribble.core.model.endpoint.actions.EDisconnect; +import org.scribble.core.model.endpoint.actions.ERecv; +import org.scribble.core.model.endpoint.actions.EReq; +import org.scribble.core.model.endpoint.actions.ESend; +import org.scribble.core.model.endpoint.actions.EServerWrap; +import org.scribble.core.type.name.MsgId; +import org.scribble.core.type.name.RecVar; +import org.scribble.core.type.name.Role; +import org.scribble.core.type.session.Payload; + +// Separate E/SModelFactories fits protected E/SState constructor pattern +public class EModelFactoryImpl extends ModelFactoryBase implements EModelFactory +{ + + public EModelFactoryImpl(ModelFactory mf) + { + super(mf); + } + + @Override + public EGraphBuilderUtil EGraphBuilderUtil() + { + return new EGraphBuilderUtil(this.mf); + } + + @Override + public EState EState(Set labs) + { + return new EState(labs); + } + + @Override + public ESend ESend(Role peer, MsgId mid, Payload pay) + { + return new ESend(this.mf, peer, mid, pay); + } + + @Override + public ERecv ERecv(Role peer, MsgId mid, Payload pay) + { + return new ERecv(this.mf, peer, mid, pay); + } + + @Override + public EReq EReq(Role peer, MsgId mid, Payload pay) + { + return new EReq(this.mf, peer, mid, pay); + } + + @Override + public EAcc EAcc(Role peer, MsgId mid, Payload pay) + { + return new EAcc(this.mf, peer, mid, pay); + } + + @Override + public EDisconnect EDisconnect(Role peer) + { + return new EDisconnect(this.mf, peer); + } + + @Override + public EClientWrap EClientWrap(Role peer) + { + return new EClientWrap(this.mf, peer); + } + + @Override + public EServerWrap EServerWrap(Role peer) + { + return new EServerWrap(this.mf, peer); + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/model/endpoint/EState.java b/scribble-core/src/main/java/org/scribble/core/model/endpoint/EState.java new file mode 100644 index 000000000..e08a3162c --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/model/endpoint/EState.java @@ -0,0 +1,362 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.model.endpoint; + +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedHashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.Function; + +import org.scribble.core.model.MPrettyState; +import org.scribble.core.model.MState; +import org.scribble.core.model.ModelFactory; +import org.scribble.core.model.endpoint.actions.EAction; +import org.scribble.core.model.visit.local.EStateVisitor; +import org.scribble.core.type.kind.Local; +import org.scribble.core.type.name.RecVar; +import org.scribble.util.Pair; +import org.scribble.util.ScribException; + +// Label types used to be both RecVar and SubprotocolSigs; now using inlined protocol for FSM building so just RecVar +public class EState extends MPrettyState +{ + protected EState(Set labs) + { + super(labs); + } + + // To be overridden by subclasses, to obtain the subclass nodes + // CHECKME: remove labs arg, and modify the underlying Set if needed ? + protected EState cloneNode(ModelFactory mf, Set labs) + { + //return ef.newEState(this.labs); + return mf.local.EState(labs); + } + + // Fully clones the reachable graph (i.e. the "general" graph -- cf., EGraph, the specific Scribble concept of an endpoint protocol graph) + // N.B. cloning means the states, actions are immutable + protected EState clone(ModelFactory mf) + { + Map clones = new HashMap<>(); // Original s.id -> clone + Function getClone = x -> + { + EState clone = clones.get(x.id); // "clones" is effectively final + if (clone == null) + { + clone = x.cloneNode(mf, x.labs); + clones.put(x.id, clone); + } + return clone; + }; + Set all = getReachableStates(); + all.add(this); + for (EState s : all) // Quadratic after getReachableStates, but simpler code for now + { + Iterator as = s.getActions().iterator(); + Iterator succs = s.getSuccs().iterator(); + EState clone = getClone.apply(s); + while (as.hasNext()) + { + clone.addEdge(as.next(), getClone.apply(succs.next())); + } + } + return clones.get(this.id); + } + + // Pre: succ is the root of the subgraph, and succ is a successor of *"this"* (which is inside the subgraph) + // i.e., this-a->succ ("a" is possibly non-det) + // Returns the clone of the subgraph rooted at succ, with all non- "this-a->succ" actions pruned from the clone of "this" state + // i.e., we took "a" from "this" to get to succ (the subgraph root); if we enter "this" again (inside the subgraph), then always take "a" again + // N.B. cloning means the states, actions are immutable + // Consider gproto annotations to specify which states to unfair-clone, i.e., choice-specific fairness + private EState unfairCloneSubgraph(ModelFactory mf, EState term, EAction a, EState succ) // Need succ param for non-det + { + Map clones = new HashMap<>(); // Original s.id -> clone + Function getClone = x -> + { + EState clone = clones.get(x.id); // "clones" is effectively final + if (clone == null) + { + clone = (term != null && x.id == term.id) + ? term + // Special case: term not cloned, otherwise a mixture of exapanded (and non-expanded) cases may lead to the term being cloned... + // ...potentially multiple times and potentially while the original still remains + : x.cloneNode(mf, Collections.emptySet()); + // CHECKME: remove labs arg from cloneNode and just clear the lab set here ? + // Cf. clone, keeps x.labs + clones.put(x.id, clone); + } + return clone; + }; + Set all = succ.getReachableStates(); + all.add(succ); + for (EState s : all) // Quadratic after getReachableStates, but simpler code for now + { + Iterator as = s.getActions().iterator(); + Iterator succs = s.getSuccs().iterator(); + EState clone = getClone.apply(s); + boolean done = false; + // Restricts adding of *at most* one "this-a->succ" edge out of potentially multiple non-det "a" + // i.e., unfair expansion prunes non-det "a" ("determinizes" entry) from "this" into the cloned subgraph + // Cf. MState.addEdge(A, S), previously implicitly pruned all non-det "this-a->s" for the same "s" + while (as.hasNext()) + { + EAction na = as.next(); + EState ns = succs.next(); + if (s.id != this.id) + { + clone.addEdge(na, getClone.apply(ns)); + } + else if (na.equals(a) && ns.equals(succ) && !done) + // Non-det (to different succ) also pruned from clone of this -- but OK? non-det still preserved on original state, so any safety violations due to non-det will still come out?... + // ...this is like non-fairness extended to defeat even non-determinism ? + { + // s.id == this.id, so "clone" is the clone of "this" + clone.addEdge(na, getClone.apply(ns)); + done = true; + } + } + } + return clones.get(succ.id); + } + + + /* Returns Pair<>(init, term) + * + .. use getallreachable to get subgraph, make a graph clone method + .. for each poly output, clone a (non-det) edge to clone of the reachable subgraph with the clone of the current node pruned to this single choice + .. be careful of original non-det edges, need to do each separately + .. do recursively on the subgraphs, will end up with a normal form with subgraphs without output choices + .. is it equiv to requiring all roles to see every choice path? except initial accepting roles -- yes + .. easier to implement as a direct check on the standard global model, rather than model hacking -- i.e. liveness is not just about terminal sets, but about "branching condition", c.f. julien? + .. the issue is connect/accept -- makes direct check a bit more complicated, maybe value in doing it by model hacking to rely on standard liveness checking? + .. should be fine, check set of roles on each path is equal, except for accept-guarded initial roles + */ + public Pair unfairTransform(ModelFactory mf) + { + EState init = clone(mf); // All state refs from here on are clones, original Graph unmodified + EState term = init.getTerminal(); + Set seen = new HashSet<>(); + Set todo = new LinkedHashSet<>(); // Linked unnecessary, but to follow the iteration pattern + todo.add(init); + while (!todo.isEmpty()) + { + Iterator i = todo.iterator(); + EState curr = i.next(); + i.remove(); + if (seen.contains(curr)) + // Convenient to check here (even though may get curr multiple times) to avoid doing the check before every todo.add + // N.B. todo is also aliased from expandUnfairCases + { + continue; + } + seen.add(curr); + + if (curr.getStateKind() == EStateKind.OUTPUT + && curr.getActions().size() > 1) // >1 makes this algorithm terminating -- in the expanded subgraph, the clone of curr will have all other edges pruned + { + expandUnfairCases(mf, term, todo, curr); + } + else + { + todo.addAll(curr.getSuccs()); + } + } + return new Pair<>(init, term); + } + + // N.B. todo alias from unfairTransform -- refactor as return? (slower) + // Pre: curr.getStateKind() == EStateKind.OUTPUT && curr.getActions().size() > 1 + // All involved states are already clones + private void expandUnfairCases(ModelFactory mf, EState term, Set todo, + EState curr) + { + Iterator as = curr.getActions().iterator(); + Iterator succs = curr.getSuccs().iterator(); + List aclones = new LinkedList<>(); // Actions involved in clones (not actually cloned themselves, immutable) + List succClones = new LinkedList<>(); + Map> toRemove = new HashMap<>(); // Original succ -> actions "a" where "curr-a->succ" + // List needed to handle removing multiple edges to the same state: e.g. mu X.(A->B:1 + A->B:2).X + + while (as.hasNext()) + { + EAction a = as.next(); + EState succ = succs.next(); + if (!succ.canReach(curr)) // Do unfairCloneSubgraph for each (potentially) "recursive" action + { + todo.add(succ); + continue; + } + EState succClone = curr.unfairCloneSubgraph(mf, term, a, succ); // succ is a successor of curr + aclones.add(a); + succClones.add(succClone); + List tmp = toRemove.get(succ); + if (tmp == null) + { + tmp = new LinkedList<>(); + toRemove.put(succ, tmp); + } + tmp.add(a); // To replace original edge with new edge into unfair-cloned subgraph + } + + if (!aclones.isEmpty()) // Redundant (toRemove would also be empty), but more clear + { + for (EState succ : toRemove.keySet()) + { + for (EAction a1 : toRemove.get(succ)) + { + curr.removeEdge(a1, succ); // First, remove original edge to original succ + } + } + Iterator iaclones = aclones.iterator(); + Iterator isuccClones = succClones.iterator(); + while (iaclones.hasNext()) + { + EAction a = iaclones.next(); // Same actions involved in toRemove loop above + EState succClone = isuccClones.next(); // Clones of the succs involved in toRemove loop above + curr.addEdge(a, succClone); // Second, add edge to cloned succ (entry to the unfair-cloned subgraph) + todo.add(succClone); // This will cause unfairTransform to "recursively" visit the nodes of the unfair-cloned subgraph + // Doesn't work if non-det preserved by the "unfairClone" aux (recursively, edges always >1 -- termination condition never met) + // Idea is to bypass succ clone (for non-det, edges>1) but in general this will be cloned again before returning to it, so bypass doesn't work -- to solve this more generally probably need to keep a record of all clones to bypass future clones + } + } + } + + // CHECKME: make an isSync in IOAction ? + // This state is a *necessarily* "blocking" output sync-client (request, clientwrap) state + public boolean isSyncClientOnly() + { + return getStateKind() == EStateKind.OUTPUT + && getActions().stream() + .allMatch(x -> x.isRequest() || x.isClientWrap()); + } + + // CHECKME: return + public void traverse(EStateVisitor v) throws ScribException + { + visitState(v); // "visitNode" + + // "visitChildren" + Iterator as = this.actions.iterator(); + Iterator succs = this.succs.iterator(); + while (as.hasNext()) + { + EAction a = as.next(); + EState succ = succs.next(); + if (!v.hasSeen(succ)) // cf. EdgeVisitor + { + succ.traverse(v.enter(this, a, succ)); + } + } + } + + protected void visitState(EStateVisitor v) throws ScribException + { + // "visitNode" + EStateKind kind = getStateKind(); // CHECKME: explicitly cache kind in EState? this lookup is slow? + switch (kind) + { + case ACCEPT: v.visitAccept(this); break; + case OUTPUT: v.visitOutput(this); break; + case POLY_RECIEVE: v.visitPolyInput(this); break; + case SERVER_WRAP: v.visitServerWrap(this); break; + case TERMINAL: v.visitTerminal(this); break; + case UNARY_RECEIVE: v.visitUnaryInput(this); break; + default: throw new RuntimeException("Unknown state kind: " + kind); + } + } + + public EStateKind getStateKind() + { + List as = this.getActions(); + if (as.size() == 0) + { + return EStateKind.TERMINAL; + } + else + { + if (as.stream() + .allMatch(a -> a.isSend() || a.isRequest() || a.isClientWrap())) // ClientWrap should be unary? + { + return EStateKind.OUTPUT; + } + else if (as.stream().allMatch(EAction::isReceive)) + { + return (as.size() == 1) ? EStateKind.UNARY_RECEIVE : EStateKind.POLY_RECIEVE; + } + else if (as.stream().allMatch(EAction::isAccept)) + { + return EStateKind.ACCEPT; // Distinguish unary for API gen? cf. receive + } + else if (as.size() == 1 && as.get(0).isDisconnect()) + { + return EStateKind.OUTPUT; + } + else if (as.size() == 1 && as.get(0).isServerWrap()) + { + return EStateKind.SERVER_WRAP; + } + else + { + throw new RuntimeException("Shouldn't get in here: " + as); + } + } + } + + /*// Helper factory method for deriving an EGraph from an arbitary EState (but not the primary way to construct EGraphs; cf., EGraphBuilderUtil) + public EGraph toGraph() + { + return new EGraph(this, getTerminal()); // Throws exception if >1 terminal; null if no terminal + }*/ + + @Override + public Set getReachableStates() // CHECKME: consider a "lazy" version? Maybe as an Iterator or Stream + { + return getReachableStatesAux(this); + } + + @Override + public int hashCode() + { + int hash = 83; + hash = 31 * hash + super.hashCode(); // N.B. ultimately uses state ID only + return hash; + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof EState)) + { + return false; + } + return super.equals(o); // Checks canEquals + } + + @Override + protected boolean canEquals(MState s) + { + return s instanceof EState; + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/model/endpoint/EStateKind.java b/scribble-core/src/main/java/org/scribble/core/model/endpoint/EStateKind.java new file mode 100644 index 000000000..1144bc836 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/model/endpoint/EStateKind.java @@ -0,0 +1,25 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.model.endpoint; + +// CHECKME: consider that enums cannot be "extended", for Scribble extensions +public enum EStateKind +{ + TERMINAL, + OUTPUT, // SEND, REQUEST and CLIENT_WRAP + UNARY_RECEIVE, + POLY_RECIEVE, + ACCEPT, // CHECKME: distinguish unary/multi accept? + SERVER_WRAP, +} diff --git a/scribble-core/src/main/java/org/scribble/core/model/endpoint/UnguardedContinueEdge.java b/scribble-core/src/main/java/org/scribble/core/model/endpoint/UnguardedContinueEdge.java new file mode 100644 index 000000000..4244bfdd4 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/model/endpoint/UnguardedContinueEdge.java @@ -0,0 +1,76 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.model.endpoint; + +import org.scribble.core.model.ModelFactory; +import org.scribble.core.model.endpoint.actions.EAction; +import org.scribble.core.model.global.actions.SAction; +import org.scribble.core.type.name.Op; +import org.scribble.core.type.name.RecVar; +import org.scribble.core.type.name.Role; +import org.scribble.core.type.session.Payload; + +class UnguardedContinueEdge extends EAction +{ + public UnguardedContinueEdge(ModelFactory mf, RecVar rv) + { + super(mf, Role.EMPTY_ROLE, new Op(rv.toString()), Payload.EMPTY_PAYLOAD); // HACK + } + + @Override + public EAction toDual(Role self) + { + throw new RuntimeException("Shouldn't get in here: " + this); + } + + @Override + public SAction toGlobal(Role self) + { + throw new RuntimeException("Shouldn't get in here: " + this); + } + + @Override + protected String getCommSymbol() + { + return "#"; + } + + @Override + public int hashCode() + { + int hash = 1021; + hash = 31 * hash + super.hashCode(); + return hash; + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof UnguardedContinueEdge)) + { + return false; + } + return super.equals(o); // Checks canEquals + } + + @Override + public boolean canEquals(Object o) + { + return o instanceof UnguardedContinueEdge; + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/model/endpoint/actions/EAcc.java b/scribble-core/src/main/java/org/scribble/core/model/endpoint/actions/EAcc.java new file mode 100644 index 000000000..48be5be4d --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/model/endpoint/actions/EAcc.java @@ -0,0 +1,79 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.model.endpoint.actions; + +import org.scribble.core.model.ModelFactory; +import org.scribble.core.model.global.actions.SAcc; +import org.scribble.core.type.name.MsgId; +import org.scribble.core.type.name.Role; +import org.scribble.core.type.session.Payload; + +public class EAcc extends EAction +{ + public EAcc(ModelFactory mf, Role peer, MsgId mid, Payload pay) + { + super(mf, peer, mid, pay); + } + + @Override + public EReq toDual(Role self) + { + return this.mf.local.EReq(self, this.mid, this.payload); + } + + @Override + public SAcc toGlobal(Role self) + { + return this.mf.global.SAcc(self, this.peer, this.mid, this.payload); + } + + @Override + public int hashCode() + { + int hash = 937; + hash = 31 * hash + super.hashCode(); + return hash; + } + + @Override + public boolean isAccept() + { + return true; + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof EAcc)) + { + return false; + } + return super.equals(o); // Does canEquals + } + + public boolean canEquals(Object o) + { + return o instanceof EAcc; + } + + @Override + protected String getCommSymbol() + { + return "??"; + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/model/endpoint/actions/EAction.java b/scribble-core/src/main/java/org/scribble/core/model/endpoint/actions/EAction.java new file mode 100644 index 000000000..f6fdbaa33 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/model/endpoint/actions/EAction.java @@ -0,0 +1,122 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.model.endpoint.actions; + +import org.scribble.core.model.MAction; +import org.scribble.core.model.ModelFactory; +import org.scribble.core.model.global.actions.SAction; +import org.scribble.core.type.kind.Local; +import org.scribble.core.type.name.MsgId; +import org.scribble.core.type.name.Role; +import org.scribble.core.type.session.Payload; + +public abstract class EAction extends MAction +{ + public final Role peer; + + protected final ModelFactory mf; // Internalising better ensures all constructions points (in a Scrib extension) consistently use the same ef/sf + + protected EAction(ModelFactory mf, Role peer, MsgId mid, Payload pay) + { + super(peer, mid, pay); + this.peer = peer; + this.mf = mf; + } + + // "self" means self of "this" (self of dual is this.peer) + public abstract EAction toDual(Role self); + public abstract SAction toGlobal(Role self); + + public boolean isSend() + { + return false; + } + + public boolean isReceive() + { + return false; + } + + public boolean isRequest() + { + return false; + } + + public boolean isDisconnect() + { + return false; + } + + public boolean isAccept() + { + return false; + } + + public boolean isClientWrap() + { + return false; + } + + public boolean isServerWrap() + { + return false; + } +} + + + + + + + + + + + + + + /*@Override + public String toString() + { + return this.peer + getCommSymbol() + this.mid + this.payload; + } + + protected abstract String getCommSymbol();*/ + + /*@Override + public int hashCode() + { + int hash = 919; + hash = 31 * hash + super.hashCode(); + hash = 31 * hash + this.peer.hashCode(); // No: peer is this.obj + return hash; + }*/ + + /*@Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof IOAction)) + { + return false; + } + IOAction a = (IOAction) o; + return a.canEqual(this) && + this.peer.equals(a.peer) && this.mid.equals(a.mid) && this.payload.equals(a.payload); + } + + public abstract boolean canEqual(Object o);*/ diff --git a/scribble-core/src/main/java/org/scribble/core/model/endpoint/actions/EClientWrap.java b/scribble-core/src/main/java/org/scribble/core/model/endpoint/actions/EClientWrap.java new file mode 100644 index 000000000..a72ac7545 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/model/endpoint/actions/EClientWrap.java @@ -0,0 +1,82 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.model.endpoint.actions; + +import org.scribble.core.model.ModelFactory; +import org.scribble.core.model.global.actions.SClientWrap; +import org.scribble.core.type.name.Op; +import org.scribble.core.type.name.Role; +import org.scribble.core.type.session.Payload; + +// Wrap at the client side +// Duplicated from Disconnect +public class EClientWrap extends EAction +{ + public EClientWrap(ModelFactory ef, Role peer) + { + super(ef, peer, Op.EMPTY_OP, Payload.EMPTY_PAYLOAD); // Must correspond with GWrap.UNIT_MESSAGE_SIG_NODE + } + + @Override + public EServerWrap toDual(Role self) + { + return this.mf.local.EServerWrap(self); + } + + @Override + public SClientWrap toGlobal(Role self) + { + return this.mf.global.SClientWrap(self, this.peer); + } + + @Override + public int hashCode() + { + int hash = 1061; + hash = 31 * hash + super.hashCode(); + return hash; + } + + @Override + public boolean isClientWrap() + { + return true; + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof EClientWrap)) + { + return false; + } + return super.equals(o); // Does canEquals + } + + @Override + public boolean canEquals(Object o) + { + return o instanceof EClientWrap; + } + + @Override + protected String getCommSymbol() + { + return "(!!)"; + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/model/endpoint/actions/EDisconnect.java b/scribble-core/src/main/java/org/scribble/core/model/endpoint/actions/EDisconnect.java new file mode 100644 index 000000000..e22b334d2 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/model/endpoint/actions/EDisconnect.java @@ -0,0 +1,81 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.model.endpoint.actions; + +import org.scribble.core.model.ModelFactory; +import org.scribble.core.model.global.actions.SDisconnect; +import org.scribble.core.type.name.Op; +import org.scribble.core.type.name.Role; +import org.scribble.core.type.session.Payload; + +public class EDisconnect extends EAction +{ + public EDisconnect(ModelFactory ef, Role peer) + { + super(ef, peer, Op.EMPTY_OP, Payload.EMPTY_PAYLOAD); // Must correspond with GDisconnect.UNIT_MESSAGE_SIG_NODE + } + + @Override + public EDisconnect toDual(Role self) + { + return this; + } + + @Override + public SDisconnect toGlobal(Role self) + { + return this.mf.global.SDisconnect(self, this.peer); + } + + @Override + public boolean isDisconnect() + { + return true; + } + + @Override + public int hashCode() + { + int hash = 1009; + hash = 31 * hash + super.hashCode(); + return hash; + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof EDisconnect)) + { + return false; + } + return super.equals(o); // Does canEquals + } + + @Override + public boolean canEquals(Object o) + { + return o instanceof EDisconnect; + } + + @Override + protected String getCommSymbol() + { + //return "\u00A1\u00A1"; + return "-/-"; + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/model/endpoint/actions/ERecv.java b/scribble-core/src/main/java/org/scribble/core/model/endpoint/actions/ERecv.java new file mode 100644 index 000000000..48d8311c9 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/model/endpoint/actions/ERecv.java @@ -0,0 +1,82 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.model.endpoint.actions; + +import org.scribble.core.model.ModelFactory; +import org.scribble.core.model.global.actions.SRecv; +import org.scribble.core.type.name.MsgId; +import org.scribble.core.type.name.Role; +import org.scribble.core.type.session.Payload; + +public class ERecv extends EAction +{ + + public ERecv(ModelFactory ef, Role peer, MsgId mid, Payload pay) + { + super(ef, peer, mid, pay); + } + + @Override + public ESend toDual(Role self) + { + return this.mf.local.ESend(self, this.mid, this.payload); + } + + @Override + public SRecv toGlobal(Role self) + { + return this.mf.global.SRecv(self, this.peer, this.mid, this.payload); + + } + + @Override + public int hashCode() + { + int hash = 947; + hash = 31 * hash + super.hashCode(); + return hash; + } + + @Override + public boolean isReceive() + { + return true; + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof ERecv)) + { + return false; + } + return super.equals(o); // Does canEquals + } + + @Override + public boolean canEquals(Object o) + { + return o instanceof ERecv; + } + + @Override + protected String getCommSymbol() + { + return "?"; + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/model/endpoint/actions/EReq.java b/scribble-core/src/main/java/org/scribble/core/model/endpoint/actions/EReq.java new file mode 100644 index 000000000..65dfe0af9 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/model/endpoint/actions/EReq.java @@ -0,0 +1,80 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.model.endpoint.actions; + +import org.scribble.core.model.ModelFactory; +import org.scribble.core.model.global.actions.SReq; +import org.scribble.core.type.name.MsgId; +import org.scribble.core.type.name.Role; +import org.scribble.core.type.session.Payload; + +public class EReq extends EAction +{ + public EReq(ModelFactory ef, Role peer, MsgId mid, Payload pay) + { + super(ef, peer, mid, pay); + } + + @Override + public EAcc toDual(Role self) + { + return this.mf.local.EAcc(self, this.mid, this.payload); + } + + @Override + public SReq toGlobal(Role self) + { + return this.mf.global.SReq(self, this.peer, this.mid, this.payload); + } + + @Override + public int hashCode() + { + int hash = 929; + hash = 31 * hash + super.hashCode(); + return hash; + } + + @Override + public boolean isRequest() + { + return true; + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof EReq)) + { + return false; + } + return super.equals(o); // Does canEquals + } + + @Override + public boolean canEquals(Object o) + { + return o instanceof EReq; + } + + @Override + protected String getCommSymbol() + { + return "!!"; + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/model/endpoint/actions/ESend.java b/scribble-core/src/main/java/org/scribble/core/model/endpoint/actions/ESend.java new file mode 100644 index 000000000..127081efb --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/model/endpoint/actions/ESend.java @@ -0,0 +1,81 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.model.endpoint.actions; + +import org.scribble.core.model.ModelFactory; +import org.scribble.core.model.global.actions.SSend; +import org.scribble.core.type.name.MsgId; +import org.scribble.core.type.name.Role; +import org.scribble.core.type.session.Payload; + +public class ESend extends EAction +{ + + public ESend(ModelFactory ef, Role peer, MsgId mid, Payload pay) + { + super(ef, peer, mid, pay); + } + + @Override + public ERecv toDual(Role self) + { + return this.mf.local.ERecv(self, this.mid, this.payload); + } + + @Override + public SSend toGlobal(Role self) + { + return this.mf.global.SSend(self, this.peer, this.mid, this.payload); + } + + @Override + public int hashCode() + { + int hash = 953; + hash = 31 * hash + super.hashCode(); + return hash; + } + + @Override + public boolean isSend() + { + return true; + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof ESend)) + { + return false; + } + return super.equals(o); // Does canEquals + } + + @Override + public boolean canEquals(Object o) + { + return o instanceof ESend; + } + + @Override + protected String getCommSymbol() + { + return "!"; + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/model/endpoint/actions/EServerWrap.java b/scribble-core/src/main/java/org/scribble/core/model/endpoint/actions/EServerWrap.java new file mode 100644 index 000000000..3d2258042 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/model/endpoint/actions/EServerWrap.java @@ -0,0 +1,82 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.model.endpoint.actions; + +import org.scribble.core.model.ModelFactory; +import org.scribble.core.model.global.actions.SServerWrap; +import org.scribble.core.type.name.Op; +import org.scribble.core.type.name.Role; +import org.scribble.core.type.session.Payload; + +// Wrap at the server side +// Duplicated from Disconnect +public class EServerWrap extends EAction +{ + public EServerWrap(ModelFactory ef, Role peer) + { + super(ef, peer, Op.EMPTY_OP, Payload.EMPTY_PAYLOAD); // Must correspond with GWrap.UNIT_MESSAGE_SIG_NODE + } + + @Override + public EClientWrap toDual(Role self) + { + return this.mf.local.EClientWrap(self); + } + + @Override + public SServerWrap toGlobal(Role self) + { + return this.mf.global.SServerWrap(self, this.peer); + } + + @Override + public int hashCode() + { + int hash = 1063; + hash = 31 * hash + super.hashCode(); + return hash; + } + + @Override + public boolean isServerWrap() + { + return true; + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof EServerWrap)) + { + return false; + } + return super.equals(o); // Does canEquals + } + + @Override + public boolean canEquals(Object o) + { + return o instanceof EServerWrap; + } + + @Override + protected String getCommSymbol() + { + return "(??)"; + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/model/global/SConfig.java b/scribble-core/src/main/java/org/scribble/core/model/global/SConfig.java new file mode 100644 index 000000000..3391b5d4e --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/model/global/SConfig.java @@ -0,0 +1,455 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.model.global; + +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.scribble.core.model.ModelFactory; +import org.scribble.core.model.endpoint.EFsm; +import org.scribble.core.model.endpoint.EState; +import org.scribble.core.model.endpoint.EStateKind; +import org.scribble.core.model.endpoint.actions.EAcc; +import org.scribble.core.model.endpoint.actions.EAction; +import org.scribble.core.model.endpoint.actions.EDisconnect; +import org.scribble.core.model.endpoint.actions.ERecv; +import org.scribble.core.model.endpoint.actions.EReq; +import org.scribble.core.model.endpoint.actions.ESend; +import org.scribble.core.model.endpoint.actions.EClientWrap; +import org.scribble.core.model.endpoint.actions.EServerWrap; +import org.scribble.core.type.name.Role; + +// Immutable -- async/sync (i.e, "fire") return updated copies (in the general case, they must return List anyway due to non-det) +public class SConfig +{ + protected final ModelFactory mf; + + public final Map efsms; + public final SingleBuffers queues; // N.B. currently hardcoded to capacity one + + protected SConfig(ModelFactory mf, Map state, SingleBuffers queues) + { + this.mf = mf; + this.efsms = Collections.unmodifiableMap(state); + this.queues = queues; + } + + // N.B. Set (not List> getFireable() + { + Map> res = new HashMap<>(); + for (Role self : this.efsms.keySet()) + { + EFsm fsm = this.efsms.get(self); + Set as = new LinkedHashSet<>(); + switch (fsm.curr.getStateKind()) // Choice subject enabling needed for non-mixed states (mixed states would be needed for async. permutations though) + { + // Currently not convenient to delegate to states, as state types not distinguished + case TERMINAL: break; + case OUTPUT: as.addAll(getOutputFireable(self, fsm)); break; + case UNARY_RECEIVE: + case POLY_RECIEVE: + as.addAll(getReceiveFireable(self, fsm)); // addAll for generic typing + break; + case ACCEPT: as.addAll(getAcceptFireable(self, fsm)); break; + case SERVER_WRAP: as.addAll(getServerWrapFireable(self, fsm)); break; + default: throw new RuntimeException("Unknown state kind: " + fsm); + } + if (!as.isEmpty()) // Guards against res.put for empty "as", but perhaps unnecessary? + { + res.put(self, as); + } + } + return res; + } + + // Pre: fsm.curr.getStateKind() == EStateKind.OUTPUT + // fsm is self's Efsm + // (N.B. return Set, not List -- see getFireable) + protected Set getOutputFireable(Role self, EFsm fsm) // "output" and "client" actions + { + Set res = new LinkedHashSet<>(); + for (EAction a : fsm.curr.getActions()) // Actions may be a mixture of the following cases + { + // Async + if (a.isSend() || a.isDisconnect()) // For disconnect, only one "a" + { + if ((a.isSend() && this.queues.canSend(self, (ESend) a)) + || (a.isDisconnect() + && this.queues.canDisconnect(self, (EDisconnect) a))) + { + res.add(a); + } + } + // Sync + else if (a.isRequest() || a.isClientWrap()) + { + if ((a.isRequest() && this.queues.canRequest(self, (EReq) a)) + || (a.isClientWrap() + && this.queues.canClientWrap(self, (EClientWrap) a))) + { + if (this.efsms.get(a.peer).curr.getActions().stream() + .anyMatch(x -> a.toDual(self).equals(x))) // anyMatch (i.e., add "a" at most once), cf. getAcceptable + { + res.add(a); + } + } + } + else + { + throw new RuntimeException("Unknown output action kind: " + a); + } + } + return res; + } + + // Pre: fsm.curr.getStateKind() == EStateKind.UNARY_RECEIVE or POLY_RECIEVE + // Unary or poly receive + // (N.B. return Set, not List -- see getFireable) + protected Set getReceiveFireable(Role self, EFsm fsm) + { + return fsm.curr.getActions().stream().map(x -> (ERecv) x) + .filter(x -> this.queues.canReceive(self, x)) + .collect(Collectors.toSet()); + } + + // Pre: fsm.curr.getStateKind() == EStateKind.ACCEPT + // (N.B. return Set, not List -- see getFireable) + protected Set getAcceptFireable(Role self, EFsm fsm) + { + List as = fsm.curr.getActions(); + Role peer = as.get(0).peer; // All peer's the same + List peeras = this.efsms.get(peer).curr.getActions(); + return fsm.curr.getActions().stream().map(x -> (EAcc) x) + .filter(x -> this.queues.canAccept(self, x) + && peeras.stream().anyMatch(y -> y.toDual(peer).equals(x))) + .collect(Collectors.toSet()); + } + + // Pre: fsm.curr.getStateKind() == EStateKind.SERVER_WRAP + // (N.B. return Set, not List -- see getFireable) + // Duplicated from getAcceptFireable + protected Set getServerWrapFireable(Role self, EFsm fsm) + { + List as = fsm.curr.getActions(); // Actually for ServerWrap, size() == 1 + Role peer = as.get(0).peer; // All peer's the same + List peeras = this.efsms.get(peer).curr.getActions(); + return fsm.curr.getActions().stream().map(x -> (EServerWrap) x) + .filter(x -> this.queues.canServerWrap(self, x) + && peeras.stream().anyMatch(y -> y.toDual(peer).equals(x))) + .collect(Collectors.toSet()); + } + + // Pre: getFireable().get(self).contains(a) + // Here, produce a List that distinguishes non-det to identical configs -- CHECKME: shouldn't? (Set would be sufficient for non-det to different configs) + // (Actual global model building (e.g., SGraphBuilderUtil.getSuccs) will collapse identical configs) + public List async(Role self, EAction a) + { + List res = new LinkedList<>(); + List succs = this.efsms.get(self).getSuccs(a); + for (EFsm succ : succs) + { + Map efsms = new HashMap<>(this.efsms); + efsms.put(self, succ); + SingleBuffers queues = // N.B. queue updates are insensitive to non-det "a" + a.isSend() ? this.queues.send(self, (ESend) a) + : a.isReceive() ? this.queues.receive(self, (ERecv) a) + : a.isDisconnect() ? this.queues.disconnect(self, (EDisconnect) a) + : null; + if (queues == null) + { + throw new RuntimeException("Shouldn't get in here: " + a); + } + res.add(this.mf.global.SConfig(efsms, queues)); + } + return res; + } + + // "Synchronous version" of fire + // Pre: getFireable().get(r1).contains(a1) && getFireable().get(r2).contains(a2), where a1 and a2 are a "sync" pair (e.g., matching message) + // Here, produce a List that distinguishes non-det to identical configs -- CHECKME: shouldn't? (Set would be sufficient for non-det to different configs) + // (Actual global model building (e.g., SGraphBuilderUtil.getSuccs) will collapse identical configs) + public List sync(Role r1, EAction a1, Role r2, EAction a2) + { + List res = new LinkedList<>(); + List succs1 = this.efsms.get(r1).getSuccs(a1); + List succs2 = this.efsms.get(r2).getSuccs(a2); + for (EFsm succ1 : succs1) + { + for (EFsm succ2 : succs2) + { + Map efsms = new HashMap<>(this.efsms); + // a1 and a2 are a "sync" pair, add all combinations of succ1 and succ2 that may arise + efsms.put(r1, succ1); // Overwrite existing r1/r2 entries + efsms.put(r2, succ2); + SingleBuffers queues; + // a1 and a2 definitely "sync", now just determine whether it is a connect or wrap + if (((a1.isRequest() && a2.isAccept()) + || (a1.isAccept() && a2.isRequest()))) + { + queues = this.queues.connect(r1, r2); // N.B. queue updates are insensitive to non-det "a" + } + else if (((a1.isClientWrap() && a2.isServerWrap()) + || (a1.isServerWrap() && a2.isClientWrap()))) + { + // Doesn't affect queue state + queues = this.queues; // OK, immutable? + } + else + { + throw new RuntimeException("Shouldn't get in here: " + a1 + ", " + a2); + } + res.add(this.mf.global.SConfig(efsms, queues)); + } + } + return res; + } + + /*// CHECKME: rename -- not just termination, could be unconnected/uninitiated + public boolean isSafeTermination() + { + return this.efsms.keySet().stream().allMatch(x -> canSafelyTerminate(x)); + }*/ + + // Should work both with and without accept-correlation? + public boolean canSafelyTerminate(Role r) + { + EFsm fsm = this.efsms.get(r); + boolean safe = this.queues.isEmpty(r) && (fsm.curr.isTerminal() || + (fsm.curr.getStateKind().equals(EStateKind.ACCEPT) && fsm.isInitial())); // Specifically the initial state + + // CHECKME: incorrectly allows stuck accepts? if inactive not initial, should be clone of initial? + //|| (s.getStateKind().equals(Kind.ACCEPT) && this.states.keySet().stream().noneMatch((rr) -> !r.equals(rr) && this.queues.isConnected(r, rr))) + return safe; + } + + // Stuck due to non-consumable messages (reception errors) + public Map getStuckMessages() + { + Map res = new HashMap<>(); + for (Role self : this.efsms.keySet()) + { + EFsm s = this.efsms.get(self); + EStateKind k = s.curr.getStateKind(); + if (k == EStateKind.UNARY_RECEIVE || k == EStateKind.POLY_RECIEVE) + { + Role peer = s.curr.getActions().get(0).peer; // Pre: consistent ext choice subj + ESend send = this.queues.getQueue(self).get(peer); + if (send != null) + { + ERecv recv = send.toDual(peer); + if (!s.curr.hasAction(recv)) + { + res.put(self, recv); + } + } + } + /*else if (k == Kind.ACCEPT) // CHECKME: ..and request (Client/ServerWrap? -- factor out "blocking"? async. blocking vs. sync? n.b. outputs blocking on queue space) + { + // CHECKME: issue is, unlike regular input states, blocked connect/accept may become unblocked later, so queued messages may not actually be stuck + // (if message is queued on the actual blocked connection, it should be orphan message) + // so, message is stuck only if connect/accept is genuinely deadlocked, which will be detected as that + }*/ + } + return res; + } + + // Doesn't include locally terminated (single term state does not induce a deadlock cycle) + public Set> getWaitForCycles() + { + Set> res = new HashSet<>(); + List todo = new LinkedList<>(this.efsms.keySet()); + while (!todo.isEmpty()) // CHECKME: maybe better to do directly on states, rather than via roles -- ? + { + Role r = todo.remove(0); + if (this.efsms.get(r).curr.isTerminal()) + { + continue; + } + Set cycle = isWaitForCycle(r); + if (cycle != null) + { + res.add(cycle); + todo.removeAll(cycle); + } + } + return res; + } + + // Return: null if no cycle -- terminated peer means no cycle (cf. getUnfinishedRoles) + // Includes connect dependencies + // N.B. if this.states.get(init).isTerminal() then orig is returned as "singleton deadlock" -- CHECKME + protected Set isWaitForCycle(Role init) + { + Set cycle = new LinkedHashSet<>(); + Set todo = new LinkedHashSet<>(Arrays.asList(init)); + while (!todo.isEmpty()) + { + Role r = todo.iterator().next(); + todo.remove(r); + cycle.add(r); + Set waitingFor = getWaitingFor(r); + if (waitingFor == null) // "r" is not necessarily waiting for anyone, so report no cycle + { + return null; + } + waitingFor.stream().filter(x -> !cycle.contains(x)) // Only more than one when client-sync cases + .forEachOrdered(x -> todo.add(x)); // todo is a Set, so re-add existing doesn't matter + } + return cycle; + } + + // Return: set of roles that "r" *must* wait for one of them in order to proceed;.. + // ..or null if "r" is not *necessarily* blocked waiting for *another role* + // Wait-for blocking includes sync-client (request, clientWrap) roles + protected Set getWaitingFor(Role r) + { + EFsm fsm = this.efsms.get(r); + EStateKind k = fsm.curr.getStateKind(); + if (k == EStateKind.TERMINAL) + { + return null; + } + + if (k == EStateKind.UNARY_RECEIVE || k == EStateKind.POLY_RECIEVE) + { + ERecv a = (ERecv) fsm.curr.getActions().get(0); // Pre: consistent ext choice subject -- CHECKME: generalise? + if (this.queues.getQueue(r).get(a.peer) != null) // Here, only looking for any message (not a.toDual, nor dual of any action, cf. stuck error) + { + return null; + } + return Stream.of(a.peer).collect(Collectors.toSet()); + } + else if (k == EStateKind.ACCEPT) + { + if (fsm.isInitial()) // TODO CHECKME: if analysing ACCEPTs, check if "s" is initial (not "deadlock blocked" if initial) -- no: instead, analysing requests + { + return null; + } + List as = fsm.curr.getActions(); // All accept + Role peer = as.get(0).peer; // Pre: consistent ext choice subject -- CHECKME: generalise? + if (this.efsms.get(peer).curr.getActions().stream() + .anyMatch(x -> as.contains(x.toDual(peer)))) + { + return null; + } + return Stream.of(peer).collect(Collectors.toSet()); + } + else if (k == EStateKind.OUTPUT) //|| k == Kind.ACCEPT .. // CHECKME: check requests if no available sends -- ? + { + if (!fsm.curr.isSyncClientOnly()) // Request, ClientWrap + { + return null; + } + List as = fsm.curr.getActions(); + Set res = new HashSet(); + for (EAction a : as) + { + if (this.efsms.get(a.peer).curr.getActions().contains(a.toDual(r))) + { + return null; + } + res.add(a.peer); + } + return res; // Non-empty, because as.size() > 0 and didn't already return + } + // TODO FIXME: ServerWrap + throw new RuntimeException("[TODO] " + k); + } + + // Includes "unconnected" messages -- CHECKME: should unconnected messages be considered as "stuck" instead? + public Map> getOrphanMessages() + { + Map> res = new HashMap<>(); + for (Role r : this.efsms.keySet()) + { + Set orphs = new HashSet<>(); + EFsm fsm = this.efsms.get(r); + if (fsm.curr.isTerminal()) // Local termination of r, i.e. not necessarily "full deadlock cycle" + { + orphs.addAll(this.queues.getQueue(r).values().stream() + .filter(v -> v != null).collect(Collectors.toSet())); + } + else + { + this.efsms.keySet().stream() + .filter(x -> !r.equals(x) && !this.queues.isConnected(r, x)) // !isConnected(r, x), means r considers its side closed + .map(x -> this.queues.getQueue(r).get(x)).filter(x -> x != null) // r's side is closed, but remaining message(s) in r's buff + .forEachOrdered(x -> orphs.add(x)); + } + if (!orphs.isEmpty()) + { + res.put(r, orphs); + } + } + return res; + } + + // Not just "unfinished", but also "non-initiated" (accept guarded) -- though could be non-initiated after some previous completions + // Maybe not needed? previously not used (even without accept-correlation check) + public Map getUnfinishedRoles() + { + if (!getFireable().isEmpty()) + // Once no fireable, then finished (no further fireable will be produced) + // N.B. must check getFireable -- cf. terminal state kind is only when no actions, does not include when actions are stuck + { + return Collections.emptyMap(); + } + return this.efsms.entrySet().stream() + .filter(x -> !canSafelyTerminate(x.getKey())) + .collect(Collectors.toMap(Entry::getKey, x -> x.getValue().curr)); + } + + @Override + public String toString() + { + return "(" + this.efsms + ", " + this.queues + ")"; + } + + @Override + public int hashCode() + { + int hash = 71; + hash = 31 * hash + this.efsms.hashCode(); + hash = 31 * hash + this.queues.hashCode(); + return hash; + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof SConfig)) + { + return false; + } + SConfig c = (SConfig) o; + return this.efsms.equals(c.efsms) && this.queues.equals(c.queues); + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/model/global/SGraph.java b/scribble-core/src/main/java/org/scribble/core/model/global/SGraph.java new file mode 100644 index 000000000..837965cd3 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/model/global/SGraph.java @@ -0,0 +1,407 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.model.global; + +import java.util.Collections; +import java.util.Deque; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.scribble.core.model.MPrettyPrint; +import org.scribble.core.model.global.actions.SAction; +import org.scribble.core.type.name.GProtoName; +import org.scribble.util.Pair; + +public class SGraph implements MPrettyPrint +{ + public final GProtoName proto; // For debugging only? deprecate? + + public final SState init; + public final Map states; // s.id -> s + + private final Set> termSets; + + // Unlike EState, SGraph is not just a "simple wrapper" for an existing graph of nodes -- it is a computed structure, so no lightweight "toGraph" wrapper method; cf., EState + protected SGraph(GProtoName proto, Map states, SState init) + { + this.proto = proto; + this.init = init; + this.states = Collections.unmodifiableMap(states); // s.id -> s + //this.reach = getReachabilityMap(); + + // TODO: refactor + tarjan(); + Set> termSets = new HashSet<>(); + for (Set scc : this.sscs) + { + if (scc.size() == 1 && scc.iterator().next().isTerminal() + || scc.stream().anyMatch( + y -> y.getSuccs().stream().anyMatch(x -> !scc.contains(x)))) + { + continue; + } + //termSets.add(scc.stream().map(x -> x.id).collect(Collectors.toSet())); + termSets.add(Collections.unmodifiableSet(scc)); + } + this.termSets = Collections.unmodifiableSet(termSets); + } + + public Set> getTermSets() + { + return this.termSets; // Already unmodifiable + } + + // Returns null if end cannot be reached + public List getTraceFromInit(SState end) + { + Map> traces = bfsFromInit(end); + LinkedList trace = new LinkedList<>(); + for (int id = end.id; id != init.id; ) // Skipped if init.id == end.id (e.g., error in init state, such as a bad connect) + { + Pair p = traces.get(id); + trace.push(p.left); + id = p.right; + } + return trace; + } + + // Returns null if end cannot be reached + private Map> bfsFromInit(SState end) // (cf., Dijkstra's with all weights 1) + { + // SState.id faster as keys than full SConfig + Set seen = new HashSet<>(); + List todo = new LinkedList<>(); + seen.add(this.init.id); + todo.add(this.init.id); + Map> traces = new HashMap<>(); + while (!todo.isEmpty()) + { + Iterator i = todo.iterator(); + Integer currid = i.next(); + i.remove(); + if (currid == end.id) + { + return traces; + } + SState curr = this.states.get(currid); + Iterator as = curr.getActions().iterator(); // CHECKME: how about non-det actions? (cf. below, todo.contains(succ.id)? e.g., bad.liveness.messagelive.Test01) + for (SState succ : curr.getSuccs()) + { + SAction a = as.next(); + if (seen.contains(succ.id) || todo.contains(succ.id)) + { + continue; + } + seen.add(succ.id); + traces.put(succ.id, new Pair<>(a, currid)); + todo.add(succ.id); + } + } + return null; + } + + @Override + public String toDot() + { + return this.init.toDot(); + } + + @Override + public String toAut() + { + return this.init.toAut(); + } + + @Override + public String toString() + { + return this.init.toString(); + } + + // Following are "one-time" usage, on instance construction + // SState.id faster as keys than full SConfig + private int counter = 0; + private Map indices = new HashMap<>(); // s.id -> index + private Map lowlinks = new HashMap<>(); // s.id -> lowlink + private Deque stack = new LinkedList<>(); + private Set onStack = new HashSet<>(); + private Set> sscs = new HashSet<>(); + + private void tarjan() + { + for (SState v : this.states.values()) + { + if (!indices.containsKey(v.id)) + { + strongConnect(v); + } + } + } + + private void strongConnect(SState v) + { + // Set the depth index for v to the smallest unused index + int index = this.counter++; + this.indices.put(v.id, index); + this.lowlinks.put(v.id, index); + this.stack.push(v); + this.onStack.add(v.id); + + // Consider successors of v + for (SState w : v.getSuccs()) + { + if (!this.indices.containsKey(w.id)) + { + // Successor w has not yet been visited; recurse on it + strongConnect(w); + int vlowlink = this.lowlinks.get(v.id); + int wlowlink = this.lowlinks.get(w.id); + this.lowlinks.put(v.id, (vlowlink <= wlowlink ? vlowlink : wlowlink)); + } + else if (this.onStack.contains(w.id)) + { + // Successor w is in stack S and hence in the current SCC + // If w is not on stack, then (v, w) is a cross-edge in the DFS tree and must be ignored + // Note: The next line may look odd - but is correct. + // It says w.index not w.lowlink; that is deliberate and from the original paper + int vlowlink = this.lowlinks.get(v.id); + int windex = this.indices.get(w.id); + this.lowlinks.put(v.id, (vlowlink <= windex ? vlowlink : windex)); + } + } + + // If v is a root node, pop the stack and generate an SCC + if (this.lowlinks.get(v.id) == this.indices.get(v.id)) + { + Set ssc = new HashSet<>(); + SState w; + do + { + w = this.stack.pop(); + this.onStack.remove(w.id); + ssc.add(w); + } + while (w.id != v.id); + this.sscs.add(ssc); + } + } + + + + + + + + + + + + + + /* + private Map> reach; // State ID -> reachable states (not reflexive) + + public Set> getTerminalSets() + { + if (this.termSets != null) + { + return this.termSets; + } + + Set> termSets = new HashSet<>(); + Set> checked = new HashSet<>(); + for (Integer i : reach.keySet()) + { + SState s = this.states.get(i); + Set rs = this.reach.get(s.id); + if (!checked.contains(rs) && rs.contains(s.id)) + { + checked.add(rs); + if (isTerminalSetMember(s)) + { + termSets.add(rs); + } + } + } + this.termSets = Collections.unmodifiableSet(termSets); + return this.termSets; + } + + private boolean isTerminalSetMember(SState s) + { + Set rs = this.reach.get(s.id); // Pre: rs.contains(s.id) + Set tmp = new HashSet<>(rs); + tmp.remove(s.id); // Unnecessary to remove, but this.reach.get(r).equals(rs) check below trivially holds by def + for (Integer r : tmp) + { + if (!this.reach.containsKey(r) || !this.reach.get(r).equals(rs)) + { + return false; + } + } + return true; + } + + // Not reflexive + public Map> getReachabilityMap() + { + if (this.reach != null) + { + return this.reach; + } + + Map idToIndex = new HashMap<>(); // state ID -> array index + Map indexToId = new HashMap<>(); // array index -> state ID + int i = 0; + for (SState s : this.states.values()) + { + idToIndex.put(s.id, i); + indexToId.put(i, s.id); + i++; + } + this.reach = getReachabilityAux(idToIndex, indexToId); + + return this.reach; + } + + private Map> getReachabilityAux( + Map idToIndex, Map indexToId) + { + int size = idToIndex.keySet().size(); + boolean[][] reach = new boolean[size][size]; + + for (Integer s1id : idToIndex.keySet()) + { + for (SState s2 : this.states.get(s1id).getSuccs()) + { + reach[idToIndex.get(s1id)][idToIndex.get(s2.id)] = true; + } + } + + for (boolean again = true; again; ) + { + again = false; + for (int i = 0; i < size; i++) + { + for (int j = 0; j < size; j++) + { + if (reach[i][j]) + { + for (int k = 0; k < size; k++) + { + if (reach[j][k] && !reach[i][k]) + { + reach[i][k] = true; + again = true; + } + } + } + } + } + } + + Map> res = new HashMap<>(); + for (int i = 0; i < size; i++) + { + Set tmp = res.get(indexToId.get(i)); + for (int j = 0; j < size; j++) + { + if (reach[i][j]) + { + if (tmp == null) + { + tmp = new HashSet<>(); + res.put(indexToId.get(i), tmp); + } + tmp.add(indexToId.get(j)); + } + } + } + + return Collections.unmodifiableMap(res); + } + + public List getTrace(SState start, SState end) + { + SortedMap> candidates = new TreeMap<>(); + Set dis0 = new LinkedHashSet(); + dis0.add(start.id); + candidates.put(0, dis0); + + Set seen = new HashSet<>(); + seen.add(start.id); + + return getTraceAux(new LinkedList<>(), seen, candidates, end); + } + + // Djikstra's + private List getTraceAux(List trace, Set seen, + SortedMap> candidates, SState end) + { + Integer dis = candidates.keySet().iterator().next(); + Set cs = candidates.get(dis); + Iterator it = cs.iterator(); + Integer currid = it.next(); + it.remove(); + if (cs.isEmpty()) + { + candidates.remove(dis); + } + + SState curr = this.states.get(currid); + Iterator as = curr.getActions().iterator(); + Iterator succs = curr.getSuccs().iterator(); + while (as.hasNext()) + { + SAction a = as.next(); + SState succ = succs.next(); + if (succ.id == end.id) + { + trace.add(a); + return trace; + } + + if (!seen.contains(succ.id)) + //&& this.reach.containsKey(s.id) && this.reach.get(s.id).contains(end.id)) + { + seen.add(succ.id); + if (succ.isTerminal()) // Unnecesary, visiting succ will do "while (as.hasNext())" + { + continue; + } + Set tmp1 = candidates.get(dis+1); + if (tmp1 == null) + { + tmp1 = new HashSet<>(); + candidates.put(dis+1, tmp1); + } + tmp1.add(succ.id); + List tmp2 = new LinkedList<>(trace); + tmp2.add(a); + List res = getTraceAux(tmp2, seen, candidates, end); // FIXME: replace by a loop + if (res != null) + { + return res; + } + } + } + return null; + } + //*/ +} \ No newline at end of file diff --git a/scribble-core/src/main/java/org/scribble/core/model/global/SGraphBuilder.java b/scribble-core/src/main/java/org/scribble/core/model/global/SGraphBuilder.java new file mode 100644 index 000000000..25f33a7e6 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/model/global/SGraphBuilder.java @@ -0,0 +1,126 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.model.global; + +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedHashSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; +import java.util.stream.Collectors; + +import org.scribble.core.job.Core; +import org.scribble.core.model.endpoint.EFsm; +import org.scribble.core.model.endpoint.EGraph; +import org.scribble.core.model.endpoint.actions.EAction; +import org.scribble.core.model.global.actions.SAction; +import org.scribble.core.type.name.GProtoName; +import org.scribble.core.type.name.Role; +import org.scribble.util.ScribException; + +public class SGraphBuilder +{ + public final Core core; + + private final SGraphBuilderUtil util; + + public SGraphBuilder(Core core) + { + this.core = core; + this.util = this.core.config.mf.global.SGraphBuilderUtil(); + } + + // Do as an initial state rather than config? + protected SConfig createInitConfig(Map egraphs, + boolean explicit) + { + Map efsms = egraphs.entrySet().stream() + .collect(Collectors.toMap(Entry::getKey, e -> e.getValue().toFsm())); + SingleBuffers b0 = new SingleBuffers(efsms.keySet(), !explicit); + return this.core.config.mf.global.SConfig(efsms, b0); + } + + // Factory method: not fully integrated with SGraph constructor because of Job arg (debug printing) + // Also checks for non-deterministic payloads + // Maybe refactor into an SGraph builder util; cf., EGraphBuilderUtil -- but not Visitor-based building (cf. EndpointGraphBuilder), this isn't an AST algorithm + public SGraph build(Map egraphs, boolean explicit, + GProtoName fullname) throws ScribException + { + this.util.reset(); + + SConfig c0 = createInitConfig(egraphs, explicit); + SState init = this.util.newState(c0); + Set todo = new LinkedHashSet<>(); // Consider Map, faster than full SConfig hash ? + todo.add(init); + for (//int debugCount = 1 + ; !todo.isEmpty(); ) // Compute configs and use util to construct graph, until no more new configs + { + Iterator i = todo.iterator(); + SState curr = i.next(); + i.remove(); + /*if (this.core.config.args.get(CoreArgs.VERBOSE)) + { + if (debugCount++ % 50 == 0) + { + this.core.verbosePrintln( + "(" + fullname + ") Building global states: " + debugCount); + } + }*/ + + // Based on config semantics, not "static" graph edges (cf., super.getActions) -- used to build global model graph + Map> fireable = curr.config.getFireable(); + for (Role r : fireable.keySet()) + { + for (EAction a : fireable.get(r)) + { + // Asynchronous (input/output) actions + if (a.isSend() || a.isReceive() || a.isDisconnect()) + { + Set next = new HashSet<>(curr.config.async(r, a)); + // SConfig.a/sync currently produces a List, but here collapse identical configs for global model (represent non-det "by edges", not "by model states") + Set succs = this.util.getSuccs(curr, a.toGlobal(r), next); // util.getSuccs constructs the edges + todo.addAll(succs); + } + // Synchronous (client/server) actions + else if (a.isAccept() || a.isRequest() || a.isClientWrap() + || a.isServerWrap()) + { + Set as = fireable.get(a.peer); + EAction abar = a.toDual(r); + if (as != null && as.contains(abar)) + { + as.remove(abar); // Removes one occurrence + SAction aglobal = (a.isRequest() || a.isClientWrap()) // "client" side action + ? a.toGlobal(r) + : abar.toGlobal(a.peer); + // CHECKME: edge will be drawn as the connect, but should be read as the sync. of both -- something like "r1, r2: sync" may be more consistent (or take a set of actions as the edge label?) + Set next = new HashSet<>(curr.config.sync(r, a, a.peer, abar)); + // SConfig.a/sync currently produces a List, but here collapse identical configs for global model (represent non-det "by edges", not "by model states") + Set succs = this.util.getSuccs(curr, aglobal, next); // util.getSuccs constructs the edges + todo.addAll(succs); + } + } + else + { + throw new RuntimeException("Unknown action kind: " + a); + } + } + } + } + + return this.core.config.mf.global.SGraph(fullname, this.util.getStates(), + init); + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/model/global/SGraphBuilderUtil.java b/scribble-core/src/main/java/org/scribble/core/model/global/SGraphBuilderUtil.java new file mode 100644 index 000000000..7a20160df --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/model/global/SGraphBuilderUtil.java @@ -0,0 +1,78 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.model.global; + +import java.util.HashMap; +import java.util.LinkedHashSet; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +import org.scribble.core.model.GraphBuilderUtil; +import org.scribble.core.model.ModelFactory; +import org.scribble.core.model.global.actions.SAction; +import org.scribble.core.type.kind.Global; + +public class SGraphBuilderUtil + extends GraphBuilderUtil +{ + private Map states = new HashMap<>(); + + protected SGraphBuilderUtil(ModelFactory mf) + { + super(mf); + reset(); + } + + @Override + protected void reset() + { + this.states.clear(); + } + + public SState newState(SConfig c) + { + SState s = this.mf.global.SState(c); + this.states.put(c, s); + return s; + } + + // Pre: this.states.containsKey(curr.config) + public Set getSuccs(SState curr, SAction a, //List succs) + Set succs) + // SConfig.a/sync currently produces a List, but here collapse identical configs for global model (represent non-det "by edges", not "by model states") + { + Set res = new LinkedHashSet<>(); // Takes care of duplicates (o/w should also do "|| res.containsKey(c)" below) + for (SConfig c : succs) + { + boolean seen = this.states.containsKey(c); + SState next = seen + ? this.states.get(c) + : newState(c); + curr.addEdge(a, next); + if (!seen) // Must use cached test, newState changes adds the key + { + res.add(next); + } + } + return res; + } + + // s.id -> s + public Map getStates() + { + return this.states.values().stream() + .collect(Collectors.toMap(x -> x.id, x -> x)); + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/model/global/SModel.java b/scribble-core/src/main/java/org/scribble/core/model/global/SModel.java new file mode 100644 index 000000000..0cee2dd2c --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/model/global/SModel.java @@ -0,0 +1,198 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.model.global; + +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; +import java.util.SortedMap; +import java.util.TreeMap; +import java.util.stream.Collectors; + +import org.scribble.core.job.Core; +import org.scribble.core.job.CoreArgs; +import org.scribble.core.model.endpoint.actions.ESend; +import org.scribble.core.type.name.Role; +import org.scribble.util.Pair; +import org.scribble.util.ScribException; + + +// For doing validation operations on an SGraph (cf. EFsm, use Graph as an FSM) +public class SModel +{ + private Core core; // CHECKME: refactor? but avoiding in constructor to keep mf more independent/uniform + + public final SGraph graph; + + protected SModel(SGraph graph) + { + this.graph = graph; + } + + // CHECKME: let Core call check safety/progress directly? (to avoid passing core) + public void validate(Core core) throws ScribException + { + this.core = core; + + SortedMap sErrs = getSafetyErrors(); + Map, Pair, Map>>> pErrors + = Collections.emptyMap(); + if (!core.config.args.get(CoreArgs.NO_PROGRESS)) + { + pErrors = getProgressErrors(); + } + + if (!sErrs.isEmpty() || !pErrors.isEmpty()) + { + String msg = ""; + if (!sErrs.isEmpty()) + { + msg += getSafetyErrors().values().stream() + .map(x -> x.toErrorMessage(this.graph)) + .collect(Collectors.joining("")); + } + if (!pErrors.isEmpty()) + { + for (Entry, Pair, Map>>> e : + pErrors.entrySet()) + { + msg += getProgressErrorMessages(e.getKey(), e.getValue()); + } + } + throw new ScribException(msg); + } + } + + protected SortedMap getSafetyErrors() // s.id key lighter than full SConfig + { + SortedMap res = new TreeMap<>(); + for (int id : this.graph.states.keySet()) + { + SStateErrors errs = this.graph.states.get(id).getErrors(); + if (!errs.isEmpty()) + { + res.put(id, errs); + } + } + return res; + } + + // These are checked only on termsets (cf. safety checked on all), and "overlap" with safety errors within there + // Could "skip" safety checks for termsets (probably better than coercing "progress" outside of termsets, as it would probably just amount to safety anyway) + // CHECKME: factor out a TermSet class? + protected Map, Pair, Map>>> + getProgressErrors() + { + Map, Pair, Map>>> res + = new HashMap<>(); + for (Set termset: this.graph.getTermSets()) + { + Set starved = checkRoleProgress(termset); + Map> ignored = checkEventualReception(termset); + if (!starved.isEmpty() || !ignored.isEmpty()) + { + res.put(termset, new Pair<>(starved, ignored)); + } + } + return res; + } + + // Could subsume terminal state check, if terminal sets included size 1 with reflexive reachability (but not a good approach) + protected Set checkRoleProgress(Set termset) + { + SState s = termset.iterator().next(); // Pick any state to check canSafelyTerminate (later, if needed), if non progressing equivalent for all + Set todo = new HashSet<>(s.config.efsms.keySet()); + for (Iterator i = termset.iterator(); + i.hasNext() && !todo.isEmpty(); ) + { + i.next().getActions().stream().map(x -> x.subj).distinct() + .forEachOrdered(x -> todo.remove(x)); + // cf. a.containsRole(r) -- implies obj will be subj for the counterpart action somewhere in the termset? + } + + // todo is now all roles that are not the subj of any action in the termset + return todo.stream() + .filter(x -> !s.config.canSafelyTerminate(x) + && s.config.queues.getQueue(x).values().stream() + .allMatch(y -> y == null)) // Check empty queues for starved -- o/w, is a stuck-message + .collect(Collectors.toSet()); + } + + // cf. eventual stability (could also check within termsets) + protected Map> checkEventualReception(Set termset) + { + SState s0 = termset.iterator().next(); + Set roles = s0.config.efsms.keySet(); + Map> q0 = s0.config.queues.getQueues(); // dest -> src -> msg -- dest.equals(msg.peer), msg is ESend to the dst + for (Role r1 : roles) + { + Map q0_r1 = q0.get(r1); + for (Role r2 : roles) + { + if (!r1.equals(r2) && q0_r1.get(r2) != null && + termset.stream() + .anyMatch(x -> x.config.queues.getQueue(r1).get(r2) == null)) + { + q0_r1.put(r2, null); + } + } + } + + // q0 now shows which buffers are never null at any state in the termset + Map> ignored = new HashMap<>(); + for (Role r : roles) + { + Set msgs = q0.values().stream() + .flatMap(x -> x.entrySet().stream()) // For all input buffs at every role... + .filter(x -> x.getKey().equals(r) && x.getValue() != null) // ...s.t. the buff is from "r" and is non-empty + .map(x -> x.getValue()).collect(Collectors.toSet()); + if (!msgs.isEmpty()) + { + ignored.put(r, msgs); + } + } + return ignored; + } + + // Cf. SStateErrors // TODO: refactor to Core, if not to its own class? + protected String getProgressErrorMessages(Set termset, + Pair, Map>> perrors) + { + String msg = ""; + if (!perrors.left.isEmpty()) // starved + { + msg += "\nRole progress violation for " + perrors.left + + " in session state terminal set:\n " + termSetToString(termset); + } + if (!perrors.right.isEmpty()) // ignored + { + msg += "\nEventual reception violation for " + perrors.right + + " in session state terminal set:\n " + termSetToString(termset); + } + return msg; + } + + protected String termSetToString(Set termset) + { + return this.core.config.args.get(CoreArgs.VERBOSE) + ? termset.stream().map(x -> x.toString()) + .collect(Collectors.joining(",")) + : termset.stream().map(x -> Integer.toString(x.id)) + .collect(Collectors.joining(",")); + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/model/global/SModelFactory.java b/scribble-core/src/main/java/org/scribble/core/model/global/SModelFactory.java new file mode 100644 index 000000000..2f81abc90 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/model/global/SModelFactory.java @@ -0,0 +1,50 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.model.global; + +import java.util.Map; + +import org.scribble.core.model.endpoint.EFsm; +import org.scribble.core.model.global.actions.SAcc; +import org.scribble.core.model.global.actions.SClientWrap; +import org.scribble.core.model.global.actions.SDisconnect; +import org.scribble.core.model.global.actions.SRecv; +import org.scribble.core.model.global.actions.SReq; +import org.scribble.core.model.global.actions.SSend; +import org.scribble.core.model.global.actions.SServerWrap; +import org.scribble.core.type.name.GProtoName; +import org.scribble.core.type.name.MsgId; +import org.scribble.core.type.name.Role; +import org.scribble.core.type.session.Payload; + +public interface SModelFactory +{ + SGraphBuilderUtil SGraphBuilderUtil(); + + // protected constructors (MState mutable) + SState SState(SConfig config); + SConfig SConfig(Map state, SingleBuffers buffs); + SGraph SGraph(GProtoName proto, Map states, + SState init); // states: s.id -> s + SModel SModel(SGraph g); + + // public constructors (subpackage, immutable) + SSend SSend(Role subj, Role obj, MsgId mid, Payload pay); + SRecv SRecv(Role subj, Role obj, MsgId mid, Payload pay); + SReq SReq(Role subj, Role obj, MsgId mid, Payload pay); + SAcc SAcc(Role subj, Role obj, MsgId mid, Payload pay); + SDisconnect SDisconnect(Role subj, Role obj); + SClientWrap SClientWrap(Role subj, Role obj); + SServerWrap SServerWrap(Role subj, Role obj); +} diff --git a/scribble-core/src/main/java/org/scribble/core/model/global/SModelFactoryImpl.java b/scribble-core/src/main/java/org/scribble/core/model/global/SModelFactoryImpl.java new file mode 100644 index 000000000..135da4586 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/model/global/SModelFactoryImpl.java @@ -0,0 +1,115 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.model.global; + +import java.util.Map; + +import org.scribble.core.model.ModelFactory; +import org.scribble.core.model.ModelFactoryBase; +import org.scribble.core.model.endpoint.EFsm; +import org.scribble.core.model.global.actions.SAcc; +import org.scribble.core.model.global.actions.SClientWrap; +import org.scribble.core.model.global.actions.SDisconnect; +import org.scribble.core.model.global.actions.SRecv; +import org.scribble.core.model.global.actions.SReq; +import org.scribble.core.model.global.actions.SSend; +import org.scribble.core.model.global.actions.SServerWrap; +import org.scribble.core.type.name.GProtoName; +import org.scribble.core.type.name.MsgId; +import org.scribble.core.type.name.Role; +import org.scribble.core.type.session.Payload; + +// Separate E/SModelFactories fits protected E/SState constructor pattern +public class SModelFactoryImpl extends ModelFactoryBase implements SModelFactory +{ + + public SModelFactoryImpl(ModelFactory mf) + { + super(mf); + } + + @Override + public SGraphBuilderUtil SGraphBuilderUtil() + { + return new SGraphBuilderUtil(this.mf); + } + + @Override + public SState SState(SConfig config) + { + return new SState(config); + } + + // states: s.id -> s + @Override + public SGraph SGraph(GProtoName proto, Map states, + SState init) + { + return new SGraph(proto, states, init); + } + + @Override + public SConfig SConfig(Map state, SingleBuffers buffs) + { + return new SConfig(this.mf, state, buffs); + } + + @Override + public SModel SModel(SGraph g) + { + return new SModel(g); + } + + @Override + public SSend SSend(Role subj, Role obj, MsgId mid, Payload pay) + { + return new SSend(subj, obj, mid, pay); + } + + @Override + public SRecv SRecv(Role subj, Role obj, MsgId mid, Payload pay) + { + return new SRecv(subj, obj, mid, pay); + } + + @Override + public SReq SReq(Role subj, Role obj, MsgId mid, Payload pay) + { + return new SReq(subj, obj, mid, pay); + } + + @Override + public SAcc SAcc(Role subj, Role obj, MsgId mid, Payload pay) + { + return new SAcc(subj, obj, mid, pay); + } + + @Override + public SDisconnect SDisconnect(Role subj, Role obj) + { + return new SDisconnect(subj, obj); + } + + @Override + public SClientWrap SClientWrap(Role subj, Role obj) + { + return new SClientWrap(subj, obj); + } + + @Override + public SServerWrap SServerWrap(Role subj, Role obj) + { + return new SServerWrap(subj, obj); + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/model/global/SState.java b/scribble-core/src/main/java/org/scribble/core/model/global/SState.java new file mode 100644 index 000000000..45acc2211 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/model/global/SState.java @@ -0,0 +1,128 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.model.global; + +import java.util.Collections; +import java.util.Set; + +import org.scribble.core.model.MPrettyState; +import org.scribble.core.model.MState; +import org.scribble.core.model.global.actions.SAction; +import org.scribble.core.type.kind.Global; + +// CHECKME: make a WFModel front-end class? (cf. EGraph) +// N.B. only uses MState.id cosmetically, cf. MState equals/hashCode -- overrides equals/hashCode based on this.config (maybe extending MState is a bit misleading) +public class SState extends MPrettyState +{ + public final SConfig config; + + protected SState(SConfig config) // CHECKME? now publically mutable (for mf imple), same for EState + { + super(Collections.emptySet()); + this.config = config; + } + + // For access from SGraphBuilderUtil + @Override + protected void addEdge(SAction a, SState s) + { + super.addEdge(a, s); + } + + public SStateErrors getErrors() // Means safety (i.e., individual state) errors + { + return new SStateErrors(this); + } + + @Override + protected String getNodeLabel() + { + String labs = this.config.toString(); + return "label=\"" + this.id + ":" + labs.substring(1, labs.length() - 1) + + "\""; + } + + @Override + public Set getReachableStates() + { + return getReachableStatesAux(this); + } + + @Override + public String toString() + { + return this.id + ":" + this.config.toString(); + } + + // N.B. does not use super.hashCode, need "semantic" equality of configs for model construction + @Override + public int hashCode() + { + int hash = 79; + hash = 31 * hash + this.config.hashCode(); + return hash; + } + + // FIXME? doesn't use this.id, cf. super.equals + // Not using id, cf. ModelState -- FIXME? use a factory pattern that associates unique states and ids? -- use id for hash, and make a separate "semantic equals" + // Care is needed if hashing, since mutable (OK to use immutable config -- cf., ModelState.id) + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof SState)) + { + return false; + } + SState them = (SState) o; + return them.canEquals(this) && this.config.equals(them.config); // N.B. does not do super.equals (cf. hashCode) + } + + @Override + protected boolean canEquals(MState s) + { + return s instanceof SState; + } +} + + + + + + + + + + + + + /*// Based on config semantics, not "static" graph edges (cf., super.getAllActions) -- used to build global model graph + public Map> getFireable() + { + return this.config.getFireable(); + } + + public List fire(Role r, EAction a) + { + return this.config.fire(r, a); + } + + // "Synchronous version" of fire + public List sync(Role r1, EAction a1, Role r2, EAction a2) + { + return this.config.sync(r1, a1, r2, a2); + }*/ \ No newline at end of file diff --git a/scribble-core/src/main/java/org/scribble/core/model/global/SStateErrors.java b/scribble-core/src/main/java/org/scribble/core/model/global/SStateErrors.java new file mode 100644 index 000000000..be0c98456 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/model/global/SStateErrors.java @@ -0,0 +1,95 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.model.global; + +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.scribble.core.model.endpoint.EState; +import org.scribble.core.model.endpoint.actions.ERecv; +import org.scribble.core.model.endpoint.actions.ESend; +import org.scribble.core.model.global.actions.SAction; +import org.scribble.core.type.name.Role; + +public class SStateErrors +{ + public final SState state; + + // FIXME: factor out explicit error classes -- for error message formatting + // FIXME: could also check for roles stuck on unconnected sends here (probably better, than current syntax check) + public final Map stuck; // Reception errors + public final Set> waitFor; // Deadlock cycles + public final Map> orphans; // Orphan messages + public final Map unfinished; // Unfinished roles + + public SStateErrors(SState state) + { + this.state = state; + this.stuck = state.config.getStuckMessages(); + this.waitFor = state.config.getWaitForCycles(); + this.orphans = state.config.getOrphanMessages(); + this.unfinished = state.config.getUnfinishedRoles(); + } + + public boolean isEmpty() + { + return this.stuck.isEmpty() && this.waitFor.isEmpty() + && this.orphans.isEmpty() && this.unfinished.isEmpty(); + } + + @Override + public String toString() + { + return "stuck=" + this.stuck + ", watiFor=" + this.waitFor + ", orphans=" + + this.orphans + ", unfinished=" + this.unfinished; + } + + public String toErrorMessage(SGraph graph) + { + String msg = ""; // Return empty when no error? + if (!isEmpty()) + { + // CHECKME: getTrace can get stuck when local choice subjects are disabled ? (has since been rewritten) + List trace = graph.getTraceFromInit(this.state); // CHECKME: getTrace broken on non-det self loops? + msg += "\nSafety violation(s) at session state " + this.state.id + + ":\n Trace=" + trace + + appendErrors(); // Does leading "\n" + } + return msg; + } + + // TODO: snip if too long? -- maybe not, let user pipe to file + protected String appendErrors() + { + String res = ""; + if (!this.stuck.isEmpty()) + { + res += "\n Stuck messages: " + this.stuck; // Deadlock from reception error + } + if (!this.waitFor.isEmpty()) + { + res += "\n Wait-for cycles: " + this.waitFor; // Deadlock from input-blocked cycles -- not from terminated dependencies, cf. unfinished roles + } + if (!this.orphans.isEmpty()) + { + res += "\n Orphan messages: " + this.orphans; // TODO: add sender of orphan to error message + } + if (!this.unfinished.isEmpty()) + { + res += "\n Unfinished roles: " + this.unfinished; + } + return res; + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/model/global/SingleBuffers.java b/scribble-core/src/main/java/org/scribble/core/model/global/SingleBuffers.java new file mode 100644 index 000000000..17ff20fa8 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/model/global/SingleBuffers.java @@ -0,0 +1,214 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.model.global; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; +import java.util.stream.Collectors; + +import org.scribble.core.model.endpoint.actions.EAcc; +import org.scribble.core.model.endpoint.actions.EClientWrap; +import org.scribble.core.model.endpoint.actions.EDisconnect; +import org.scribble.core.model.endpoint.actions.ERecv; +import org.scribble.core.model.endpoint.actions.EReq; +import org.scribble.core.model.endpoint.actions.ESend; +import org.scribble.core.model.endpoint.actions.EServerWrap; +import org.scribble.core.type.name.Role; + +// Immutable -- send/receive/etc return updated copies +public class SingleBuffers +{ + private final Map> connected = new HashMap<>(); // local -> peer -> does-local-consider-connected (symmetric) + // CHECKME: refactor as Map> ? cf. ConnectionChecker + + private final Map> buffs = new HashMap<>(); // dest -> src -> msg -- N.B. connected.get(A).get(B) => can send into buffs.get(B).get(A) ("reversed") + // N.B. hardcoded to capacity one -- SQueues would be the generalisation + // null ESend for empty queue + + public SingleBuffers(Set roles, boolean implicit) + { + for(Role r1 : roles) + { + HashMap connected = new HashMap<>(); + HashMap queues = new HashMap<>(); + for (Role r2 : roles) + { + if (!r1.equals(r2)) + { + connected.put(r2, implicit); + queues.put(r2, null); // null for empty queue + } + } + this.connected.put(r1, connected); + this.buffs.put(r1, queues); + } + } + + protected SingleBuffers(SingleBuffers queues) + { + for (Role r : queues.buffs.keySet()) + { + this.connected.put(r, new HashMap<>(queues.connected.get(r))); + this.buffs.put(r, new HashMap<>(queues.buffs.get(r))); + } + } + + public boolean canSend(Role self, ESend a) + { + return isConnected(self, a.peer) //&& isConnected(a.peer, self) // CHECKME: only consider local side? + && this.buffs.get(a.peer).get(self) == null; + } + + public boolean canReceive(Role self, ERecv a) + { + ESend send = this.buffs.get(self).get(a.peer); + return isConnected(self, a.peer) // Other direction doesn't matter, local can still receive after peer disconnected + && send != null && send.toDual(a.peer).equals(a); + } + + // N.B. "sync" action but only considers the self side, i.e., to actually fire, must also explicitly check canAccept + public boolean canRequest(Role self, EReq c) + { + return !isConnected(self, c.peer); + } + + // N.B. "sync" action but only considers the self side, i.e., to actually fire, must also explicitly check canRequest + public boolean canAccept(Role self, EAcc a) + { + return !isConnected(self, a.peer); + } + + public boolean canDisconnect(Role self, EDisconnect d) + { + return isConnected(self, d.peer); + } + + // N.B. "sync" action but only considers the self side, i.e., to actually fire, must also explicitly check canServerWrap + // N.B. doesn't actually change any state + public boolean canClientWrap(Role self, EClientWrap cw) + { + return isConnected(self, cw.peer); + } + + // N.B. "sync" action but only considers the self side, i.e., to actually fire, must also explicitly check canClientWrap + // N.B. doesn't actually change queues state + public boolean canServerWrap(Role self, EServerWrap sw) + { + return isConnected(self, sw.peer); + } + + // Pre: canSend, e.g., via via SConfig.getFireable + // Return an updated copy + public SingleBuffers send(Role self, ESend a) + { + SingleBuffers copy = new SingleBuffers(this); + copy.buffs.get(a.peer).put(self, a); + return copy; + } + + // Pre: canReceive, e.g., via SConfig.getFireable + // Return an updated copy + public SingleBuffers receive(Role self, ERecv a) + { + SingleBuffers copy = new SingleBuffers(this); + copy.buffs.get(self).put(a.peer, null); + return copy; + } + + // Sync action + // Pre: canRequest(r1, [[r2]]) and canAccept(r2, [[r1]]), where [[r]] is a matching action with peer r -- e.g., via via SConfig.getFireable + // Return an updated copy + public SingleBuffers connect(Role r1, Role r2) // Role sides and message don't matter + { + SingleBuffers copy = new SingleBuffers(this); + copy.connected.get(r1).put(r2, true); + copy.connected.get(r2).put(r1, true); + return copy; + } + + // Pre: canDisconnect(self, d), e.g., via SConfig.via getFireable + // Return an updated copy + public SingleBuffers disconnect(Role self, EDisconnect d) + { + SingleBuffers copy = new SingleBuffers(this); + copy.connected.get(self).put(d.peer, false); // Didn't update buffs (cf. SConfig.getOrphanMessages) + return copy; + } + + // N.B. direction sensitive (viz., after some disconnect) + public boolean isConnected(Role self, Role peer) + { + return this.connected.get(self).get(peer); + } + + public boolean isEmpty(Role r) // this.connected doesn't matter + { + return this.buffs.get(r).values().stream().allMatch(v -> v == null); + } + + // Return a (deep) copy -- currently, checkEventualReception expects a modifiable return + // N.B. hardcoded to capacity one + public Map> getQueues() + { + return this.buffs.entrySet().stream().collect(Collectors.toMap( + Entry::getKey, + x -> new HashMap<>(x.getValue()))); // Collections.unmodifiableMap(x.getValue()) + } + + // N.B. hardcoded to capacity one + public Map getQueue(Role r) + { + return Collections.unmodifiableMap(this.buffs.get(r)); + } + + @Override + public final int hashCode() + { + int hash = 131; + hash = 31 * hash + this.connected.hashCode(); + hash = 31 * hash + this.buffs.hashCode(); + return hash; + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof SingleBuffers)) + { + return false; + } + SingleBuffers b = (SingleBuffers) o; + return this.connected.equals(b.connected) && this.buffs.equals(b.buffs); + } + + @Override + public String toString() + { + return this.buffs.entrySet().stream() + .filter(e -> e.getValue().values().stream().anyMatch(v -> v != null)) + .collect(Collectors.toMap( + e -> e.getKey(), + e -> e.getValue().entrySet().stream() + .filter(f -> f.getValue() != null) + .collect(Collectors.toMap(f -> f.getKey(), f -> f.getValue())) + )).toString(); + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/model/global/actions/SAcc.java b/scribble-core/src/main/java/org/scribble/core/model/global/actions/SAcc.java new file mode 100644 index 000000000..e2049680e --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/model/global/actions/SAcc.java @@ -0,0 +1,66 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.model.global.actions; + +import org.scribble.core.type.name.MsgId; +import org.scribble.core.type.name.Role; +import org.scribble.core.type.session.Payload; + +public class SAcc extends SAction +{ + public SAcc(Role subj, Role obj, MsgId mid, Payload pay) + { + super(subj, obj, mid, pay); + } + + @Override + public boolean isAccept() + { + return true; + } + + @Override + public int hashCode() + { + int hash = 967; + hash = 31 * hash + super.hashCode(); + return hash; + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof SAcc)) + { + return false; + } + return super.equals(o); // Does canEquals + } + + public boolean canEquals(Object o) + { + return o instanceof SAcc; + } + + @Override + protected String getCommSymbol() + { + //return "??"; + return "<<-"; + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/model/global/actions/SAction.java b/scribble-core/src/main/java/org/scribble/core/model/global/actions/SAction.java new file mode 100644 index 000000000..209df9618 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/model/global/actions/SAction.java @@ -0,0 +1,162 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.model.global.actions; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; + +import org.scribble.core.model.MAction; +import org.scribble.core.type.kind.Global; +import org.scribble.core.type.name.MsgId; +import org.scribble.core.type.name.Role; +import org.scribble.core.type.session.Payload; + +// N.B. these are not exactly global type constructors -- they are "endpoint-oriented" like locals, but record both subj/obj roles (so more like locals with self) +public abstract class SAction extends MAction +{ + public final Role subj; + + public SAction(Role subj, Role obj, MsgId mid, Payload pay) + { + super(obj, mid, pay); + this.subj = subj; + } + + public boolean isSend() + { + return false; + } + + public boolean isReceive() + { + return false; + } + + public boolean isRequest() + { + return false; + } + + public boolean isAccept() + { + return false; + } + + public boolean isDisconnect() + { + return false; + } + + public boolean isClientWrap() + { + return false; + } + + public boolean isServerWrap() + { + return false; + } + + public Set getRoles() + { + return new HashSet<>(Arrays.asList(this.subj, this.obj)); + } + + /*public boolean containsRole(Role role) + { + return this.subj.equals(role) || this.obj.equals(role); + }*/ + + @Override + public String toString() + { + return this.subj + getCommSymbol() + this.obj + ":" + this.mid + + this.payload; + } + + @Override + public int hashCode() + { + int hash = 149; + hash = 31 * hash + super.hashCode(); + hash = 31 * hash + this.subj.hashCode(); + return hash; + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof SAction)) + { + return false; + } + SAction them = (SAction) o; + return super.equals(o) // Checks canEquals + && this.subj.equals(them.subj); + } + + @Override + public boolean canEquals(Object o) + { + return o instanceof SAction; + } +} + + + + + + + + + + + + + + + + + + /*public IOAction project(Role self) + { + if (this.subj.equals(self)) + { + if (this.obj.equals(self)) + { + throw new RuntimeException("TODO: " + this); + } + else + { + return new Send(this.obj, this.mid, this.payload); + } + } + else + { + if (this.obj.equals(self)) + { + return new Receive(this.subj, this.mid, this.payload); + //return Receive.get(this.subj, this.mid, this.payload); + } + else + { + return null; // FIXME? + } + } + }*/ \ No newline at end of file diff --git a/scribble-core/src/main/java/org/scribble/core/model/global/actions/SClientWrap.java b/scribble-core/src/main/java/org/scribble/core/model/global/actions/SClientWrap.java new file mode 100644 index 000000000..88d84a880 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/model/global/actions/SClientWrap.java @@ -0,0 +1,67 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.model.global.actions; + +import org.scribble.core.type.name.Op; +import org.scribble.core.type.name.Role; +import org.scribble.core.type.session.Payload; + +// Wrap at the client side +public class SClientWrap extends SAction +{ + public SClientWrap(Role subj, Role obj) + { + super(subj, obj, Op.EMPTY_OP, Payload.EMPTY_PAYLOAD); + } + + @Override + public boolean isClientWrap() + { + return true; + } + + @Override + public int hashCode() + { + int hash = 1069; + hash = 31 * hash + super.hashCode(); + return hash; + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof SClientWrap)) + { + return false; + } + return super.equals(o); // Does canEquals + } + + @Override + public boolean canEquals(Object o) + { + return o instanceof SClientWrap; + } + + @Override + protected String getCommSymbol() + { + return "(->>)"; + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/model/global/actions/SDisconnect.java b/scribble-core/src/main/java/org/scribble/core/model/global/actions/SDisconnect.java new file mode 100644 index 000000000..7a41d62d6 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/model/global/actions/SDisconnect.java @@ -0,0 +1,67 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.model.global.actions; + +import org.scribble.core.type.name.Op; +import org.scribble.core.type.name.Role; +import org.scribble.core.type.session.Payload; + +public class SDisconnect extends SAction +{ + public SDisconnect(Role subj, Role obj) + { + super(subj, obj, Op.EMPTY_OP, Payload.EMPTY_PAYLOAD); + } + + @Override + public boolean isRequest() + { + return true; + } + + @Override + public int hashCode() + { + int hash = 1013; + hash = 31 * hash + super.hashCode(); + return hash; + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof SDisconnect)) + { + return false; + } + return super.equals(o); // Does canEquals + } + + @Override + public boolean canEquals(Object o) + { + return o instanceof SDisconnect; + } + + @Override + protected String getCommSymbol() + { + //return "\u00A1\u00A1abc"; + return "-/-"; + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/model/global/actions/SRecv.java b/scribble-core/src/main/java/org/scribble/core/model/global/actions/SRecv.java new file mode 100644 index 000000000..32f637624 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/model/global/actions/SRecv.java @@ -0,0 +1,65 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.model.global.actions; + +import org.scribble.core.type.name.MsgId; +import org.scribble.core.type.name.Role; +import org.scribble.core.type.session.Payload; + +public class SRecv extends SAction +{ + public SRecv(Role subj, Role obj, MsgId mid, Payload pay) + { + super(subj, obj, mid, pay); + } + + @Override + public boolean isReceive() + { + return true; + } + + @Override + public int hashCode() + { + int hash = 977; + hash = 31 * hash + super.hashCode(); + return hash; + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof SRecv)) + { + return false; + } + return super.equals(o); // Does canEquals + } + + public boolean canEquals(Object o) + { + return o instanceof SRecv; + } + + @Override + protected String getCommSymbol() + { + return "?"; + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/model/global/actions/SReq.java b/scribble-core/src/main/java/org/scribble/core/model/global/actions/SReq.java new file mode 100644 index 000000000..06534bb45 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/model/global/actions/SReq.java @@ -0,0 +1,66 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.model.global.actions; + +import org.scribble.core.type.name.MsgId; +import org.scribble.core.type.name.Role; +import org.scribble.core.type.session.Payload; + +public class SReq extends SAction +{ + public SReq(Role subj, Role obj, MsgId mid, Payload pay) + { + super(subj, obj, mid, pay); + } + + @Override + public boolean isRequest() + { + return true; + } + + @Override + public int hashCode() + { + int hash = 971; + hash = 31 * hash + super.hashCode(); + return hash; + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof SReq)) + { + return false; + } + return super.equals(o); // Does canEquals + } + + @Override + public boolean canEquals(Object o) + { + return o instanceof SReq; + } + + @Override + protected String getCommSymbol() + { + return "->>"; + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/model/global/actions/SRequest.java b/scribble-core/src/main/java/org/scribble/core/model/global/actions/SRequest.java new file mode 100644 index 000000000..0fdcc6def --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/model/global/actions/SRequest.java @@ -0,0 +1,67 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.model.global.actions; + +import org.scribble.core.type.name.MsgId; +import org.scribble.core.type.name.Role; +import org.scribble.core.type.session.Payload; + +public class SRequest extends SAction +{ + public SRequest(Role subj, Role obj, MsgId mid, Payload pay) + { + super(subj, obj, mid, pay); + } + + @Override + public boolean isRequest() + { + return true; + } + + @Override + public int hashCode() + { + int hash = 971; + hash = 31 * hash + super.hashCode(); + return hash; + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof SRequest)) + { + return false; + } + return super.equals(o); // Does canEquals + } + + @Override + public boolean canEquals(Object o) + { + return o instanceof SRequest; + } + + @Override + protected String getCommSymbol() + { + //return "!!"; + return "->>"; + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/model/global/actions/SSend.java b/scribble-core/src/main/java/org/scribble/core/model/global/actions/SSend.java new file mode 100644 index 000000000..67117293f --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/model/global/actions/SSend.java @@ -0,0 +1,66 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.model.global.actions; + +import org.scribble.core.type.name.MsgId; +import org.scribble.core.type.name.Role; +import org.scribble.core.type.session.Payload; + +public class SSend extends SAction +{ + public SSend(Role subj, Role obj, MsgId mid, Payload pay) + { + super(subj, obj, mid, pay); + } + + @Override + public boolean isSend() + { + return true; + } + + @Override + public int hashCode() + { + int hash = 977; + hash = 31 * hash + super.hashCode(); + return hash; + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof SSend)) + { + return false; + } + return super.equals(o); // Does canEquals + } + + @Override + public boolean canEquals(Object o) + { + return o instanceof SSend; + } + + @Override + protected String getCommSymbol() + { + return "!"; + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/model/global/actions/SServerWrap.java b/scribble-core/src/main/java/org/scribble/core/model/global/actions/SServerWrap.java new file mode 100644 index 000000000..02ecbd1ed --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/model/global/actions/SServerWrap.java @@ -0,0 +1,67 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.model.global.actions; + +import org.scribble.core.type.name.Op; +import org.scribble.core.type.name.Role; +import org.scribble.core.type.session.Payload; + +// Wrap at the server side +public class SServerWrap extends SAction +{ + public SServerWrap(Role subj, Role obj) + { + super(subj, obj, Op.EMPTY_OP, Payload.EMPTY_PAYLOAD); + } + + @Override + public boolean isServerWrap() + { + return true; + } + + @Override + public int hashCode() + { + int hash = 1087; + hash = 31 * hash + super.hashCode(); + return hash; + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof SServerWrap)) + { + return false; + } + return super.equals(o); // Does canEquals + } + + @Override + public boolean canEquals(Object o) + { + return o instanceof SServerWrap; + } + + @Override + protected String getCommSymbol() + { + return "(<<-)"; + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/model/visit/EdgeVisitor.java b/scribble-core/src/main/java/org/scribble/core/model/visit/EdgeVisitor.java new file mode 100644 index 000000000..b4f15b910 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/model/visit/EdgeVisitor.java @@ -0,0 +1,66 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.model.visit; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import org.scribble.core.model.MAction; +import org.scribble.core.model.MState; +import org.scribble.core.type.kind.ProtoKind; + +public abstract class EdgeVisitor +< + L, + A extends MAction, + S extends MState, + K extends ProtoKind +> +{ + // "One-time" traveral (visitor no for reuse) + private final Map>> seen = new HashMap<>(); + + public boolean hasSeen(S s, A a, S succ) + { + if (!this.seen.containsKey(s)) + { + return false; + } + Map> tmp = this.seen.get(s); + return tmp.containsKey(a) && tmp.get(a).contains(succ); + } + + protected void setSeen(S s, A a, S succ) + { + Map> tmp1 = this.seen.get(s); + if (tmp1 == null) + { + tmp1 = new HashMap<>(); + this.seen.put(s, tmp1); + } + Set tmp2 = tmp1.get(a); + if (tmp2 == null) + { + tmp2 = new HashSet<>(); + tmp1.put(a, tmp2); + } + if (!tmp2.contains(succ)) // Worth? Or just do add + { + tmp2.add(succ); + } + } +} + \ No newline at end of file diff --git a/scribble-core/src/main/java/org/scribble/core/model/visit/StateVisitor.java b/scribble-core/src/main/java/org/scribble/core/model/visit/StateVisitor.java new file mode 100644 index 000000000..8763ba076 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/model/visit/StateVisitor.java @@ -0,0 +1,47 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.model.visit; + +import java.util.HashSet; +import java.util.Set; + +import org.scribble.core.model.MAction; +import org.scribble.core.model.MState; +import org.scribble.core.type.kind.ProtoKind; + +public abstract class StateVisitor +< + L, + A extends MAction, + S extends MState, + K extends ProtoKind +> +{ + // "One-time" traveral (visitor no for reuse) + private final Set seen = new HashSet<>(); + + public boolean hasSeen(S s) + { + return this.seen.contains(s); + } + + protected void setSeen(S s) + { + //if (!this.seen.contains(s)) // Worth? Or just do add + { + this.seen.add(s); + } + } +} + \ No newline at end of file diff --git a/scribble-core/src/main/java/org/scribble/core/model/visit/local/EStateVisitor.java b/scribble-core/src/main/java/org/scribble/core/model/visit/local/EStateVisitor.java new file mode 100644 index 000000000..43aa8501d --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/model/visit/local/EStateVisitor.java @@ -0,0 +1,65 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.model.visit.local; + +import org.scribble.core.model.endpoint.EState; +import org.scribble.core.model.endpoint.actions.EAction; +import org.scribble.core.model.visit.StateVisitor; +import org.scribble.core.type.kind.Local; +import org.scribble.core.type.name.RecVar; +import org.scribble.util.ScribException; + +public abstract class EStateVisitor + extends StateVisitor +{ + + // Allows to visit branch succs with fresh visitors, but limited usefulness? because pattern doesn't support merge... + // (...but could try too? e.g., by using EGraph to join visitors? -- issue is recursion, may need to precompute/integrate traversal paths and join points, e.f., b/dfs) + // CHECKME: take "self" generic param, use as return? or just override + public EStateVisitor enter(EState s, EAction a, EState succ) + { + return this; + } + + public void visitAccept(EState s) throws ScribException + { + setSeen(s); + } + + public void visitOutput(EState s) throws ScribException + { + setSeen(s); + } + + public void visitPolyInput(EState s) throws ScribException + { + setSeen(s); + } + + public void visitServerWrap(EState s) throws ScribException + { + setSeen(s); + } + + public void visitTerminal(EState s) throws ScribException + { + setSeen(s); + } + + public void visitUnaryInput(EState s) throws ScribException + { + setSeen(s); + } +} + \ No newline at end of file diff --git a/scribble-core/src/main/java/org/scribble/core/model/visit/local/NonDetPayChecker.java b/scribble-core/src/main/java/org/scribble/core/model/visit/local/NonDetPayChecker.java new file mode 100644 index 000000000..dcca36997 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/model/visit/local/NonDetPayChecker.java @@ -0,0 +1,71 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.model.visit.local; + +import java.util.List; + +import org.scribble.core.model.endpoint.EState; +import org.scribble.core.model.endpoint.actions.EAction; +import org.scribble.util.ScribException; + +// CHECKME: should make via factory method? cf. VisitorFactory +public class NonDetPayChecker extends EStateVisitor +{ + + protected void checkNonDetPays(EState s) throws ScribException + { + List as = s.getActions(); + if (as.size() <= 1) + { + return; + } + for (EAction a : as) + { + if (as.stream().anyMatch(x -> x.peer.equals(a.peer) && x.mid.equals(a.mid) + && !x.payload.equals(a.payload))) + { + throw new ScribException( + "Bad non-deterministic action payloads: " + as); + } + } + } + + @Override + public void visitAccept(EState s) throws ScribException + { + super.visitOutput(s); // Does setSeen + checkNonDetPays(s); + } + + @Override + public void visitOutput(EState s) throws ScribException + { + super.visitOutput(s); // Does setSeen + checkNonDetPays(s); + } + + @Override + public void visitPolyInput(EState s) throws ScribException + { + super.visitOutput(s); // Does setSeen + checkNonDetPays(s); + } + + @Override + public void visitServerWrap(EState s) throws ScribException + { + super.visitOutput(s); // Does setSeen + checkNonDetPays(s); + } +} \ No newline at end of file diff --git a/scribble-core/src/main/java/org/scribble/core/type/kind/AbstractKind.java b/scribble-core/src/main/java/org/scribble/core/type/kind/AbstractKind.java new file mode 100644 index 000000000..c7700af67 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/kind/AbstractKind.java @@ -0,0 +1,50 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.kind; + +public abstract class AbstractKind implements Kind +{ + protected String kind; // Not final for easier serialiazation (OpKind) + + // For serialization + protected AbstractKind() + { + + } + + public AbstractKind(String kind) + { + this.kind = kind; + } + + @Override + public int hashCode() + { + int hash = 7901; + hash = 31 * hash + this.kind.hashCode(); + return hash; + } + + @Override + public abstract boolean equals(Object o); + + public abstract boolean canEqual(Object o); // Not really needed due to singleton pattern + + @Override + public String toString() + { + String s = this.getClass().toString(); + return s.substring("class org.sribble.type.kind.".length() + 1, s.length()); // FIXME: factor out by reflection (in initialiser) + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/type/kind/AmbigKind.java b/scribble-core/src/main/java/org/scribble/core/type/kind/AmbigKind.java new file mode 100644 index 000000000..0c3b7c6b8 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/kind/AmbigKind.java @@ -0,0 +1,45 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.kind; + + +public class AmbigKind extends AbstractKind implements NonRoleArgKind//, PayloadTypeKind +{ + public static final AmbigKind KIND = new AmbigKind(); + + protected AmbigKind() + { + super("Ambig"); + } + + @Override + public boolean equals(Object o) + { + if (o == this) + { + return true; + } + if (!(o instanceof AmbigKind)) + { + return false; + } + return ((AmbigKind) o).canEqual(this); + } + + @Override + public boolean canEqual(Object o) + { + return o instanceof AmbigKind; + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/type/kind/DataKind.java b/scribble-core/src/main/java/org/scribble/core/type/kind/DataKind.java new file mode 100644 index 000000000..ef9d60230 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/kind/DataKind.java @@ -0,0 +1,44 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.kind; + +public class DataKind extends AbstractKind implements PayElemKind, ImportKind, ModuleMemberKind +{ + public static final DataKind KIND = new DataKind(); + + protected DataKind() + { + super("DataType"); + } + + @Override + public boolean equals(Object o) + { + if (o == this) + { + return true; + } + if (!(o instanceof DataKind)) + { + return false; + } + return ((DataKind) o).canEqual(this); + } + + @Override + public boolean canEqual(Object o) + { + return o instanceof DataKind; + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/type/kind/Global.java b/scribble-core/src/main/java/org/scribble/core/type/kind/Global.java new file mode 100644 index 000000000..c7c6a1d8b --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/kind/Global.java @@ -0,0 +1,44 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.kind; + +public class Global extends AbstractKind implements ProtoKind +{ + public static final Global KIND = new Global(); + + protected Global() + { + super("Global"); + } + + @Override + public boolean equals(Object o) + { + if (o == this) + { + return true; + } + if (!(o instanceof Global)) + { + return false; + } + return ((Global) o).canEqual(this); + } + + @Override + public boolean canEqual(Object o) + { + return o instanceof Global; + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/type/kind/IdKind.java b/scribble-core/src/main/java/org/scribble/core/type/kind/IdKind.java new file mode 100644 index 000000000..2f91d9211 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/kind/IdKind.java @@ -0,0 +1,46 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.kind; + + +// IdKind can be disregarded, the "true" kind (for qualified names) recorded by the IdNode parent +public class IdKind extends AbstractKind +{ + public static final IdKind KIND = new IdKind(); + + protected IdKind() + { + super("Id"); + } + + @Override + public boolean equals(Object o) + { + if (o == this) + { + return true; + } + if (!(o instanceof IdKind)) + { + return false; + } + return ((IdKind) o).canEqual(this); + } + + @Override + public boolean canEqual(Object o) + { + return o instanceof IdKind; + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/type/kind/ImportKind.java b/scribble-core/src/main/java/org/scribble/core/type/kind/ImportKind.java new file mode 100644 index 000000000..6e2eb0d76 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/kind/ImportKind.java @@ -0,0 +1,20 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.kind; + + +public interface ImportKind extends Kind +{ + +} diff --git a/scribble-core/src/main/java/org/scribble/core/type/kind/Kind.java b/scribble-core/src/main/java/org/scribble/core/type/kind/Kind.java new file mode 100644 index 000000000..134b07bb3 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/kind/Kind.java @@ -0,0 +1,27 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.kind; + +import org.scribble.core.type.name.Name; + +public interface Kind +{ + public static Name castName(K kind, Name name) + { + kind.getClass().cast(name.getKind()); + @SuppressWarnings("unchecked") + Name tmp = (Name) name; + return tmp; + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/type/kind/Local.java b/scribble-core/src/main/java/org/scribble/core/type/kind/Local.java new file mode 100644 index 000000000..790c09ca6 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/kind/Local.java @@ -0,0 +1,44 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.kind; + +public class Local extends AbstractKind implements ProtoKind, PayElemKind +{ + public static final Local KIND = new Local(); + + protected Local() + { + super("Local"); + } + + @Override + public boolean equals(Object o) + { + if (o == this) + { + return true; + } + if (!(o instanceof Local)) + { + return false; + } + return ((Local) o).canEqual(this); + } + + @Override + public boolean canEqual(Object o) + { + return o instanceof Local; + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/type/kind/ModuleKind.java b/scribble-core/src/main/java/org/scribble/core/type/kind/ModuleKind.java new file mode 100644 index 000000000..65a392347 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/kind/ModuleKind.java @@ -0,0 +1,44 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.kind; + +public class ModuleKind extends AbstractKind implements ImportKind +{ + public static final ModuleKind KIND = new ModuleKind(); + + protected ModuleKind() + { + super("Module"); + } + + @Override + public boolean equals(Object o) + { + if (o == this) + { + return true; + } + if (!(o instanceof ModuleKind)) + { + return false; + } + return ((ModuleKind) o).canEqual(this); + } + + @Override + public boolean canEqual(Object o) + { + return o instanceof ModuleKind; + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/type/kind/ModuleMemberKind.java b/scribble-core/src/main/java/org/scribble/core/type/kind/ModuleMemberKind.java new file mode 100644 index 000000000..c180acb15 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/kind/ModuleMemberKind.java @@ -0,0 +1,20 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.kind; + + +public interface ModuleMemberKind extends Kind +{ + +} diff --git a/scribble-core/src/main/java/org/scribble/core/type/kind/MsgIdKind.java b/scribble-core/src/main/java/org/scribble/core/type/kind/MsgIdKind.java new file mode 100644 index 000000000..9ecbff345 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/kind/MsgIdKind.java @@ -0,0 +1,20 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.kind; + + +public interface MsgIdKind extends Kind +{ + +} diff --git a/scribble-core/src/main/java/org/scribble/core/type/kind/NonProtoKind.java b/scribble-core/src/main/java/org/scribble/core/type/kind/NonProtoKind.java new file mode 100644 index 000000000..c40231b48 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/kind/NonProtoKind.java @@ -0,0 +1,20 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.kind; + + +public interface NonProtoKind extends Kind +{ + +} diff --git a/scribble-core/src/main/java/org/scribble/core/type/kind/NonRoleArgKind.java b/scribble-core/src/main/java/org/scribble/core/type/kind/NonRoleArgKind.java new file mode 100644 index 000000000..fc9d53735 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/kind/NonRoleArgKind.java @@ -0,0 +1,22 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.kind; + + +// Following sesstype.Arg hierarchy +// Non-role args -- includes NonRoleParamKind, and AmbigKind +public interface NonRoleArgKind extends NonProtoKind +{ + +} diff --git a/scribble-core/src/main/java/org/scribble/core/type/kind/NonRoleParamKind.java b/scribble-core/src/main/java/org/scribble/core/type/kind/NonRoleParamKind.java new file mode 100644 index 000000000..9eb8768e2 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/kind/NonRoleParamKind.java @@ -0,0 +1,21 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.kind; + + +// Non-role params +public interface NonRoleParamKind extends NonRoleArgKind, ParamKind +{ + +} diff --git a/scribble-core/src/main/java/org/scribble/core/type/kind/OpKind.java b/scribble-core/src/main/java/org/scribble/core/type/kind/OpKind.java new file mode 100644 index 000000000..16d8527d1 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/kind/OpKind.java @@ -0,0 +1,59 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.kind; + +import java.io.IOException; +import java.io.Serializable; + +public class OpKind extends AbstractKind implements MsgIdKind, Serializable +{ + private static final long serialVersionUID = 1L; + + public static final OpKind KIND = new OpKind(); + + public OpKind() + { + super("Op"); + } + + private void writeObject(java.io.ObjectOutputStream stream) throws IOException + { + stream.writeObject(this.kind); + } + + private void readObject(java.io.ObjectInputStream stream) throws IOException, ClassNotFoundException + { + this.kind = (String) stream.readObject(); // i.e. "Op" + } + + @Override + public boolean equals(Object o) + { + if (o == this) + { + return true; + } + if (!(o instanceof OpKind)) + { + return false; + } + return ((OpKind) o).canEqual(this); + } + + @Override + public boolean canEqual(Object o) + { + return o instanceof OpKind; + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/type/kind/PackageKind.java b/scribble-core/src/main/java/org/scribble/core/type/kind/PackageKind.java new file mode 100644 index 000000000..ff060c378 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/kind/PackageKind.java @@ -0,0 +1,44 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.kind; + +public class PackageKind extends AbstractKind +{ + public static final PackageKind KIND = new PackageKind(); + + protected PackageKind() + { + super("Package"); + } + + @Override + public boolean equals(Object o) + { + if (o == this) + { + return true; + } + if (!(o instanceof PackageKind)) + { + return false; + } + return ((PackageKind) o).canEqual(this); + } + + @Override + public boolean canEqual(Object o) + { + return o instanceof PackageKind; + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/type/kind/ParamKind.java b/scribble-core/src/main/java/org/scribble/core/type/kind/ParamKind.java new file mode 100644 index 000000000..1d99e9172 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/kind/ParamKind.java @@ -0,0 +1,20 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.kind; + + +public interface ParamKind extends Kind +{ + +} diff --git a/scribble-core/src/main/java/org/scribble/core/type/kind/PayElemKind.java b/scribble-core/src/main/java/org/scribble/core/type/kind/PayElemKind.java new file mode 100644 index 000000000..288253725 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/kind/PayElemKind.java @@ -0,0 +1,21 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.kind; + + +// Following sesstype.Arg hierarchy +public interface PayElemKind extends NonRoleParamKind //ArgKind +{ + +} diff --git a/scribble-core/src/main/java/org/scribble/core/type/kind/ProtoKind.java b/scribble-core/src/main/java/org/scribble/core/type/kind/ProtoKind.java new file mode 100644 index 000000000..dded85fd5 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/kind/ProtoKind.java @@ -0,0 +1,19 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.kind; + +public interface ProtoKind extends ModuleMemberKind +{ + +} diff --git a/scribble-core/src/main/java/org/scribble/core/type/kind/RecVarKind.java b/scribble-core/src/main/java/org/scribble/core/type/kind/RecVarKind.java new file mode 100644 index 000000000..073498914 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/kind/RecVarKind.java @@ -0,0 +1,44 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.kind; + +public class RecVarKind extends AbstractKind +{ + public static final RecVarKind KIND = new RecVarKind(); + + protected RecVarKind() + { + super("RecVar"); + } + + @Override + public boolean equals(Object o) + { + if (o == this) + { + return true; + } + if (!(o instanceof RecVarKind)) + { + return false; + } + return ((RecVarKind) o).canEqual(this); + } + + @Override + public boolean canEqual(Object o) + { + return o instanceof RecVarKind; + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/type/kind/RoleKind.java b/scribble-core/src/main/java/org/scribble/core/type/kind/RoleKind.java new file mode 100644 index 000000000..8fd3d4e96 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/kind/RoleKind.java @@ -0,0 +1,44 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.kind; + +public class RoleKind extends AbstractKind implements ParamKind +{ + public static final RoleKind KIND = new RoleKind(); + + protected RoleKind() + { + super("Role"); + } + + @Override + public boolean equals(Object o) + { + if (o == this) + { + return true; + } + if (!(o instanceof RoleKind)) + { + return false; + } + return ((RoleKind) o).canEqual(this); + } + + @Override + public boolean canEqual(Object o) + { + return o instanceof RoleKind; + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/type/kind/SigKind.java b/scribble-core/src/main/java/org/scribble/core/type/kind/SigKind.java new file mode 100644 index 000000000..02545144e --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/kind/SigKind.java @@ -0,0 +1,47 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.kind; + + +// Following sesstype.Arg hierarchy +public class SigKind extends AbstractKind implements NonRoleParamKind, MsgIdKind, //ArgKind + ModuleMemberKind +{ + public static final SigKind KIND = new SigKind(); + + protected SigKind() + { + super("Sig"); + } + + @Override + public boolean equals(Object o) + { + if (o == this) + { + return true; + } + if (!(o instanceof SigKind)) + { + return false; + } + return ((SigKind) o).canEqual(this); + } + + @Override + public boolean canEqual(Object o) + { + return o instanceof SigKind; + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/type/name/AbstractName.java b/scribble-core/src/main/java/org/scribble/core/type/name/AbstractName.java new file mode 100644 index 000000000..91964724d --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/name/AbstractName.java @@ -0,0 +1,122 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.name; + +import java.io.IOException; +import java.util.Arrays; + +import org.scribble.core.type.kind.Kind; + +public abstract class AbstractName implements Name +{ + private static final long serialVersionUID = 1L; + + protected K kind; // non-final for serialization + + protected String[] elems; + + protected AbstractName(K kind, String... elems) + { + this.kind = kind; + this.elems = elems; + } + + @Override + public K getKind() + { + return this.kind; + } + + @Override + public int getElementCount() + { + return this.elems.length; + } + + @Override + public boolean isEmpty() + { + return this.elems.length == 0; + } + + @Override + public String[] getElements() + { + return Arrays.copyOf(this.elems, this.elems.length); + } + + // Not SimpleName so that e.g. ModuleName can return a simple ModuleName + @Override + public String getLastElement() + { + return this.elems[this.elems.length - 1]; + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof AbstractName)) + { + return false; + } + AbstractName them = (AbstractName) o; + return them.canEquals(this) && this.kind.equals(them.kind) + && Arrays.equals(this.elems, them.elems); + } + + public abstract boolean canEquals(Object o); + + @Override + public int hashCode() + { + int hash = 2749; + hash = 31 * hash + this.kind.hashCode(); + hash = 31 * hash + Arrays.hashCode(this.elems); + return hash; + } + + @Override + public String toString() + { + if (isEmpty()) + { + return ""; + } + String name = this.elems[0]; + for (int i = 1; i < this.elems.length; i++) + { + name += "." + this.elems[i]; + } + return name; + } + + private void writeObject(java.io.ObjectOutputStream out) throws IOException + { + out.writeObject(this.kind); + out.writeObject(this.elems); + } + + private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException + { + @SuppressWarnings("unchecked") + K k = (K) in.readObject(); + this.kind = k; + //this.kind = readKind(); // TODO: protected abstract -- will this work? + this.elems = (String[]) in.readObject(); + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/type/name/AmbigName.java b/scribble-core/src/main/java/org/scribble/core/type/name/AmbigName.java new file mode 100644 index 000000000..e8c0f8274 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/name/AmbigName.java @@ -0,0 +1,64 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.name; + +import org.scribble.core.type.kind.AmbigKind; + +public class AmbigName extends AbstractName +{ + private static final long serialVersionUID = 1L; + + public AmbigName(String text) + { + super(AmbigKind.KIND, text); + } + + public SigName toSigName() + { + return new SigName(getLastElement()); + } + + public DataName toDataName() + { + return new DataName(getLastElement()); + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof AmbigName)) + { + return false; + } + AmbigName n = (AmbigName) o; + return n.canEquals(this) && super.equals(o); + } + + public boolean canEquals(Object o) + { + return o instanceof AmbigName; + } + + @Override + public int hashCode() + { + int hash = 4073; + hash = 31 * super.hashCode(); + return hash; + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/type/name/DataName.java b/scribble-core/src/main/java/org/scribble/core/type/name/DataName.java new file mode 100644 index 000000000..b48cad2ea --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/name/DataName.java @@ -0,0 +1,80 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.name; + +import org.scribble.core.type.kind.DataKind; + + +// Potentially qualified/canonical payload type name; not the AST primitive identifier +// FIXME: record "external type name" from DataTypeDecl (for API gen)? cf. OutputSockGen#addSendOpParams +public class DataName extends MemberName + implements PayElemType +{ + private static final long serialVersionUID = 1L; + + public DataName(ModuleName modname, DataName membname) + { + super(DataKind.KIND, modname, membname); + } + + public DataName(String simplename) + { + super(DataKind.KIND, simplename); + } + + public boolean isDataName() + { + return true; + } + + @Override + public DataKind getKind() + { + return DataKind.KIND; + } + + @Override + public DataName getSimpleName() + { + return new DataName(getLastElement()); + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof DataName)) + { + return false; + } + DataName n = (DataName) o; + return n.canEquals(this) && super.equals(o); + } + + public boolean canEquals(Object o) + { + return o instanceof DataName; + } + + @Override + public int hashCode() + { + int hash = 2767; + hash = 31 * super.hashCode(); + return hash; + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/type/name/GDelegType.java b/scribble-core/src/main/java/org/scribble/core/type/name/GDelegType.java new file mode 100644 index 000000000..d8881dab3 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/name/GDelegType.java @@ -0,0 +1,104 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.name; + +import java.io.IOException; +import java.io.Serializable; + +import org.scribble.core.type.kind.Local; + +// CHECKME: factor out of name package? (and then PayloadType also needs to be moved out of name?) +public class GDelegType implements PayElemType, Serializable +{ + private static final long serialVersionUID = 1L; + + private GProtoName proto; // Cannot be final, for Serializable + private Role role; + + public GDelegType(GProtoName proto, Role role) + { + this.proto = proto; + this.role = role; + } + + @Override + public boolean isGDelegationType() + { + return true; + } + + public GProtoName getGlobalProtocol() + { + return this.proto; + } + + public Role getRole() + { + return this.role; + } + + @Override + public Local getKind() + { + return Local.KIND; + } + + @Override + public String toString() + { + return this.proto + "@" + this.role; + } + + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof GDelegType)) + { + return false; + } + GDelegType them = (GDelegType) o; + return them.canEqual(this) && this.proto.equals(them.proto) && this.role.equals(them.role); + } + + public boolean canEqual(Object o) + { + return o instanceof GDelegType; + } + + @Override + public int hashCode() + { + int hash = 1381; + hash = 31 * this.proto.hashCode(); + hash = 31 * this.role.hashCode(); + return hash; + } + + private void writeObject(java.io.ObjectOutputStream out) throws IOException + { + out.writeObject(this.proto); + out.writeObject(this.role); + } + + private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException + { + this.proto = (GProtoName) in.readObject(); + this.role = (Role) in.readObject(); + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/type/name/GProtoName.java b/scribble-core/src/main/java/org/scribble/core/type/name/GProtoName.java new file mode 100644 index 000000000..231efc3f3 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/name/GProtoName.java @@ -0,0 +1,66 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.name; + +import org.scribble.core.type.kind.Global; + + +public class GProtoName extends ProtoName +{ + private static final long serialVersionUID = 1L; + + public GProtoName(ModuleName modname, ProtoName membname) + { + super(Global.KIND, modname, membname); + } + + public GProtoName(String simpname) + { + super(Global.KIND, simpname); + } + + @Override + public GProtoName getSimpleName() + { + return new GProtoName(getLastElement()); + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof GProtoName)) + { + return false; + } + GProtoName n = (GProtoName) o; + return n.canEquals(this) && super.equals(o); + } + + public boolean canEquals(Object o) + { + return o instanceof GProtoName; + } + + @Override + public int hashCode() + { + int hash = 2777; + hash = 31 * super.hashCode(); + return hash; + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/type/name/Id.java b/scribble-core/src/main/java/org/scribble/core/type/name/Id.java new file mode 100644 index 000000000..8d33e64ab --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/name/Id.java @@ -0,0 +1,54 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.name; + +import org.scribble.core.type.kind.IdKind; + +public class Id extends AbstractName +{ + private static final long serialVersionUID = 1L; + + public Id(String text) + { + super(IdKind.KIND, text); + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof Id)) + { + return false; + } + Id n = (Id) o; + return n.canEquals(this) && super.equals(o); + } + + public boolean canEquals(Object o) + { + return o instanceof Id; + } + + @Override + public int hashCode() + { + int hash = 2753; + hash = 31 * super.hashCode(); + return hash; + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/type/name/LProtoName.java b/scribble-core/src/main/java/org/scribble/core/type/name/LProtoName.java new file mode 100644 index 000000000..c666b300a --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/name/LProtoName.java @@ -0,0 +1,73 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.name; + +import org.scribble.core.type.kind.Local; + + +public class LProtoName extends ProtoName + implements PayElemType // @Deprecated -- not used, deleg elems currently have to be (Global@Role) +{ + private static final long serialVersionUID = 1L; + + public LProtoName(ModuleName modname, ProtoName membname) + { + super(Local.KIND, modname, membname); + } + + public LProtoName(String simpname) + { + super(Local.KIND, simpname); + } + + /*@Override + public boolean isLDelegationType() + { + return true; + }*/ + + @Override + public LProtoName getSimpleName() + { + return new LProtoName(getLastElement()); + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof LProtoName)) + { + return false; + } + LProtoName n = (LProtoName) o; + return n.canEquals(this) && super.equals(o); + } + + public boolean canEquals(Object o) + { + return o instanceof LProtoName; + } + + @Override + public int hashCode() + { + int hash = 2789; + hash = 31 * super.hashCode(); + return hash; + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/type/name/MemberName.java b/scribble-core/src/main/java/org/scribble/core/type/name/MemberName.java new file mode 100644 index 000000000..4b2c240f9 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/name/MemberName.java @@ -0,0 +1,45 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.name; + +import org.scribble.core.type.kind.Kind; + + +// Simple name or qualified name +public abstract class MemberName extends QualName +{ + private static final long serialVersionUID = 1L; + + public MemberName(K kind, ModuleName modname, Name membname) + { + super(kind, compileMemberName(modname, membname)); + } + + public MemberName(K kind, String simplename) + { + super(kind, Name.compileElements(ModuleName.EMPTY_MODULENAME.getElements(), simplename)); + } + + @Override + public ModuleName getPrefix() + { + return new ModuleName(getPrefixElements()); + } + + // Similar in ModuleName + private static String[] compileMemberName(ModuleName modname, Name membname) + { + return Name.compileElements(modname.getElements(), membname.getLastElement()); + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/type/name/ModuleName.java b/scribble-core/src/main/java/org/scribble/core/type/name/ModuleName.java new file mode 100644 index 000000000..4511bde8d --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/name/ModuleName.java @@ -0,0 +1,108 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.name; + +import java.nio.file.Path; +import java.nio.file.Paths; + +import org.scribble.core.type.kind.ModuleKind; +import org.scribble.util.Constants; + +// General name: simple or full (a central class for value comparison) +public class ModuleName extends QualName +{ + private static final long serialVersionUID = 1L; + + protected static final ModuleName EMPTY_MODULENAME = new ModuleName(); + + protected ModuleName(String... elems) + { + super(ModuleKind.KIND, elems); + } + + public ModuleName(PackageName packname, ModuleName modname) + { + super(ModuleKind.KIND, compileModuleName(packname, modname)); + } + + public ModuleName(String modname) + { + super(ModuleKind.KIND, Name.compileElements(PackageName.EMPTY_PACKAGENAME.getElements(), modname)); + } + + public Path toPath() + { + String[] elems = getElements(); + String file = elems[0]; + for (int i = 1; i < elems.length; i++) + { + file += "/" + elems[i]; + } + return Paths.get(file + "." + Constants.SCRIBBLE_FILE_EXTENSION); + } + + public boolean isSimpleName() + { + return !isPrefixed(); + } + + @Override + public ModuleName getSimpleName() + { + return new ModuleName(getLastElement()); + } + + public PackageName getPrefix() + { + return new PackageName(getPrefixElements()); + } + + public PackageName getPackageName() + { + return getPrefix(); + } + + private static String[] compileModuleName(PackageName packname, ModuleName modname) + { + return Name.compileElements(packname.getElements(), modname.getLastElement()); + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof ModuleName)) + { + return false; + } + ModuleName n = (ModuleName) o; + return n.canEquals(this) && super.equals(o); + } + + public boolean canEquals(Object o) + { + return o instanceof ModuleName; + } + + @Override + public int hashCode() + { + int hash = 2797; + hash = 31 * super.hashCode(); + return hash; + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/type/name/MsgId.java b/scribble-core/src/main/java/org/scribble/core/type/name/MsgId.java new file mode 100644 index 000000000..f95ad2b30 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/name/MsgId.java @@ -0,0 +1,30 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.name; + +import org.scribble.core.type.kind.MsgIdKind; + + +public interface MsgId extends Name +{ + default boolean isOp() + { + return false; + } + + default boolean isSigName() + { + return false; + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/type/name/Name.java b/scribble-core/src/main/java/org/scribble/core/type/name/Name.java new file mode 100644 index 000000000..2c103444a --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/name/Name.java @@ -0,0 +1,43 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.name; + +import java.io.Serializable; +import java.util.Arrays; + +import org.scribble.core.type.kind.Kind; + + +public interface Name extends Serializable +{ + K getKind(); + + String[] getElements(); + int getElementCount(); + boolean isEmpty(); + String getLastElement(); + //boolean isPrefixed(); + //String[] getPrefixElements(); + + static String[] compileElements(String[] cn, String n) + { + if (cn.length == 0) + { + return new String[] { n }; + } + String[] elems = Arrays.copyOf(cn, cn.length + 1); + elems[elems.length - 1] = n; + return elems; + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/type/name/Named.java b/scribble-core/src/main/java/org/scribble/core/type/name/Named.java new file mode 100644 index 000000000..9d5043321 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/name/Named.java @@ -0,0 +1,22 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.name; + +import org.scribble.core.type.kind.Kind; + + +public interface Named +{ + Name toName(); +} diff --git a/scribble-core/src/main/java/org/scribble/core/type/name/Op.java b/scribble-core/src/main/java/org/scribble/core/type/name/Op.java new file mode 100644 index 000000000..27bab91db --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/name/Op.java @@ -0,0 +1,67 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.name; + +import org.scribble.core.type.kind.OpKind; + +public class Op extends AbstractName implements MsgId +{ + private static final long serialVersionUID = 1L; + + public static final Op EMPTY_OP = new Op(); + + protected Op() + { + super(OpKind.KIND); + } + + public Op(String text) + { + super(OpKind.KIND, text); + } + + @Override + public boolean isOp() + { + return true; + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof Op)) + { + return false; + } + Op n = (Op) o; + return n.canEquals(this) && super.equals(o); + } + + public boolean canEquals(Object o) + { + return o instanceof Op; + } + + @Override + public int hashCode() + { + int hash = 2801; + hash = 31 * super.hashCode(); + return hash; + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/type/name/PackageName.java b/scribble-core/src/main/java/org/scribble/core/type/name/PackageName.java new file mode 100644 index 000000000..96bc5a77d --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/name/PackageName.java @@ -0,0 +1,68 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.name; + +import org.scribble.core.type.kind.PackageKind; + +public class PackageName extends QualName +{ + private static final long serialVersionUID = 1L; + + public static final PackageName EMPTY_PACKAGENAME = new PackageName(); + + public PackageName(String... elems) + { + super(PackageKind.KIND, elems); + } + + @Override + public PackageName getPrefix() + { + return new PackageName(getPrefixElements()); + } + + @Override + public PackageName getSimpleName() + { + return new PackageName(getLastElement()); + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof PackageName)) + { + return false; + } + PackageName n = (PackageName) o; + return n.canEquals(this) && super.equals(o); + } + + public boolean canEquals(Object o) + { + return o instanceof PackageName; + } + + @Override + public int hashCode() + { + int hash = 2803; + hash = 31 * super.hashCode(); + return hash; + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/type/name/PayElemType.java b/scribble-core/src/main/java/org/scribble/core/type/name/PayElemType.java new file mode 100644 index 000000000..dbd0987ad --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/name/PayElemType.java @@ -0,0 +1,36 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.name; + +import org.scribble.core.type.kind.PayElemKind; +import org.scribble.core.type.session.Arg; + + +public interface PayElemType extends Arg +{ + default boolean isDataName() + { + return false; + } + + default boolean isGDelegationType() + { + return false; + } + + /*public boolean isLDelegationType() // Not currently used + { + return true; + }*/ +} diff --git a/scribble-core/src/main/java/org/scribble/core/type/name/ProtoName.java b/scribble-core/src/main/java/org/scribble/core/type/name/ProtoName.java new file mode 100644 index 000000000..bab4a8151 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/name/ProtoName.java @@ -0,0 +1,36 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.name; + +import org.scribble.core.type.kind.ProtoKind; + + +// Potentially qualified/canonical protocol name; not the AST primitive identifier +public abstract class ProtoName extends MemberName +{ + private static final long serialVersionUID = 1L; + + public ProtoName(K kind, ModuleName modname, ProtoName membname) + { + super(kind, modname, membname); + } + + public ProtoName(K kind, String simpname) + { + super(kind, simpname); + } + + @Override + public abstract ProtoName getSimpleName(); +} diff --git a/scribble-core/src/main/java/org/scribble/core/type/name/QualName.java b/scribble-core/src/main/java/org/scribble/core/type/name/QualName.java new file mode 100644 index 000000000..e071d7c35 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/name/QualName.java @@ -0,0 +1,46 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.name; + +import java.util.Arrays; + +import org.scribble.core.type.kind.Kind; + + +// A (potenitally" qualified name -- a compound name +public abstract class QualName extends AbstractName +{ + private static final long serialVersionUID = 1L; + + public QualName(K kind, String... elems) + { + super(kind, elems); + } + + //@Override + public boolean isPrefixed() + { + return this.elems.length > 1; + } + + //@Override + public String[] getPrefixElements() + { + return Arrays.copyOfRange(this.elems, 0, this.elems.length - 1); + } + + // Also done by Scope + public abstract Name getPrefix(); + public abstract Name getSimpleName(); +} diff --git a/scribble-core/src/main/java/org/scribble/core/type/name/RecVar.java b/scribble-core/src/main/java/org/scribble/core/type/name/RecVar.java new file mode 100644 index 000000000..7cdbc56ce --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/name/RecVar.java @@ -0,0 +1,60 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.name; + +import org.scribble.core.type.kind.RecVarKind; + +// CHECKME: RecVar inconsistent with, e.g., G/LProtocolName? +public class RecVar extends AbstractName //implements PathElement +{ + private static final long serialVersionUID = 1L; + + protected RecVar() + { + super(RecVarKind.KIND); + } + + public RecVar(String text) + { + super(RecVarKind.KIND, text); + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof RecVar)) + { + return false; + } + RecVar n = (RecVar) o; + return n.canEquals(this) && super.equals(o); + } + + public boolean canEquals(Object o) + { + return o instanceof RecVar; + } + + @Override + public int hashCode() + { + int hash = 2819; + hash = 31 * super.hashCode(); + return hash; + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/type/name/Role.java b/scribble-core/src/main/java/org/scribble/core/type/name/Role.java new file mode 100644 index 000000000..fb0e96349 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/name/Role.java @@ -0,0 +1,63 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.name; + +import org.scribble.core.type.kind.RoleKind; + + +public class Role extends AbstractName // CHECKME: type.name package has no SimpleName +{ + public static final Role EMPTY_ROLE = new Role(); + public static final Role SELF = new Role("self"); // TODO Factor out constant + + private static final long serialVersionUID = 1L; + + protected Role() + { + super(RoleKind.KIND); + } + + public Role(String text) + { + super(RoleKind.KIND, text); + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof Role)) + { + return false; + } + Role n = (Role) o; + return n.canEquals(this) && super.equals(o); + } + + public boolean canEquals(Object o) + { + return o instanceof Role; + } + + @Override + public int hashCode() + { + int hash = 2741; + hash = 31 * super.hashCode(); + return hash; + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/type/name/SigName.java b/scribble-core/src/main/java/org/scribble/core/type/name/SigName.java new file mode 100644 index 000000000..53b806993 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/name/SigName.java @@ -0,0 +1,86 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.name; + +import org.scribble.core.type.kind.SigKind; +import org.scribble.core.type.session.Msg; + + +// The name of a declared (imported) message signature member +public class SigName extends MemberName implements Msg, MsgId +{ + private static final long serialVersionUID = 1L; + + public SigName(ModuleName modname, SigName simplename) + { + super(SigKind.KIND, modname, simplename); + } + + public SigName(String simplename) + { + super(SigKind.KIND, simplename); + } + + @Override + public SigKind getKind() + { + return SigKind.KIND; // Same as this.kind + } + + @Override + public SigName getSimpleName() + { + return new SigName(getLastElement()); + } + + @Override + public MsgId getId() + { + return this; // FIXME: should be resolved to a canonical name + } + + @Override + public boolean isSigName() + { + return true; + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof SigName)) + { + return false; + } + SigName n = (SigName) o; + return n.canEquals(this) && super.equals(o); + } + + public boolean canEquals(Object o) + { + return o instanceof SigName; + } + + @Override + public int hashCode() + { + int hash = 2791; + hash = 31 * super.hashCode(); + return hash; + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/type/name/Substitutions.java b/scribble-core/src/main/java/org/scribble/core/type/name/Substitutions.java new file mode 100644 index 000000000..b04baf91b --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/name/Substitutions.java @@ -0,0 +1,135 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.name; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.scribble.core.lang.SubprotoSig; +import org.scribble.core.type.kind.NonRoleParamKind; +import org.scribble.core.type.session.Arg; + +// CHECKME: move to util? +public class Substitutions +{ + // Old name -> new name + private final Map rsubs = new HashMap<>(); + private final Map, Arg> + asubs = new HashMap<>(); + // Keys are actually simple names (params) + // args are MessageSigName or DataType (but not MessageSig) -- N.B. substitution may replace sig name with a sig + // NonRoleParamKind, not NonRoleArgKind, because latter includes AmbigKind due to parsing requirements + // Better (CHECKME: necessary?) to separate roles and args -- but MessageSigName and DataType need to be distinct (so can group up, cf. NonRoleArgList) + + public Substitutions(List rold, List rnew, + List> aold, + List> anew) + { + if (rold.size() != rnew.size()) + { + throw new RuntimeException( + "Role list arity mismatch: " + rold + " ; " + rnew); + } + if (aold.size() != anew.size()) + { + throw new RuntimeException( + "Arg list arity mismatch: " + aold + " ; " + anew); + } + Iterator i = rnew.iterator(); + rold.forEach(x -> this.rsubs.put(x, i.next())); + Iterator> j = anew.iterator(); + aold.forEach(x -> this.asubs.put(x, j.next())); + } + + /*public void put(N old, N neu) + { + this.subs.put(old, neu); + }*/ + + public Role subsRole(Role old) + { + return subsRole(old, false); + } + + public Role subsRole(Role old, boolean passive) + { + if (!this.rsubs.containsKey(old)) + { + if (!passive) + { + throw new RuntimeException("Unknown role: " + old); + } + return old; + } + return this.rsubs.get(old); + } + + public Arg subsArg(MemberName old) + { + return subsArg(old, false); + } + + public // + Arg subsArg(MemberName old, boolean passive) + // ? param more convenient for accepting DataType/MessageSigName params + { + if (!this.asubs.containsKey(old)) + { + if (!passive) + { + throw new RuntimeException("Unknown param/arg: " + old); + } + return SubprotoSig.paramToArg(old); + } + return this.asubs.get(old); + } + + public boolean hasArg(MemberName old) + // ? param more convenient for accepting DataType/MessageSigName params + { + return this.asubs.containsKey(old); + } + + @Override + public String toString() + { + return this.rsubs + "; " + this.asubs; + } + + @Override + public int hashCode() + { + int hash = 1889; + hash = 31 * hash + this.rsubs.hashCode(); + hash = 31 * hash + this.asubs.hashCode(); + return hash; + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof Substitutions)) + { + return false; + } + Substitutions them = (Substitutions) o; + return this.rsubs.equals(them.rsubs) && this.asubs.equals(them.asubs); + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/type/session/Arg.java b/scribble-core/src/main/java/org/scribble/core/type/session/Arg.java new file mode 100644 index 000000000..74b2999bd --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/session/Arg.java @@ -0,0 +1,22 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.session; + +import org.scribble.core.type.kind.NonRoleArgKind; + +// A subprotocol argument (DoArgNode): SigKind or PayloadTypeKind +public interface Arg +{ + NonRoleArgKind getKind(); +} diff --git a/scribble-core/src/main/java/org/scribble/core/type/session/BasicInteraction.java b/scribble-core/src/main/java/org/scribble/core/type/session/BasicInteraction.java new file mode 100644 index 000000000..2006b9edd --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/session/BasicInteraction.java @@ -0,0 +1,74 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.session; + +import org.antlr.runtime.tree.CommonTree; +import org.scribble.core.type.kind.ProtoKind; + +public abstract class BasicInteraction> + extends STypeBase implements SType +{ + public BasicInteraction(CommonTree source) + { + super(source); + } + + @Override + public CommonTree getSource() + { + return (CommonTree) super.getSource(); + } + + + + + + + + + + + + + /*@Override + public Set getRecVars() + { + return Collections.emptySet(); + } + + @Override + public BasicInteraction getInlined(STypeInliner v) + { + return this; + } + + @Override + public BasicInteraction unfoldAllOnce(STypeUnfolder u) + { + return this; + } + + @Override + public List> getProtoDependencies() + { + return Collections.emptyList(); + } + + @Override + public BasicInteraction pruneRecs() + { + return this; + } + */ +} diff --git a/scribble-core/src/main/java/org/scribble/core/type/session/Choice.java b/scribble-core/src/main/java/org/scribble/core/type/session/Choice.java new file mode 100644 index 000000000..6e8956e09 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/session/Choice.java @@ -0,0 +1,201 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.session; + +import java.util.Collections; +import java.util.List; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.antlr.runtime.tree.CommonTree; +import org.scribble.core.type.kind.ProtoKind; +import org.scribble.core.type.name.Role; +import org.scribble.core.visit.STypeAgg; +import org.scribble.core.visit.STypeAggNoThrow; +import org.scribble.util.ScribException; + +public abstract class Choice> + extends STypeBase implements SType +{ + public final Role subj; + public final List blocks; // Pre: size > 0 + // CHECKME: rename? + + public Choice(CommonTree source, Role subj, + List blocks) + { + super(source); + this.subj = subj; + this.blocks = Collections.unmodifiableList(blocks); + } + + public abstract Choice reconstruct(CommonTree source, Role subj, + List blocks); + //List> blocks); + + @Override + public T visitWith(STypeAgg v) throws ScribException + { + return v.visitChoice(this); + } + + @Override + public T visitWithNoThrow(STypeAggNoThrow v) + { + return v.visitChoice(this); + } + + @Override + public Stream gather(Function, Stream> f) + { + return Stream.concat(f.apply(this), + this.blocks.stream().flatMap(x -> x.gather(f))); + } + + @Override + public String toString() + { + return "choice at " + this.subj + " " + + this.blocks.stream().map(x -> "{\n" + x.toString() + "\n}") + .collect(Collectors.joining(" or ")); + } + + @Override + public int hashCode() + { + int hash = 1487; + hash = 31 * hash + super.hashCode(); + hash = 31 * hash + this.subj.hashCode(); + hash = 31 * hash + this.blocks.hashCode(); + return hash; + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof Choice)) + { + return false; + } + Choice them = (Choice) o; + return super.equals(this) // Does canEquals + && this.subj.equals(them.subj) && this.blocks.equals(them.blocks); + } + + + + + + + + + + + + + + + + + /* + + @Override + public SType visitWith(STypeVisitor v) throws ScribException + { + return v.visitChoice(this); + } + + @Override + public SType visitWithNoEx(STypeVisitorNoEx v) + { + return v.visitChoice(this); + } + + @Override + public Set getRoles() + { + Set res = Stream.of(this.subj).collect(Collectors.toSet()); + this.blocks.forEach(x -> res.addAll(x.getRoles())); + return res; + } + + @Override + public Set> getMessageIds() + { + return this.blocks.stream().flatMap(x -> x.getMessageIds().stream()) + .collect(Collectors.toSet()); + } + + @Override + public Set getRecVars() + { + return this.blocks.stream().flatMap(x -> x.getRecVars().stream()) + .collect(Collectors.toSet()); + } + + @Override + public Choice getInlined(STypeInliner v) + { + CommonTree source = getSource(); // CHECKME: or empty source? + List blocks = this.blocks.stream().map(x -> x.getInlined(v)) + .collect(Collectors.toList()); + return reconstruct(source, this.subj, blocks); + } + + @Override + public Choice unfoldAllOnce(STypeUnfolder u) + { + CommonTree source = getSource(); // CHECKME: or empty source? + List blocks = this.blocks.stream().map(x -> x.unfoldAllOnce(u)) + .collect(Collectors.toList()); + return reconstruct(source, this.subj, blocks); + } + + @Override + public List> getProtoDependencies() + { + return this.blocks.stream().flatMap(x -> x.getProtoDependencies().stream()) + .distinct().collect(Collectors.toList()); + } + + @Override + public List> getNonProtoDependencies() + { + return this.blocks.stream() + .flatMap(x -> x.getNonProtoDependencies().stream()).distinct() + .collect(Collectors.toList()); + } + + @Override + public Choice substitute(Substitutions subs) + { + List blocks = this.blocks.stream().map(x -> x.substitute(subs)) + .collect(Collectors.toList()); + return reconstruct(getSource(), subs.subsRole(this.subj), blocks); + } + + @Override + public Choice pruneRecs() + { + List blocks = this.blocks.stream().map(x -> x.pruneRecs()) + .collect(Collectors.toList()); + return reconstruct(getSource(), this.subj, blocks); + } + */ +} diff --git a/scribble-core/src/main/java/org/scribble/core/type/session/ConnectAction.java b/scribble-core/src/main/java/org/scribble/core/type/session/ConnectAction.java new file mode 100644 index 000000000..b7bdfa26b --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/session/ConnectAction.java @@ -0,0 +1,77 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.session; + +import org.antlr.runtime.tree.CommonTree; +import org.scribble.core.type.kind.ProtoKind; +import org.scribble.core.type.name.Role; + +public abstract class ConnectAction> + extends DirectedInteraction +{ + public ConnectAction(CommonTree source, // BaseInteractionNode not ideal + Msg msg, Role src, Role dst) + { + super(source, msg, src, dst); + } + + + + + + + + + + + + + + + + + + + + + /*@Override + public List> getNonProtoDependencies() + { + List> res = new LinkedList<>(); + if (this.msg.isMessageSigName()) + { + res.add((MessageSigName) this.msg); + } + else //if (this.msg.isMessageSig) + { + Payload pay = ((MessageSig) this.msg).payload; + for (PayloadElemType p : pay.elems) + { + if (p.isDataType()) + { + res.add((DataType) p); + } + else if (p.isGDelegationType()) + { + throw new RuntimeException("Shouldn't get in here: " + this); + } + else + { + throw new RuntimeException("[TODO]: " + this); + } + } + } + return res; + }*/ +} diff --git a/scribble-core/src/main/java/org/scribble/core/type/session/Continue.java b/scribble-core/src/main/java/org/scribble/core/type/session/Continue.java new file mode 100644 index 000000000..ebfc1aec3 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/session/Continue.java @@ -0,0 +1,165 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.session; + +import java.util.function.Function; +import java.util.stream.Stream; + +import org.antlr.runtime.tree.CommonTree; +import org.scribble.core.type.kind.ProtoKind; +import org.scribble.core.type.name.RecVar; +import org.scribble.core.visit.STypeAgg; +import org.scribble.core.visit.STypeAggNoThrow; +import org.scribble.util.ScribException; + +public abstract class Continue> + extends STypeBase +{ + public final RecVar recvar; + + public Continue(//org.scribble.ast.Continue source, + CommonTree source, // Due to inlining, do -> continue + RecVar recvar) + { + super(source); + this.recvar = recvar; + } + + public abstract Continue reconstruct( + CommonTree source, RecVar recvar); + + @Override + public T visitWith(STypeAgg v) throws ScribException + { + return v.visitContinue(this); + } + + @Override + public T visitWithNoThrow(STypeAggNoThrow v) + { + return v.visitContinue(this); + } + + @Override + public Stream gather(Function, Stream> f) + { + return f.apply(this); + } + + @Override + public String toString() + { + return "continue " + this.recvar + ";"; + } + + @Override + public int hashCode() + { + int hash = 3217; + hash = 31 * hash + super.hashCode(); + hash = 31 * hash + this.recvar.hashCode(); + return hash; + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof Continue)) + { + return false; + } + Continue them = (Continue) o; + return super.equals(this) // Does canEquals + && this.recvar.equals(them.recvar); + } + + + + + + + + + + + /* + + @Override + public SType visitWith(STypeVisitor v) throws ScribException + { + return v.visitContinue(this); + } + + @Override + public SType visitWithNoEx(STypeVisitorNoEx v) + { + return v.visitContinue(this); + } + + @Override + public Set getRoles() + { + return Collections.emptySet(); + } + + @Override + public Set> getMessageIds() + { + return Collections.emptySet(); + } + + @Override + public Set getRecVars() + { + return Stream.of(this.recvar).collect(Collectors.toSet()); + } + + @Override + public Continue getInlined(STypeInliner v) + { + RecVar rv = v.getInlinedRecVar(this.recvar); + return reconstruct(getSource(), rv); + } + + @Override + public List> getProtoDependencies() + { + return Collections.emptyList(); + } + + @Override + public List> getNonProtoDependencies() + { + return Collections.emptyList(); + } + + @Override + public Continue substitute(Substitutions subs) + { + //return reconstruct(getSource(), this.recvar); + return this; + } + + @Override + public Continue pruneRecs() + { + //return reconstruct(getSource(), this.recvar); + return this; + } + */ +} diff --git a/scribble-core/src/main/java/org/scribble/core/type/session/DirectedInteraction.java b/scribble-core/src/main/java/org/scribble/core/type/session/DirectedInteraction.java new file mode 100644 index 000000000..c7c805bd5 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/session/DirectedInteraction.java @@ -0,0 +1,155 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.session; + +import java.util.function.Function; +import java.util.stream.Stream; + +import org.antlr.runtime.tree.CommonTree; +import org.scribble.core.type.kind.ProtoKind; +import org.scribble.core.type.name.Role; +import org.scribble.core.visit.STypeAgg; +import org.scribble.core.visit.STypeAggNoThrow; +import org.scribble.util.ScribException; + +// Besides directed-ness, also features a Message +public abstract class DirectedInteraction> + extends BasicInteraction +{ + // Following ast children order + public final Msg msg; + public final Role src; + public final Role dst; + + public DirectedInteraction(CommonTree source, + Msg msg, Role src, Role dst) + { + super(source); + this.msg = msg; + this.src = src; + this.dst = dst; + } + + public abstract DirectedInteraction reconstruct( + CommonTree source, Msg msg, Role src, + Role dst); + + @Override + public T visitWith(STypeAgg v) throws ScribException + { + return v.visitDirectedInteraction(this); + } + + @Override + public T visitWithNoThrow(STypeAggNoThrow v) + { + return v.visitDirectedInteraction(this); + } + + @Override + public Stream gather(Function, Stream> f) + { + return f.apply(this); + } + + @Override + public CommonTree getSource() + { + return (CommonTree) super.getSource(); + } + + @Override + public int hashCode() + { + int hash = 10631; + hash = 31 * hash + super.hashCode(); + hash = 31 * hash + this.msg.hashCode(); + hash = 31 * hash + this.src.hashCode(); + hash = 31 * hash + this.dst.hashCode(); + return hash; + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof DirectedInteraction)) + { + return false; + } + DirectedInteraction them = (DirectedInteraction) o; + return super.equals(this) // Does canEquals + && this.msg.equals(them.msg) && this.src.equals(them.src) + && this.dst.equals(them.dst); + } + + + + + + + + + + + + + + /* + + @Override + public SType visitWith(STypeVisitor v) throws ScribException + { + return v.visitDirectedInteraction(this); + } + + @Override + public SType visitWithNoEx(STypeVisitorNoEx v) + { + return v.visitDirectedInteraction(this); + } + + @Override + public Set getRoles() + { + // Includes self + return Stream.of(this.src, this.dst).collect(Collectors.toSet()); + } + + @Override + public Set> getMessageIds() + { + return Stream.of(this.msg.getId()).collect(Collectors.toSet()); + } + + @Override + public DirectedInteraction substitute(Substitutions subs) + { + Message msg = this.msg; + if (msg instanceof MemberName) + { + MemberName n = (MemberName) msg; + if (subs.hasArg(n)) + { + msg = (Message) subs.subsArg(n); + } + } + return reconstruct(getSource(), msg, subs.subsRole(this.src), + subs.subsRole(this.dst)); + } + */ +} diff --git a/scribble-core/src/main/java/org/scribble/core/type/session/DisconnectAction.java b/scribble-core/src/main/java/org/scribble/core/type/session/DisconnectAction.java new file mode 100644 index 000000000..d7d44e78d --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/session/DisconnectAction.java @@ -0,0 +1,145 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.session; + +import java.util.function.Function; +import java.util.stream.Stream; + +import org.antlr.runtime.tree.CommonTree; +import org.scribble.core.type.kind.ProtoKind; +import org.scribble.core.type.name.Role; +import org.scribble.core.visit.STypeAgg; +import org.scribble.core.visit.STypeAggNoThrow; +import org.scribble.util.ScribException; + +// Base class would be "SymmetricInteraction" (cf., DirectedInteraction) +public abstract class DisconnectAction> + extends BasicInteraction +{ + public final Role left; + public final Role right; + + public DisconnectAction(CommonTree source, + Role left, Role right) + { + super(source); + this.left = left; + this.right = right; + } + + public abstract DisconnectAction reconstruct( + CommonTree source, Role src, Role dst); + + @Override + public T visitWith(STypeAgg v) throws ScribException + { + return v.visitDisconnect(this); + } + + @Override + public T visitWithNoThrow(STypeAggNoThrow v) + { + return v.visitDisconnect(this); + } + + @Override + public Stream gather(Function, Stream> f) + { + return f.apply(this); + } + + @Override + public int hashCode() + { + int hash = 10663; + hash = 31 * hash + super.hashCode(); + hash = 31 * hash + this.left.hashCode(); + hash = 31 * hash + this.right.hashCode(); + return hash; + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof DisconnectAction)) + { + return false; + } + DisconnectAction them = (DisconnectAction) o; + return super.equals(this) // Does canEquals + && this.left.equals(them.left) && this.right.equals(them.right); + } + + + + + + + + + + + + + + + + + + + /* + + @Override + public SType visitWith(STypeVisitor v) throws ScribException + { + return v.visitDisconnect(this); + } + + @Override + public SType visitWithNoEx(STypeVisitorNoEx v) + { + return v.visitDisconnect(this); + } + + @Override + public Set getRoles() + { + // Includes self + return Stream.of(this.left, this.right).collect(Collectors.toSet()); + } + + @Override + public Set> getMessageIds() + { + return Collections.emptySet(); + } + + @Override + public List> getNonProtoDependencies() + { + return Collections.emptyList(); + } + + @Override + public DisconnectAction substitute(Substitutions subs) + { + return reconstruct(getSource(), subs.subsRole(this.left), + subs.subsRole(this.right)); + } + */ +} diff --git a/scribble-core/src/main/java/org/scribble/core/type/session/Do.java b/scribble-core/src/main/java/org/scribble/core/type/session/Do.java new file mode 100644 index 000000000..839cde50c --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/session/Do.java @@ -0,0 +1,219 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.session; + +import java.util.Collections; +import java.util.List; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.antlr.runtime.tree.CommonTree; +import org.scribble.core.job.Core; +import org.scribble.core.lang.Protocol; +import org.scribble.core.type.kind.NonRoleParamKind; +import org.scribble.core.type.kind.ProtoKind; +import org.scribble.core.type.name.ProtoName; +import org.scribble.core.type.name.Role; +import org.scribble.core.visit.STypeAgg; +import org.scribble.core.visit.STypeAggNoThrow; +import org.scribble.util.ScribException; + +public abstract class Do> + extends STypeBase +{ + public final ProtoName proto; // Currently disamb'd to fullname by GTypeTranslator (see GDoDel::translate) + public final List roles; // Ordered role args; pre: size > 2 + public final List> args; + // NonRoleParamKind, not NonRoleArgKind, because latter includes AmbigKind due to parsing requirements + + public Do(CommonTree source, ProtoName proto, + List roles, List> args) + { + super(source); + this.proto = proto; + this.roles = Collections.unmodifiableList(roles); + this.args = Collections.unmodifiableList(args); + } + + /*// Not that useful: calling on Do doesn't give the overridden return + public abstract ProtoName getProto(); // Override with concrete return*/ + + public abstract Protocol getTarget(Core core); // CHECKME: "?" + + public abstract Do reconstruct(CommonTree source, + ProtoName proto, List roles, List> args); + + @Override + public T visitWith(STypeAgg v) throws ScribException + { + return v.visitDo(this); + } + + @Override + public T visitWithNoThrow(STypeAggNoThrow v) + { + return v.visitDo(this); + } + + @Override + public Stream gather(Function, Stream> f) + { + return f.apply(this); + } + + @Override + public String toString() + { + return "do " + this.proto + + "<" + + this.args.stream().map(x -> x.toString()) + .collect(Collectors.joining(", ")) + + ">" + + "(" + this.roles.stream().map(x -> x.toString()) + .collect(Collectors.joining(", ")) + + ");"; + } + + @Override + public int hashCode() + { + int hash = 193; + hash = 31 * hash + super.hashCode(); + hash = 31 * hash + this.proto.hashCode(); + hash = 31 * hash + this.roles.hashCode(); + hash = 31 * hash + this.args.hashCode(); + return hash; + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof Do)) + { + return false; + } + Do them = (Do) o; + return super.equals(this) // Does canEquals + && this.proto.equals(them.proto) && this.roles.equals(them.roles) + && this.args.equals(them.args); + } + + + + + + + + + + + + + + + /* + @Override + public SType visitWith(STypeVisitor v) throws ScribException + { + return v.visitDo(this); + } + + @Override + public SType visitWithNoEx(STypeVisitorNoEx v) + { + return v.visitDo(this); + } + + @Override + public Set getRoles() + { + return this.roles.stream().collect(Collectors.toSet()); + } + + @Override + public Set> getMessageIds() + { + Set> mids = new HashSet<>(); + for (Arg a : this.args) + { + if (a instanceof Message) + { + mids.add(((Message) a).getId()); + } + } + return mids; + } + + @Override + public Set getRecVars() + { + return Collections.emptySet(); + } + + @Override + public SType unfoldAllOnce(STypeUnfolder u) + { + throw new RuntimeException("Unsupported for Do: " + this); + } + + @Override + public List> getProtoDependencies() + { + return Stream.of(this.proto).collect(Collectors.toList()); + } + + @Override + public List> getNonProtoDependencies() + { + return this.args.stream() + .filter(x -> (x instanceof MessageSig) || (x instanceof DataType)) // CHECKME: refactor? + .map(x -> (MemberName) x).collect(Collectors.toList()); + } + + @Override + public Do pruneRecs() + { + return this; + } + + @Override + public Do substitute(Substitutions subs) + { + List roles = this.roles.stream().map(x -> subs.subsRole(x)) + .collect(Collectors.toList()); + List> args = new LinkedList<>(); + for (Arg a : this.args) + { + if (a instanceof MemberName && subs.hasArg((MemberName) a)) + { + if (a instanceof DataType) + { + a = subs.subsArg((DataType) a); + } + else if (a instanceof MessageSigName) + { + a = subs.subsArg((MessageSigName) a); + } + } + args.add(a); + } + return reconstruct(getSource(), this.proto, roles, args); + } + */ +} diff --git a/scribble-core/src/main/java/org/scribble/core/type/session/Msg.java b/scribble-core/src/main/java/org/scribble/core/type/session/Msg.java new file mode 100644 index 000000000..f5a852ef5 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/session/Msg.java @@ -0,0 +1,36 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.session; + +import org.scribble.core.type.kind.MsgIdKind; +import org.scribble.core.type.kind.SigKind; +import org.scribble.core.type.name.MsgId; + + + +// A sig kind name: MessageSignature value (or parameter) +public interface Msg extends Arg +{ + MsgId getId(); + + default boolean isSigLit() + { + return false; + } + + default boolean isSigName() + { + return false; + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/type/session/MsgTransfer.java b/scribble-core/src/main/java/org/scribble/core/type/session/MsgTransfer.java new file mode 100644 index 000000000..664095387 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/session/MsgTransfer.java @@ -0,0 +1,76 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.session; + +import org.antlr.runtime.tree.CommonTree; +import org.scribble.core.type.kind.ProtoKind; +import org.scribble.core.type.name.Role; + +public abstract class MsgTransfer> + extends DirectedInteraction +{ + public MsgTransfer(CommonTree source, + Msg msg, Role src, Role dst) + { + super(source, msg, src, dst); + } + + + + + + + + + + + + + + + + + + + /* + @Override + public List> getNonProtoDependencies() + { + List> res = new LinkedList<>(); + if (this.msg.isMessageSigName()) + { + res.add((MessageSigName) this.msg); + } + else //if (this.msg.isMessageSig) + { + Payload pay = ((MessageSig) this.msg).payload; + for (PayloadElemType p : pay.elems) + { + if (p.isDataType()) + { + res.add((DataType) p); + } + else if (p.isGDelegationType()) // TODO FIXME: should be projected to local name + { + res.add(((GDelegationType) p).getGlobalProtocol()); + } + else + { + throw new RuntimeException("[TODO]: " + this); + } + } + } + return res; + }*/ +} diff --git a/scribble-core/src/main/java/org/scribble/core/type/session/Payload.java b/scribble-core/src/main/java/org/scribble/core/type/session/Payload.java new file mode 100644 index 000000000..95a64d84c --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/session/Payload.java @@ -0,0 +1,74 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.session; + +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; + +import org.scribble.core.type.kind.PayElemKind; +import org.scribble.core.type.name.PayElemType; + +public class Payload +{ + public static final Payload EMPTY_PAYLOAD = new Payload( + Collections.emptyList()); + + public final List> elems; + + public Payload(List> elems) + { + this.elems = Collections.unmodifiableList(elems); + } + + public boolean isEmpty() + { + return this.elems.isEmpty(); + } + + @Override + public int hashCode() + { + int hash = 577; + hash = 31 * hash + this.elems.hashCode(); + return hash; + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof Payload)) + { + return false; + } + return this.elems.equals(((Payload) o).elems); + } + + @Override + public String toString() + { + return "(" + this.elems.stream().map(x -> x.toString()) + .collect(Collectors.joining(", ")) + ")"; + } + + /*@Override + public boolean isParameter() + { + return false; + }*/ +} diff --git a/scribble-core/src/main/java/org/scribble/core/type/session/Recursion.java b/scribble-core/src/main/java/org/scribble/core/type/session/Recursion.java new file mode 100644 index 000000000..33b362ee5 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/session/Recursion.java @@ -0,0 +1,180 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.session; + +import java.util.function.Function; +import java.util.stream.Stream; + +import org.antlr.runtime.tree.CommonTree; +import org.scribble.core.type.kind.ProtoKind; +import org.scribble.core.type.name.RecVar; +import org.scribble.core.visit.STypeAgg; +import org.scribble.core.visit.STypeAggNoThrow; +import org.scribble.util.ScribException; + +public abstract class Recursion> + extends STypeBase +{ + public final RecVar recvar; + public final B body; + + public Recursion(//org.scribble.ast.Recursion source, + CommonTree source, // Due to inlining, protodecl -> rec + RecVar recvar, B body) + { + super(source); + this.recvar = recvar; + this.body = body; + } + + public abstract Recursion reconstruct( + CommonTree source, RecVar recvar, B body); + + @Override + public T visitWith(STypeAgg v) throws ScribException + { + return v.visitRecursion(this); + } + + @Override + public T visitWithNoThrow(STypeAggNoThrow v) + { + return v.visitRecursion(this); + } + + @Override + public Stream gather(Function, Stream> f) + { + return Stream.concat(f.apply(this), this.body.gather(f)); + } + + @Override + public String toString() + { + return "rec " + this.recvar + " {\n" + this.body + "\n}"; + } + + @Override + public int hashCode() + { + int hash = 1487; + hash = 31 * hash + super.hashCode(); + hash = 31 * hash + this.recvar.hashCode(); + hash = 31 * hash + this.body.hashCode(); + return hash; + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof Recursion)) + { + return false; + } + Recursion them = (Recursion) o; + return super.equals(this) // Does canEquals + && this.recvar.equals(them.recvar) && this.body.equals(them.body); + } + + + + + + + + + + + + /* + @Override + public SType visitWith(STypeVisitor v) throws ScribException + { + return v.visitRecursion(this); + } + + @Override + public SType visitWithNoEx(STypeVisitorNoEx v) + { + return v.visitRecursion(this); + } + + + @Override + public Set getRoles() + { + return this.body.getRoles(); + } + + @Override + public Set> getMessageIds() + { + return this.body.getMessageIds(); + } + + @Override + public Set getRecVars() + { + return this.body.getRecVars(); + } + + + @Override + public SType unfoldAllOnce(STypeUnfolder u) + { + if (!u.hasRec(this.recvar)) // N.B. doesn't work if recvars shadowed + { + u.pushRec(this.recvar, this.body); + SType unf = this.body.unfoldAllOnce(u); + u.popRec(this.recvar); + // Needed for, e.g., repeat do's in separate choice cases -- cf. stack.pop in GDo::getInlined, must pop sig there for Seqs + return unf; + } + return this; + } + + @Override + public List> getProtoDependencies() + { + return this.body.getProtoDependencies(); + } + + @Override + public List> getNonProtoDependencies() + { + return this.body.getNonProtoDependencies(); + } + + @Override + public Recursion substitute(Substitutions subs) + { + return reconstruct(getSource(), this.recvar, this.body.substitute(subs)); + } + + @Override + public SType pruneRecs() + { + // Assumes no shadowing (e.g., use after SType#getInlined recvar disamb) + Set rvs = this.body.gather(new RecVarCollector()::visit) + .collect(Collectors.toSet()); + return rvs.contains(this.recvar) + ? this + : this.body; // i.e., return a Seq, to be "inlined" by Seq.pruneRecs -- N.B. must handle empty Seq case + } + */ +} diff --git a/scribble-core/src/main/java/org/scribble/core/type/session/SType.java b/scribble-core/src/main/java/org/scribble/core/type/session/SType.java new file mode 100644 index 000000000..54a29ef0d --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/session/SType.java @@ -0,0 +1,81 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.session; + +import java.util.function.Function; +import java.util.stream.Stream; + +import org.scribble.core.lang.SNode; +import org.scribble.core.type.kind.ProtoKind; +import org.scribble.core.visit.STypeAgg; +import org.scribble.core.visit.STypeAggNoThrow; +import org.scribble.util.ScribException; + + +// B used (needed?) to factor up several methods from G/L compounds to bases, e.g., getInlined and unfoldAllOnce +// Generic param works to "specialise" G/L subclasses (and works with immutable pattern) -- cf. not supported by contravariant method parameter subtyping for getters/setters +// N.B. Taking G/LSeq as the B param "limits" the "cast-freeness" of this hierarchy at this point -- i.e., potential G/LSeq subclasses would be beyond that point +// However, the framework is mainly intended to be extended "horizontally" w.r.t. node types (additional types), and "vertically" (subclasses) for behaviour only via Visitors +// In case of "vertical" extension of node types (e.g., additional node fields), still consider that extension of Seq is less often necessary +public interface SType> + extends SNode +{ + // N.B. visitWith should be considered a "top-level" entry point only, i.e., do not assume visitWith is called (or not) again during the recursive traversal + // (visitWith may be called enroute to each visitNode, except for Seq, which is "entered directly" via visitSeq due to its generic typing) + // (However, visitWith is used by Seq to visit its elems -- main point of visitWith is to be agnostic to node type) + T visitWith(STypeAgg v) throws ScribException; + T visitWithNoThrow(STypeAggNoThrow v); + + // Pass in an STypeGatherer::visit, e.g., n.(new RoleGatherer()::visit) + Stream gather(Function, Stream> f); + + // subclass equals should call this by: them.canEquals(this) + boolean canEquals(Object o); + + + + + + + + + + + + + + + + + /*Set getRoles(); + Set> getMessageIds(); + Set getRecVars(); // Gets Continue RecVars (not Recursion) + + // CHECKME: OK to (re-)use GTypeTranslator for inlining? + SType getInlined(STypeInliner i); + + // Unsupported for Do + // CHECKME: repeat recvar names OK? including non-shadowing (e.g., choice cases) + SType unfoldAllOnce(STypeUnfolder u); + + // Resulting Lists should not contain duplicates (i.e., Choice/Seq use distinct) + // Result does not necessarily contain root proto (protodecl is not an SType), but may do so via dependencies + List> getProtoDependencies(); + List> getNonProtoDependencies(); // N.B. delegation payloads currently here, not getProtoDependencies (CHECKME: refactor?) + + SType substitute(Substitutions subs); + + SType pruneRecs(); // Assumes no shadowing (e.g., use after inlining recvar disamb) + */ +} diff --git a/scribble-core/src/main/java/org/scribble/core/type/session/STypeBase.java b/scribble-core/src/main/java/org/scribble/core/type/session/STypeBase.java new file mode 100644 index 000000000..9e2da1ef1 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/session/STypeBase.java @@ -0,0 +1,70 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.session; + +import org.antlr.runtime.tree.CommonTree; +import org.scribble.core.type.kind.ProtoKind; + +// SessTypeBase is to SessType as ScribNodeBase is to ScribNode +public abstract class STypeBase> + implements SType +{ + private final CommonTree source; // Currently null for "generated" terms (cf. hasSource) + + public STypeBase(CommonTree source) + { + /*CommonTree clone = (source == null) + ? null + : CommonTree.clone(); // clone not visibile*/ + // CHECKME: ScribNodes are technically mutable -- though should be treated immutable (defensive copies) post disamb, i.e., in core passes + this.source = source; + } + + @Override + public boolean hasSource() + { + return this.source != null; + } + + // Pre: hasSource + @Override + public CommonTree getSource() + { + return this.source; + } + + // Does *not* include this.source -- equals/hashCode is for "surface-level" syntactic equality of SessType only + @Override + public int hashCode() + { + int hash = 1871; + hash = 31 * hash + super.hashCode(); + return hash; + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof STypeBase)) + { + return false; + } + STypeBase them = (STypeBase) o; + return them.canEquals(this); + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/type/session/STypeFactory.java b/scribble-core/src/main/java/org/scribble/core/type/session/STypeFactory.java new file mode 100644 index 000000000..c1d88c90d --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/session/STypeFactory.java @@ -0,0 +1,66 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.session; + +import java.util.Arrays; + +import org.scribble.core.type.name.GProtoName; +import org.scribble.core.type.name.ModuleName; +import org.scribble.core.type.name.PackageName; +import org.scribble.core.type.session.global.GTypeFactory; +import org.scribble.core.type.session.local.LTypeFactory; + +public class STypeFactory +{ + public final GTypeFactory global; + public final LTypeFactory local; + + public STypeFactory(GTypeFactory global, LTypeFactory local) + { + this.global = global; + this.local = local; + } + + // N.B. targetted by generated Session API + // From fullname + public static GProtoName parseGlobalProtocolName(String name) + { + String[] elems = name.split("\\."); + if (elems.length < 2) + { + throw new RuntimeException("Bad protocol full name: " + name); + } + String membname = elems[elems.length - 1]; + ModuleName modname = new ModuleName(elems[elems.length - 2]); + if (elems.length > 2) + { + PackageName packname = new PackageName(Arrays.copyOfRange(elems, 0, elems.length - 2)); + modname = new ModuleName(packname, modname); + } + GProtoName gpn = new GProtoName(membname); + return new GProtoName(modname, gpn); + } + + + + + + + + /*public static ModuleName parseModuleName(String name) + { + String[] elems = name.split("\\."); + return new ModuleName(elems); + }*/ +} diff --git a/scribble-core/src/main/java/org/scribble/core/type/session/Seq.java b/scribble-core/src/main/java/org/scribble/core/type/session/Seq.java new file mode 100644 index 000000000..12714f118 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/session/Seq.java @@ -0,0 +1,238 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.session; + +import java.util.Collections; +import java.util.List; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.antlr.runtime.tree.CommonTree; +import org.scribble.core.type.kind.ProtoKind; + +public abstract class Seq> + extends STypeBase +{ + // GType or LType -- could make SType subclasses take themself as another param, but not worth it + public final List> elems; + + public Seq(CommonTree source, List> elems) + { + super(source); + this.elems = Collections.unmodifiableList(elems); + } + + public abstract B reconstruct(CommonTree source, + List> elems); + + @Override + public Stream gather(Function, Stream> f) + { + return this.elems.stream().flatMap(x -> x.gather(f)); + } + + // Re. return type, could make SType subclasses take themself as another param, but not worth it + public abstract List> getElements(); + + public boolean isEmpty() + { + return this.elems.isEmpty(); + } + + @Override + public String toString() + { + return this.elems.stream().map(x -> x.toString()) + .collect(Collectors.joining("\n")); + } + + @Override + public int hashCode() + { + int hash = 1483; + hash = 31 * hash + super.hashCode(); + hash = 31 * hash + this.elems.hashCode(); + return hash; + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof Seq)) + { + return false; + } + Seq them = (Seq) o; + return super.equals(this) // Does canEquals + && this.elems.equals(them.elems); + } + + + + + + + + + + + + + + + /*@Override + public Set getRoles() + { + return this.elems.stream().flatMap(x -> x.getRoles().stream()) + .collect(Collectors.toSet()); + } + + @Override + public Set> getMessageIds() + { + return this.elems.stream().flatMap(x -> x.getMessageIds().stream()) + .collect(Collectors.toSet()); + } + + @Override + public Set getRecVars() + { + return this.elems.stream().flatMap(x -> x.getRecVars().stream()) + .collect(Collectors.toSet()); + } + + @Override + public B getInlined(STypeInliner v) + { + CommonTree source = getSource(); // CHECKME: or empty source? + List> elems = new LinkedList<>(); + for (SType e : this.elems) + { + SType e1 = e.getInlined(v); + if (e1 instanceof Seq) + { + elems.addAll(((Seq) e1).elems); // Inline Seq's returned by Do.getInlined + } + else + { + elems.add(e1); + } + } + return reconstruct(source, elems); + } + + @Override + public B unfoldAllOnce(STypeUnfolder u) + { + CommonTree source = getSource(); + List> elems = new LinkedList<>(); + for (SType e : this.elems) + { + SType e1 = e.unfoldAllOnce(u); + if (e1 instanceof Seq) + { + elems.addAll(((Seq) e1).elems); + } + else + { + elems.add(e1); + } + } + return reconstruct(source, elems); + } + + @Override + public List> getProtoDependencies() + { + return this.elems.stream().flatMap(x -> x.getProtoDependencies().stream()) + .distinct().collect(Collectors.toList()); + } + + @Override + public List> getNonProtoDependencies() + { + return this.elems.stream() + .flatMap(x -> x.getNonProtoDependencies().stream()).distinct() + .collect(Collectors.toList()); + } + + @Override + public B substitute(Substitutions subs) + { + List> elems = this.elems.stream() + .map(x -> x.substitute(subs)).collect(Collectors.toList()); + return reconstruct(getSource(), elems); + } + + @Override + public B pruneRecs() + { + List> elems = new LinkedList<>(); + for (SType e : this.elems) + { + SType e1 = (SType) e.pruneRecs(); + if (e1 instanceof Seq) // cf. Recursion::pruneRecs + { + elems.addAll(((Seq) e1).getElements()); // Handles empty Seq case + } + else + { + elems.add(e1); + } + } + return reconstruct(getSource(), elems); + } + */ + + /*@Override + public T aggregate(STypeAgg v) throws ScribException + { + @SuppressWarnings("unchecked") + B cast = (B) this; + return v.visitSeq(cast); + } + + @Override + public T aggregateNoEx(STypeAggNoEx v) + { + @SuppressWarnings("unchecked") + B cast = (B) this; + return v.visitSeq(cast); + } + + // Override STypeBase.visitWith for B return + // Alternatively: call v.visitSeq directly, bypasses generic cast + @Override + public B visitWith(STypeVisitor v) throws ScribException + { + @SuppressWarnings("unchecked") + B cast = (B) this; // CHECKME: OK as long as G/LSeq specify themselves as B param + return v.visitSeq(cast); + } + + // Override STypeBase.visitWithNoEx for B return + @Override + public B visitWithNoEx(STypeVisitorNoEx v) + { + @SuppressWarnings("unchecked") + B cast = (B) this; + return v.visitSeq(cast); + } + */ +} diff --git a/scribble-core/src/main/java/org/scribble/core/type/session/SigLit.java b/scribble-core/src/main/java/org/scribble/core/type/session/SigLit.java new file mode 100644 index 000000000..4e833089a --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/session/SigLit.java @@ -0,0 +1,79 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.session; + +import org.scribble.core.type.kind.OpKind; +import org.scribble.core.type.kind.SigKind; +import org.scribble.core.type.name.MsgId; +import org.scribble.core.type.name.Op; + +public class SigLit implements Msg +{ + public final Op op; + public final Payload payload; + + public SigLit(Op op, Payload payload) + { + this.op = op; + this.payload = payload; + } + + @Override + public boolean isSigLit() + { + return true; + } + + @Override + public SigKind getKind() + { + return SigKind.KIND; + } + + @Override + public MsgId getId() + { + return this.op; + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof SigLit)) + { + return false; + } + SigLit sig = (SigLit) o; + return this.op.equals(sig.op) && this.payload.equals(sig.payload); + } + + @Override + public int hashCode() + { + int hash = 3187; + hash = 31 * hash + this.op.hashCode(); + hash = 31 * hash + this.payload.hashCode(); + return hash; + } + + @Override + public String toString() + { + return this.op.toString() + this.payload.toString(); + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/type/session/global/GChoice.java b/scribble-core/src/main/java/org/scribble/core/type/session/global/GChoice.java new file mode 100644 index 000000000..4a0849002 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/session/global/GChoice.java @@ -0,0 +1,165 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.session.global; + +import java.util.List; + +import org.antlr.runtime.tree.CommonTree; +import org.scribble.core.type.kind.Global; +import org.scribble.core.type.name.Role; +import org.scribble.core.type.session.Choice; + +public class GChoice extends Choice implements GType +{ + protected GChoice(CommonTree source, Role subj, + List blocks) + { + super(source, subj, blocks); + } + + @Override + public GChoice reconstruct(CommonTree source, Role subj, + List blocks) + //List> blocks) + { + return new GChoice(source, subj, blocks); + } + + @Override + public int hashCode() + { + int hash = 3067; + hash = 31 * hash + super.hashCode(); + return hash; + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof GChoice)) + { + return false; + } + return super.equals(o); + } + + @Override + public boolean canEquals(Object o) + { + return o instanceof GChoice; + } +} + + + + + + + + + + + + + + + + +/* + @Override + public Set checkRoleEnabling(Set enabled) throws ScribException + { + if (!enabled.contains(this.subj)) + { + throw new ScribException("Subject not enabled: " + this.subj); + } + Set subj = Stream.of(this.subj).collect(Collectors.toSet()); + List> blocks = new LinkedList<>(); + for (GSeq block : this.blocks) + { + blocks.add(block.checkRoleEnabling(subj)); + } + Set res = new HashSet<>(enabled); + Set tmp = blocks.stream().flatMap(x -> x.stream()) + .filter(x -> blocks.stream().allMatch(y -> y.contains(x))) + .collect(Collectors.toSet()); + res.addAll(tmp); + return Collections.unmodifiableSet(res); + } + + @Override + public Map checkExtChoiceConsistency(Map enablers) + throws ScribException + { + Map subj = Stream.of(this.subj) + .collect(Collectors.toMap(x -> x, x -> x)); + List> blocks = new LinkedList<>(); + for (GSeq block : this.blocks) + { + blocks.add(block.checkExtChoiceConsistency(subj)); + } + Map res = new HashMap<>(enablers); + Set> all = blocks.stream() + .flatMap(x -> x.entrySet().stream()).collect(Collectors.toSet()); + for (Entry e : all) + { + Role enabled = e.getKey(); + Role enabler = e.getValue(); + if (all.stream().anyMatch( + x -> x.getKey().equals(enabled) && !x.getValue().equals(enabler))) + { + throw new ScribException( + "Inconsistent external choice subjects for " + enabled + ": " + + all.stream().filter(x -> x.getKey().equals(enabled)) + .collect(Collectors.toList())); + } + if (!res.containsKey(enabled)) + { + res.put(enabled, enabler); + } + } + return Collections.unmodifiableMap(res); + } + + @Override + public LType projectInlined(Role self) + { + return projectAux(self, + this.blocks.stream().map(x -> x.projectInlined(self))); + } + + private LType projectAux(Role self, Stream blocks) + { + Role subj = this.subj.equals(self) ? Role.SELF : this.subj; + // CHECKME: "self" also explcitily used for Do, but implicitly for MessageTransfer, inconsistent? + List tmp = blocks + .filter(x -> !x.isEmpty()) + .collect(Collectors.toList()); + if (tmp.isEmpty()) + { + return LSkip.SKIP; // CHECKME: OK, or "empty" choice at subj still important? + } + return new LChoice(null, subj, tmp); + } + + @Override + public LType project(ProjEnv v) + { + return projectAux(v.self, this.blocks.stream().map(x -> x.project(v))); + } +*/ \ No newline at end of file diff --git a/scribble-core/src/main/java/org/scribble/core/type/session/global/GConnect.java b/scribble-core/src/main/java/org/scribble/core/type/session/global/GConnect.java new file mode 100644 index 000000000..eb557751f --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/session/global/GConnect.java @@ -0,0 +1,142 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.session.global; + +import org.antlr.runtime.tree.CommonTree; +import org.scribble.core.type.kind.Global; +import org.scribble.core.type.name.Role; +import org.scribble.core.type.session.ConnectAction; +import org.scribble.core.type.session.Msg; + +public class GConnect extends ConnectAction + implements GType +{ + + protected GConnect(CommonTree source, // DirectedInteraction not ideal (imprecise) + Role src, Msg msg, Role dst) + { + super(source, msg, src, dst); + } + + @Override + public GConnect reconstruct(CommonTree source, Msg msg, Role src, Role dst) + { + return new GConnect(source, src, msg, dst); + } + + @Override + public String toString() + { + return this.msg + " connect " + this.src + " to " + this.dst + ";"; + } + + @Override + public int hashCode() + { + int hash = 10639; + hash = 31 * hash + super.hashCode(); + return hash; + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof GConnect)) + { + return false; + } + return super.equals(o); // Does canEquals + } + + @Override + public boolean canEquals(Object o) + { + return o instanceof GConnect; + } +} + + + + + + + + + + + + + + +/* + @Override + public Set checkRoleEnabling(Set enabled) throws ScribException + { + if (!enabled.contains(this.src)) + { + throw new ScribException("Source role not enabled: " + this.src); + } + if (enabled.contains(this.dst)) + { + return enabled; + } + Set tmp = new HashSet<>(enabled); + tmp.add(this.dst); + return Collections.unmodifiableSet(tmp); + } + + @Override + public Map checkExtChoiceConsistency(Map enablers) + throws ScribException + { + if (enablers.containsKey(this.dst)) + { + return enablers; + } + Map tmp = new HashMap<>(enablers); + tmp.put(this.dst, this.src); + return Collections.unmodifiableMap(tmp); + } + + @Override + public LType projectInlined(Role self) + { + if (this.src.equals(self)) + { + /*if (this.dst.equals(self)) + { + // CHECKME: already checked? + }* / + return new LReq(null, this.msg, this.dst); + } + else if (this.dst.equals(self)) + { + return new LAcc(null, this.src, this.msg); + } + else + { + return LSkip.SKIP; + } + } + + @Override + public LType project(ProjEnv v) + { + return projectInlined(v.self); // No need for "aux", no recursive call + } + */ diff --git a/scribble-core/src/main/java/org/scribble/core/type/session/global/GContinue.java b/scribble-core/src/main/java/org/scribble/core/type/session/global/GContinue.java new file mode 100644 index 000000000..4d2a904e4 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/session/global/GContinue.java @@ -0,0 +1,118 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.session.global; + +import org.antlr.runtime.tree.CommonTree; +import org.scribble.core.type.kind.Global; +import org.scribble.core.type.name.RecVar; +import org.scribble.core.type.session.Continue; + +public class GContinue extends Continue implements GType +{ + protected GContinue(CommonTree source, // Due to inlining, do -> continue + RecVar recvar) + { + super(source, recvar); + } + + @Override + public GContinue reconstruct(CommonTree source, + RecVar recvar) + { + return new GContinue(source, recvar); + } + + @Override + public int hashCode() + { + int hash = 3457; + hash = 31 * hash + super.hashCode(); + return hash; + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof GContinue)) + { + return false; + } + return super.equals(o); + } + + @Override + public boolean canEquals(Object o) + { + return o instanceof GContinue; + } + +} + + + + + + + + + + + + /*@Override + public GRecursion unfoldAllOnce(STypeUnfolder u) + { + return new GRecursion(getSource(), this.recvar, + (GSeq) u.getRec(this.recvar)); + // CHECKME: Continue (not Recursion) as the source of the unfolding ? + } + + @Override + public Set checkRoleEnabling(Set enabled) throws ScribException + { + return enabled; + } + + @Override + public Map checkExtChoiceConsistency(Map enablers) + throws ScribException + { + return enablers; + } + + @Override + public LContinue projectInlined(Role self) + { + return new LContinue(null, this.recvar); + } + + @Override + public LContinue project(ProjEnv v) + { + return projectInlined(v.self); // No need for "aux", no recursive call + } + + */ + + + + + + + + + diff --git a/scribble-core/src/main/java/org/scribble/core/type/session/global/GDisconnect.java b/scribble-core/src/main/java/org/scribble/core/type/session/global/GDisconnect.java new file mode 100644 index 000000000..3d6ef69f9 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/session/global/GDisconnect.java @@ -0,0 +1,136 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.session.global; + +import org.antlr.runtime.tree.CommonTree; +import org.scribble.core.type.kind.Global; +import org.scribble.core.type.name.Role; +import org.scribble.core.type.session.DisconnectAction; + +public class GDisconnect extends DisconnectAction + implements GType +{ + + protected GDisconnect(CommonTree source, + Role left, Role right) + { + super(source, left, right); + } + + @Override + public GDisconnect reconstruct( + CommonTree source, Role left, Role right) + { + return new GDisconnect(source, left, right); + } + + @Override + public String toString() + { + return "disconnect " + this.left + " and " + this.right + ";"; + } + + @Override + public int hashCode() + { + int hash = 8747; + hash = 31 * hash + super.hashCode(); + return hash; + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof GDisconnect)) + { + return false; + } + return super.equals(o); // Does canEquals + } + + @Override + public boolean canEquals(Object o) + { + return o instanceof GDisconnect; + } +} + + + + + + + + + + + + + + + + +/* + @Override + public Set checkRoleEnabling(Set enabled) throws ScribException + { + if (!enabled.contains(this.left)) + { + throw new ScribException("Role not enabled: " + this.left); + } + if (!enabled.contains(this.right)) + { + throw new ScribException("Role not enabled: " + this.right); + } + return enabled; + } + + @Override + public Map checkExtChoiceConsistency(Map enablers) + throws ScribException + { + return enablers; + } + + @Override + public LType projectInlined(Role self) + { + if (this.left.equals(self)) + { + /*if (this.dst.equals(self)) + { + // CHECKME: already checked? + }* / + return new LDisconnect(null, this.right); + } + else if (this.right.equals(self)) + { + return new LDisconnect(null, this.left); + } + else + { + return LSkip.SKIP; + } + } + + @Override + public LType project(ProjEnv v) + { + return projectInlined(v.self); // No need for "aux", no recursive call + } +*/ \ No newline at end of file diff --git a/scribble-core/src/main/java/org/scribble/core/type/session/global/GDo.java b/scribble-core/src/main/java/org/scribble/core/type/session/global/GDo.java new file mode 100644 index 000000000..0b6dbf1a1 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/session/global/GDo.java @@ -0,0 +1,185 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.session.global; + +import java.util.List; + +import org.antlr.runtime.tree.CommonTree; +import org.scribble.core.job.Core; +import org.scribble.core.lang.global.GProtocol; +import org.scribble.core.type.kind.Global; +import org.scribble.core.type.kind.NonRoleParamKind; +import org.scribble.core.type.name.ProtoName; +import org.scribble.core.type.name.Role; +import org.scribble.core.type.session.Arg; +import org.scribble.core.type.session.Do; + +public class GDo extends Do implements GType +{ + protected GDo(CommonTree source, ProtoName proto, + List roles, List> args) + { + super(source, proto, roles, args); + } + + @Override + public GProtocol getTarget(Core core) + { + return core.getContext().getIntermediate(this.proto); // Subproto visiting hardcoded to intermediate (i.e., parsed) + } + + @Override + public GDo reconstruct(CommonTree source, + ProtoName proto, List roles, + List> args) + { + return new GDo(source, proto, roles, args); + } + + @Override + public int hashCode() + { + int hash = 1303; + hash = 31 * hash + super.hashCode(); + return hash; + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof GDo)) + { + return false; + } + return super.equals(o); // Does canEquals + } + + @Override + public boolean canEquals(Object o) + { + return o instanceof GDo; + } + +} + + + + + + + + + + + + + + + + + + + /* + @Override + public GProtoName getProto() + { + return (GProtoName) this.proto; + } + + // CHECKME: factor up to base? + @Override + public GType getInlined(STypeInliner v) + { + GProtocolName fullname = this.proto; + SubprotoSig sig = new SubprotoSig(fullname, this.roles, this.args); + RecVar rv = v.getInlinedRecVar(sig); + if (v.hasSig(sig)) + { + return new GContinue(getSource(), rv); + } + v.pushSig(sig); + GProtocol g = v.job.getContext().getIntermediate(fullname); + Substitutions subs = + new Substitutions(g.roles, this.roles, g.params, this.args); + GSeq inlined = g.def.substitute(subs).getInlined(v); + // i.e. returning a GSeq -- rely on parent GSeq to inline + v.popSig(); + return new GRecursion(null, rv, inlined); + } + + @Override + public Set checkRoleEnabling(Set enabled) throws ScribException + { + throw new RuntimeException("Unsupported for Do: " + this); + } + + @Override + public Map checkExtChoiceConsistency(Map enablers) + throws ScribException + { + throw new RuntimeException("Unsupported for Do: " + this); + } + + @Override + public LType projectInlined(Role self) + { + throw new RuntimeException("Unsupported for Do: " + this); + } + + @Override + public LType project(ProjEnv v) + { + if (!this.roles.contains(v.self)) + { + return LSkip.SKIP; + } + + JobContext jobc = v.job.getContext(); + //GProtocolDecl gpd = jobc.getParsed(this.proto); + GProtocol gpd = jobc.getIntermediate(this.proto); + Role targSelf = gpd.roles.get(this.roles.indexOf(v.self)); + + GProtocol imed = jobc.getIntermediate(this.proto); + if (!imed.roles.contains(targSelf)) // CHECKME: because roles already pruned for intermed decl? + { + return LSkip.SKIP; + } + + LProtocolName fullname = ProjEnv.projectFullProtocolName(this.proto, + targSelf); + Substitutions subs = new Substitutions(imed.roles, this.roles, + Collections.emptyList(), Collections.emptyList()); + List used = jobc.getInlined(this.proto).roles.stream() + .map(x -> subs.subsRole(x)).collect(Collectors.toList()); + List rs = this.roles.stream().filter(x -> used.contains(x)) + .map(x -> x.equals(v.self) ? Role.SELF : x) + // CHECKME: "self" also explcitily used for Choice, but implicitly for MessageTransfer, inconsistent? + .collect(Collectors.toList()); + return new LDo(null, fullname, rs, this.args); // TODO CHECKME: prune args? + } + */ + + + + + + + + + + diff --git a/scribble-core/src/main/java/org/scribble/core/type/session/global/GMessageTransfer.java b/scribble-core/src/main/java/org/scribble/core/type/session/global/GMessageTransfer.java new file mode 100644 index 000000000..d9f3b3d98 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/session/global/GMessageTransfer.java @@ -0,0 +1,143 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.session.global; + +import org.antlr.runtime.tree.CommonTree; +import org.scribble.core.type.kind.Global; +import org.scribble.core.type.name.Role; +import org.scribble.core.type.session.Msg; +import org.scribble.core.type.session.MsgTransfer; + +public class GMessageTransfer extends MsgTransfer + implements GType +{ + + protected GMessageTransfer(CommonTree source, Role src, Msg msg, Role dst) + { + super(source, msg, src, dst); + } + + @Override + public GMessageTransfer reconstruct(CommonTree source, Msg msg, Role src, + Role dst) + { + return new GMessageTransfer(source, src, msg, dst); + } + + @Override + public String toString() + { + return this.msg + " from " + this.src + " to " + this.dst + ";"; + } + + @Override + public int hashCode() + { + int hash = 1481; + hash = 31 * hash + super.hashCode(); + return hash; + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof GMessageTransfer)) + { + return false; + } + return super.equals(o); // Does canEquals + } + + @Override + public boolean canEquals(Object o) + { + return o instanceof GMessageTransfer; + } +} + + + + + + + + + + + + + + + +/* + @Override + public Set checkRoleEnabling(Set enabled) throws ScribException + { + if (!enabled.contains(this.src)) + { + throw new ScribException("Source role not enabled: " + this.src); + } + if (enabled.contains(this.dst)) + { + return enabled; + } + Set tmp = new HashSet<>(enabled); + tmp.add(this.dst); + return Collections.unmodifiableSet(tmp); + } + + @Override + public Map checkExtChoiceConsistency(Map enablers) + throws ScribException + { + if (enablers.containsKey(this.dst)) + { + return enablers; + } + Map tmp = new HashMap<>(enablers); + tmp.put(this.dst, this.src); + return Collections.unmodifiableMap(tmp); + } + + @Override + public LType projectInlined(Role self) + { + if (this.src.equals(self)) + { + /*if (this.dst.equals(self)) + { + // CHECKME: already checked? + }* / + return new LSend(null, this.msg, this.dst); + } + else if (this.dst.equals(self)) + { + return new LRcv(null, this.src, this.msg); + } + else + { + return LSkip.SKIP; + } + } + + @Override + public LType project(ProjEnv v) + { + return projectInlined(v.self); // No need for "aux", no recursive call + } +*/ diff --git a/scribble-core/src/main/java/org/scribble/core/type/session/global/GRecursion.java b/scribble-core/src/main/java/org/scribble/core/type/session/global/GRecursion.java new file mode 100644 index 000000000..52c151bb5 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/session/global/GRecursion.java @@ -0,0 +1,128 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.session.global; + +import org.antlr.runtime.tree.CommonTree; +import org.scribble.core.type.kind.Global; +import org.scribble.core.type.name.RecVar; +import org.scribble.core.type.session.Recursion; + +public class GRecursion extends Recursion implements GType +{ + protected GRecursion(CommonTree source, // Due to inlining, protocoldecl -> rec + RecVar recvar, GSeq body) + { + super(source, recvar, body); + } + + @Override + public GRecursion reconstruct(CommonTree source, RecVar recvar, GSeq block) + { + return new GRecursion(source, recvar, block); + } + + @Override + public int hashCode() + { + int hash = 2309; + hash = 31 * hash + super.hashCode(); + return hash; + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof GRecursion)) + { + return false; + } + return super.equals(o); + } + + @Override + public boolean canEquals(Object o) + { + return o instanceof GRecursion; + } +} + + + + + + + + + + + + + + + + +/* + @Override + public Set checkRoleEnabling(Set enabled) throws ScribException + { + return this.body.checkRoleEnabling(enabled); + } + + @Override + public Map checkExtChoiceConsistency(Map enablers) + throws ScribException + { + return this.body.checkExtChoiceConsistency(enablers); + } + + @Override + public LType projectInlined(Role self) + { + LSeq body = this.body.projectInlined(self); + return projectAux(body); + } + + private LType projectAux(LSeq body) + { + if (body.isEmpty()) // N.B. projection is doing empty-rec pruning + { + return LSkip.SKIP; + } + /*RecVar rv = body.isSingleCont(); // CHECKME: should do more "compressing" of "single continue" (subset) choice cases? or should not do "single continue" checking for choice at all? + if (rv != null) + { + return this.recvar.equals(rv) + ? LSkip.SKIP + : new LContinue(null, rv); // CHECKME: source + }* / + Set rvs = new HashSet<>(); + rvs.add(this.recvar); + if (body.aggregateNoEx(new SingleContinueChecker(rvs))) + { + return LSkip.SKIP; + } + return new LRecursion(null, this.recvar, body); + } + + @Override + public LType project(ProjEnv v) + { + LSeq body = this.body.project(v); + return projectAux(body); + } +*/ \ No newline at end of file diff --git a/scribble-core/src/main/java/org/scribble/core/type/session/global/GSeq.java b/scribble-core/src/main/java/org/scribble/core/type/session/global/GSeq.java new file mode 100644 index 000000000..22aa131fe --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/session/global/GSeq.java @@ -0,0 +1,158 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.session.global; + +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.antlr.runtime.tree.CommonTree; +import org.scribble.core.type.kind.Global; +import org.scribble.core.type.session.SType; +import org.scribble.core.type.session.Seq; +import org.scribble.core.visit.STypeAgg; +import org.scribble.core.visit.STypeAggNoThrow; +import org.scribble.util.ScribException; + +public class GSeq extends Seq implements GType +{ + protected GSeq(CommonTree source, List elems) + { + super(source, elems); + } + + @Override + public GSeq reconstruct(CommonTree source, + List> elems) + { + return new GSeq(source, + castElems(elems.stream()).collect(Collectors.toList())); + } + + protected static Stream castElems( + Stream> elems) + { + return elems.map(x -> (GType) x); + } + + @Override + public T visitWith(STypeAgg v) throws ScribException + { + return v.visitSeq(this); + } + + @Override + public T visitWithNoThrow(STypeAggNoThrow v) + { + return v.visitSeq(this); + } + + @Override + public List getElements() + { + return castElems(this.elems.stream()).collect(Collectors.toList()); + } + + @Override + public int hashCode() + { + int hash = 29; + hash = 31 * hash + super.hashCode(); + return hash; + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof GSeq)) + { + return false; + } + return super.equals(o); // Does canEquals + } + + @Override + public boolean canEquals(Object o) + { + return o instanceof GSeq; + } +} + + + + + + + + + + + + + + + + + + + +/* @Override + public Set checkRoleEnabling(Set enabled) throws ScribException + { + for (GType elem : getElements()) + { + enabled = elem.checkRoleEnabling(enabled); + } + return enabled; + } + + @Override + public Map checkExtChoiceConsistency(Map enablers) + throws ScribException + { + for (GType elem : getElements()) + { + enablers = elem.checkExtChoiceConsistency(enablers); + } + return enablers; + + @Override + public LSeq projectInlined(Role self) + { + return projectAux(this.elems.stream() + .map(x -> ((GType) x).projectInlined(self))); + } + + private LSeq projectAux(Stream elems) + { + List tmp = elems.filter(x -> !x.equals(LSkip.SKIP)) + .collect(Collectors.toList()); + return new LSeq(null, tmp); + // Empty seqs converted to LSkip by GChoice/Recursion projection + // And a WF top-level protocol cannot produce empty LSeq + // So a projection never contains an empty LSeq -- i.e., "empty choice/rec" pruning unnecessary + } + + @Override + public LSeq project(ProjEnv v) + { + return projectAux(this.elems.stream() + .map(x -> ((GType) x).project(v))); + } + } +*/ \ No newline at end of file diff --git a/scribble-core/src/main/java/org/scribble/core/type/session/global/GType.java b/scribble-core/src/main/java/org/scribble/core/type/session/global/GType.java new file mode 100644 index 000000000..25d1cbef2 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/session/global/GType.java @@ -0,0 +1,75 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.session.global; + +import org.scribble.core.lang.global.GNode; +import org.scribble.core.type.kind.Global; +import org.scribble.core.type.session.SType; + +public interface GType extends SType, GNode +{ + +} + + + + + + + + + + + + + + + + + + /*// Pre: use on inlined or later (unsupported for Do, also Protocol) + // enabled treated immutably + // Returns enabled post visiting + // Cf. SType visitors, here we only throw ScribbleException or return nothing, so can use return this way + Set checkRoleEnabling(Set enabled) throws ScribException; + + // Pre: use on inlined or later (unsupported for Do, also Protocol) + // Pre: checkRoleEnabling + // enablers: enabled -> enabler -- treated immutably + // Returns enablers post visiting + Map checkExtChoiceConsistency(Map enablers) + throws ScribException; + + // Pre: conns is reflexive + // Also does correlation warnings + //Map checkConnections(Map conns) throws ScribbleException; + // Check on model instead: could possibly do syntactically on once-unfolding, but still need separate checks for dup-conn, unconnected and bad-dconn (may vs. must) + */ + + /*@Override + GType substitute(Substitutions subs);*/ // Otherwise causes return type inconsistency with base abstract classes + + /*// GType returns cause "conflicts" in implementing subclasses -- SType would need itself as another generic param, but not worth it + @Override + GType getInlined(STypeInliner i);//, Deque stack); + + @Override + SType unfoldAllOnce(STypeUnfolder u); // Not GType return, o/w need to override again in GDo + + LType + projectInlined(Role self); // Use on inlined (i.e., Do inlined, roles pruned) + + LType project(ProjEnv v); // Use on parsed (intermed) + */ + diff --git a/scribble-core/src/main/java/org/scribble/core/type/session/global/GTypeFactory.java b/scribble-core/src/main/java/org/scribble/core/type/session/global/GTypeFactory.java new file mode 100644 index 000000000..9065e58b1 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/session/global/GTypeFactory.java @@ -0,0 +1,48 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.session.global; + +import java.util.List; + +import org.antlr.runtime.tree.CommonTree; +import org.scribble.core.type.kind.Global; +import org.scribble.core.type.kind.NonRoleParamKind; +import org.scribble.core.type.name.ProtoName; +import org.scribble.core.type.name.RecVar; +import org.scribble.core.type.name.Role; +import org.scribble.core.type.session.Arg; +import org.scribble.core.type.session.Msg; + +public interface GTypeFactory +{ + + GChoice GChoice(CommonTree source, Role subj, List blocks); + + GConnect GConnect(CommonTree source, Role src, Msg msg, Role dst); + + GContinue GContinue(CommonTree source, RecVar recvar); + + GDisconnect GDisconnect(CommonTree source, Role left, Role right); + + GDo GDo(CommonTree source, ProtoName proto, List roles, + List> args); + + GMessageTransfer GMessageTransfer(CommonTree source, Role src, Msg msg, + Role dst); + + GRecursion GRecursion(CommonTree source, RecVar recvar, GSeq body); + + GSeq GSeq(CommonTree source, List elems); + +} diff --git a/scribble-core/src/main/java/org/scribble/core/type/session/global/GTypeFactoryImpl.java b/scribble-core/src/main/java/org/scribble/core/type/session/global/GTypeFactoryImpl.java new file mode 100644 index 000000000..de4d309d5 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/session/global/GTypeFactoryImpl.java @@ -0,0 +1,79 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.session.global; + +import java.util.List; + +import org.antlr.runtime.tree.CommonTree; +import org.scribble.core.type.kind.Global; +import org.scribble.core.type.kind.NonRoleParamKind; +import org.scribble.core.type.name.ProtoName; +import org.scribble.core.type.name.RecVar; +import org.scribble.core.type.name.Role; +import org.scribble.core.type.session.Arg; +import org.scribble.core.type.session.Msg; + +public class GTypeFactoryImpl implements GTypeFactory +{ + + @Override + public GChoice GChoice(CommonTree source, Role subj, List blocks) + { + return new GChoice(source, subj, blocks); + } + + @Override + public GConnect GConnect(CommonTree source, Role src, Msg msg, Role dst) + { + return new GConnect(source, src, msg, dst); + } + + @Override + public GContinue GContinue(CommonTree source, RecVar recvar) + { + return new GContinue(source, recvar); + } + + @Override + public GDisconnect GDisconnect(CommonTree source, Role left, Role right) + { + return new GDisconnect(source, left, right); + } + + @Override + public GDo GDo(CommonTree source, ProtoName proto, List roles, + List> args) + { + return new GDo(source, proto, roles, args); + } + + @Override + public GMessageTransfer GMessageTransfer(CommonTree source, Role src, Msg msg, + Role dst) + { + return new GMessageTransfer(source, src, msg, dst); + } + + @Override + public GRecursion GRecursion(CommonTree source, RecVar recvar, GSeq body) + { + return new GRecursion(source, recvar, body); + } + + @Override + public GSeq GSeq(CommonTree source, List elems) + { + return new GSeq(source, elems); + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/type/session/local/LAcc.java b/scribble-core/src/main/java/org/scribble/core/type/session/local/LAcc.java new file mode 100644 index 000000000..e333348af --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/session/local/LAcc.java @@ -0,0 +1,112 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.session.local; + +import org.antlr.runtime.tree.CommonTree; +import org.scribble.core.type.kind.Local; +import org.scribble.core.type.name.Role; +import org.scribble.core.type.session.ConnectAction; +import org.scribble.core.type.session.Msg; + +// CHECKME: factor out LConnect? +public class LAcc extends ConnectAction implements LType +{ + + // this.dst == Role.SELF + protected LAcc(CommonTree source, + Role src, Msg msg) + { + super(source, msg, src, Role.SELF); + } + + // FIXME: unnecessary dst + @Override + public LAcc reconstruct( + CommonTree source, Msg msg, Role src, + Role dst) + { + return new LAcc(source, src, msg); + } + + @Override + public String toString() + { + return this.msg + " accept " + this.src + ";"; + } + + @Override + public int hashCode() + { + int hash = 10601; + hash = 31 * hash + super.hashCode(); + return hash; + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof LAcc)) + { + return false; + } + return super.equals(o); // Does canEquals + } + + @Override + public boolean canEquals(Object o) + { + return o instanceof LAcc; + } + +} + + + + + + + + + + + +/* + @Override + public boolean isSingleConts(Set rvs) + { + return false; + } + + @Override + public ReachabilityEnv checkReachability(ReachabilityEnv env) + throws ScribException + { + return env; + } + + @Override + public void buildGraph(EGraphBuilderUtil2 b) + { + Role peer = this.src; + MessageId mid = this.msg.getId(); + Payload payload = this.msg.isMessageSig() // CHECKME: generalise? (e.g., hasPayload) + ? ((MessageSig) msg).payload + : Payload.EMPTY_PAYLOAD; + b.addEdge(b.getEntry(), b.ef.newEAccept(peer, mid, payload), b.getExit()); + } +*/ \ No newline at end of file diff --git a/scribble-core/src/main/java/org/scribble/core/type/session/local/LChoice.java b/scribble-core/src/main/java/org/scribble/core/type/session/local/LChoice.java new file mode 100644 index 000000000..88bf055db --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/session/local/LChoice.java @@ -0,0 +1,183 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.session.local; + +import java.util.List; + +import org.antlr.runtime.tree.CommonTree; +import org.scribble.core.type.kind.Local; +import org.scribble.core.type.name.Role; +import org.scribble.core.type.session.Choice; + +public class LChoice extends Choice implements LType +{ + protected LChoice(CommonTree source, Role subj, + List blocks) + { + super(source, subj, blocks); + } + + @Override + public LChoice reconstruct(CommonTree source, Role subj, + List blocks) + { + return new LChoice(source, subj, blocks); + } + + /*@Override + public List getBlocks() + { + return this.blocks; + }*/ + + @Override + public int hashCode() + { + int hash = 3067; + hash = 31 * hash + super.hashCode(); + return hash; + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof LChoice)) + { + return false; + } + return super.equals(o); + } + + @Override + public boolean canEquals(Object o) + { + return o instanceof LChoice; + } +} + + + + + + + + + + + + + + + + + +/* + + @Override + public boolean isSingleConts(Set rvs) + { + return this.blocks.stream().allMatch(x -> x.isSingleConts(rvs)); + } + + @Override + public ReachabilityEnv checkReachability(ReachabilityEnv env) + throws ScribException + { + List blocks = new LinkedList<>(); + for (LSeq block : this.blocks) + { + blocks.add(block.checkReachability(env)); + } + boolean postcont = blocks.stream().allMatch(x -> x.postcont); // i.e., no exits + Set recvars = blocks.stream().flatMap(x -> x.recvars.stream()) + .collect(Collectors.toSet()); + return new ReachabilityEnv(postcont, recvars); + } + + @Override + public void buildGraph(EGraphBuilderUtil2 b) + { + b.enterChoice(); + for (LSeq block : this.blocks) + { + List elems = block.getElements(); + LType first = elems.get(0); + if (first instanceof LRecursion) // CHECKME: do this here? refactor into builderutil? + { + //EGraphBuilderUtil2 b1 = new EGraphBuilderUtil2(b); + // "Inherits" b.recvars, for continue edge building (to "outer" recs) + //EGraph nested; + EState entry = b.getEntry(); + EState exit = b.getExit(); + + EState nestedEntry = b.newState(Collections.emptySet()); + b.setEntry(nestedEntry); + if (elems.size() == 1) + { + /*b1.setExit(b.getExit()); + first.buildGraph(b1); + nested = b1.finalise();* / + first.buildGraph(b); + } + else + { + /*first.buildGraph(b1); + nested = b1.finalise();* / + // Reuse existing b, to directly add continue-edges back to the "outer" graph + EState nestedExit = b.newState(Collections.emptySet()); + b.setExit(nestedExit); + first.buildGraph(b); + + b.setEntry(nestedExit); // Must be non null + b.setExit(exit); + LSeq tail = new LSeq(null, elems.subList(1, elems.size())); + tail.buildGraph(b); + } + //EState init = nested.init; + EState init = nestedEntry; + ////for (EAction a : first.getEnabling()) + for (EAction a : (Iterable) + init.getAllActions().stream().distinct()::iterator) + // Enabling actions + { + for (EState s : init.getSuccessors(a)) + { + b.addEdge(entry, a, s); + } + } + + b.setEntry(entry); + b.setExit(exit); + } + else if (first instanceof LContinue) + { + // Cannot treat choice-unguarded-continue in "a single pass" because may not have built all recursion enacting edges yet + // (Single-pass building would be sensitive to order of choice block visiting) + LContinue cont = (LContinue) first; // First and only element + b.addContinueEdge(b.getEntry(), cont.recvar); + } + else + { + b.pushChoiceBlock(); // CHECKME: still needed? LContinue doesn't check isUnguardedInChoice any more + block.buildGraph(b); + b.popChoiceBlock(); + } + } + b.leaveChoice(); + } + */ diff --git a/scribble-core/src/main/java/org/scribble/core/type/session/local/LContinue.java b/scribble-core/src/main/java/org/scribble/core/type/session/local/LContinue.java new file mode 100644 index 000000000..55bf25282 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/session/local/LContinue.java @@ -0,0 +1,131 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.session.local; + +import org.antlr.runtime.tree.CommonTree; +import org.scribble.core.type.kind.Local; +import org.scribble.core.type.name.RecVar; +import org.scribble.core.type.session.Continue; + +public class LContinue extends Continue implements LType +{ + // N.B. source changes from do to continue after inlining + protected LContinue(CommonTree source, RecVar recvar) + { + super(source, recvar); + } + + @Override + public LContinue reconstruct(CommonTree source, + RecVar recvar) + { + return new LContinue(source, recvar); + } + + @Override + public int hashCode() + { + int hash = 3457; + hash = 31 * hash + super.hashCode(); + return hash; + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof LContinue)) + { + return false; + } + return super.equals(o); + } + + @Override + public boolean canEquals(Object o) + { + return o instanceof LContinue; + } + + + + + + + + + + + + + + /*@Override + public LRecursion unfoldAllOnce(STypeUnfolder u) + { + return new LRecursion(getSource(), this.recvar, // CHECKME: Continue (not Recursion) as the source of the unfolding + (LSeq) u.getRec(this.recvar)); + } + + @Override + public boolean isSingleConts(Set rvs) + { + return rvs.contains(this.recvar); + } + + @Override + public ReachabilityEnv checkReachability(ReachabilityEnv env) + throws ScribException + { + Set tmp = new HashSet<>(env.recvars); + tmp.add(this.recvar); + return new ReachabilityEnv(true, tmp); + } + + @Override + public void buildGraph(EGraphBuilderUtil2 b) + { + // CHECKME: identical edges, i.e. same pred/prev/succ (e.g. rec X { choice at A { A->B:1 } or { A->B:1 } continue X; }) + // Choice-guarded continue -- choice-unguarded continue detected and handled in LChoice + EState curr = b.getEntry(); + for (EState pred : b.getAllPredecessors(curr)) // Does getAllSuccessors + { + for (EAction a : new LinkedList<>(pred.getAllActions())) + { + // Following is because pred.getSuccessor doesn't support non-det edges + // FIXME: refactor actions/successor Lists in MState to list of edges? + for (EState succ : pred.getSuccessors(a)) + { + if (succ.equals(curr)) + { + try + { + b.removeEdge(pred, a, curr); //b.removeEdgeFromPredecessor(pred, prev); + //b.addEdge(pred, a, entry); //b.addRecursionEdge(pred, prev, b.getRecursionEntry(this.recvar)); + b.addRecursionEdge(pred, a, this.recvar); + } + catch (ScribException e) // CHECKME: necessary for removeEdge to have throws? + { + throw new RuntimeException(e); + } + } + } + } + } + } + */ +} + diff --git a/scribble-core/src/main/java/org/scribble/core/type/session/local/LDisconnect.java b/scribble-core/src/main/java/org/scribble/core/type/session/local/LDisconnect.java new file mode 100644 index 000000000..9f7a75eb4 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/session/local/LDisconnect.java @@ -0,0 +1,118 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.session.local; + +import org.antlr.runtime.tree.CommonTree; +import org.scribble.core.type.kind.Local; +import org.scribble.core.type.name.Role; +import org.scribble.core.type.session.DisconnectAction; + +public class LDisconnect extends DisconnectAction + implements LType +{ + + // this.src == Role.SELF + protected LDisconnect(CommonTree source, + Role peer) + { + super(source, Role.SELF, peer); + } + + public Role getSelf() + { + return this.left; + } + + public Role getPeer() + { + return this.right; + } + + // CHECKME: remove unnecessary self ? + @Override + public LDisconnect reconstruct( + CommonTree source, Role self, Role peer) + { + return new LDisconnect(source, peer); + } + + @Override + public String toString() + { + return "disconnect " + getPeer() + ";"; + } + + @Override + public int hashCode() + { + int hash = 8753; + hash = 31 * hash + super.hashCode(); + return hash; + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof LDisconnect)) + { + return false; + } + return super.equals(o); // Does canEquals + } + + @Override + public boolean canEquals(Object o) + { + return o instanceof LDisconnect; + } +} + + + + + + + + + + + + +/* + + @Override + public boolean isSingleConts(Set rvs) + { + return false; + } + + @Override + public ReachabilityEnv checkReachability(ReachabilityEnv env) + throws ScribException + { + return env; + } + + @Override + public void buildGraph(EGraphBuilderUtil2 b) + { + Role peer = getPeer(); + // TODO: add toAction method to base Interaction + b.addEdge(b.getEntry(), b.ef.newEDisconnect(peer), b.getExit()); + } + */ diff --git a/scribble-core/src/main/java/org/scribble/core/type/session/local/LDo.java b/scribble-core/src/main/java/org/scribble/core/type/session/local/LDo.java new file mode 100644 index 000000000..5a2e61782 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/session/local/LDo.java @@ -0,0 +1,137 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.session.local; + +import java.util.List; + +import org.antlr.runtime.tree.CommonTree; +import org.scribble.core.job.Core; +import org.scribble.core.lang.local.LProtocol; +import org.scribble.core.type.kind.Local; +import org.scribble.core.type.kind.NonRoleParamKind; +import org.scribble.core.type.name.ProtoName; +import org.scribble.core.type.name.Role; +import org.scribble.core.type.session.Arg; +import org.scribble.core.type.session.Do; + +public class LDo extends Do implements LType +{ + protected LDo(CommonTree source, ProtoName proto, + List roles, List> args) + { + super(source, proto, roles, args); + } + + @Override + public LProtocol getTarget(Core core) + { + return core.getContext().getProjection(this.proto); // CHECKME: hardcoded to projections -- factor out "getLocal" (parsed or projected) + } + + @Override + public LDo reconstruct(CommonTree source, + ProtoName proto, List roles, + List> args) + { + return new LDo(source, proto, roles, args); + } + + @Override + public int hashCode() + { + int hash = 1303; + hash = 31 * hash + super.hashCode(); + return hash; + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof LDo)) + { + return false; + } + return super.equals(o); // Does canEquals + } + + @Override + public boolean canEquals(Object o) + { + return o instanceof LDo; + } + + + + + + + + + + + + /* + @Override + public LProtoName getProto() + { + return (LProtoName) this.proto; + } + + // CHECKME: factor up to base? + @Override + public LType getInlined(STypeInliner v) + { + LProtocolName fullname = this.proto; + SubprotoSig sig = new SubprotoSig(fullname, this.roles, this.args); + RecVar rv = v.getInlinedRecVar(sig); + if (v.hasSig(sig)) + { + return new LContinue(getSource(), rv); + } + v.pushSig(sig); + LProtocol p = v.job.getContext().getProjection(fullname); // This line differs from GDo version + Substitutions subs = + new Substitutions(p.roles, this.roles, p.params, this.args); + LSeq inlined = p.def.substitute(subs).getInlined(v);//, stack); + // i.e. returning a Seq -- rely on parent Seq to inline + v.popSig(); + return new LRecursion(null, rv, inlined); + } + + @Override + public boolean isSingleConts(Set rvs) + { + throw new RuntimeException("Unsupported for LDo: " + this); + } + + @Override + public ReachabilityEnv checkReachability(ReachabilityEnv env) + throws ScribException + { + throw new RuntimeException("Unsupported for LDo: " + this); + } + + @Override + public void buildGraph(EGraphBuilderUtil2 b) + { + throw new RuntimeException("Unsupported for LDo: " + this); + } + */ +} + + diff --git a/scribble-core/src/main/java/org/scribble/core/type/session/local/LRecursion.java b/scribble-core/src/main/java/org/scribble/core/type/session/local/LRecursion.java new file mode 100644 index 000000000..d0894788e --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/session/local/LRecursion.java @@ -0,0 +1,112 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.session.local; + +import org.antlr.runtime.tree.CommonTree; +import org.scribble.core.type.kind.Local; +import org.scribble.core.type.name.RecVar; +import org.scribble.core.type.session.Recursion; + +public class LRecursion extends Recursion implements LType +{ + protected LRecursion(//org.scribble.ast.Recursion source, + CommonTree source, // Due to inlining, protocoldecl -> rec + RecVar recvar, LSeq body) + { + super(source, recvar, body); + } + + @Override + public LRecursion reconstruct(CommonTree source, + RecVar recvar, LSeq block) + { + return new LRecursion(source, recvar, block); + } + + @Override + public int hashCode() + { + int hash = 2309; + hash = 31 * hash + super.hashCode(); + return hash; + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof LRecursion)) + { + return false; + } + return super.equals(o); + } + + @Override + public boolean canEquals(Object o) + { + return o instanceof LRecursion; + } +} + + + + + + + + + + + + + + + + +/* + @Override + public boolean isSingleConts(Set rvs) + { + Set tmp = new HashSet<>(rvs); + tmp.add(this.recvar); + return this.body.isSingleConts(tmp); + } + + @Override + public ReachabilityEnv checkReachability(ReachabilityEnv env) + throws ScribException + { + env = this.body.checkReachability(env); + if (env.recvars.contains(this.recvar)) + { + Set tmp = new HashSet<>(env.recvars); + tmp.remove(this.recvar); + env = new ReachabilityEnv(env.postcont, tmp); + } + return env; + } + + @Override + public void buildGraph(EGraphBuilderUtil2 b) + { + b.addEntryLabel(this.recvar); + b.pushRecursionEntry(this.recvar, b.getEntry()); + this.body.buildGraph(b); + b.popRecursionEntry(this.recvar); + } + */ diff --git a/scribble-core/src/main/java/org/scribble/core/type/session/local/LRecv.java b/scribble-core/src/main/java/org/scribble/core/type/session/local/LRecv.java new file mode 100644 index 000000000..9b9587350 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/session/local/LRecv.java @@ -0,0 +1,119 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.session.local; + +import org.antlr.runtime.tree.CommonTree; +import org.scribble.core.type.kind.Local; +import org.scribble.core.type.name.Role; +import org.scribble.core.type.session.Msg; +import org.scribble.core.type.session.MsgTransfer; + +public class LRecv extends MsgTransfer + implements LType +{ + + // this.dst == Role.SELF + protected LRecv(CommonTree source, + Role src, Msg msg) + { + super(source, msg, src, Role.SELF); + } + + // FIXME: unnecessary dst + @Override + public LRecv reconstruct( + CommonTree source, Msg msg, Role src, + Role dst) + { + return new LRecv(source, src, msg); + } + + @Override + public String toString() + { + return this.msg + " from " + this.src + ";"; + } + + @Override + public int hashCode() + { + int hash = 1481; + hash = 31 * hash + super.hashCode(); + return hash; + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof LRecv)) + { + return false; + } + return super.equals(o); // Does canEquals + } + + @Override + public boolean canEquals(Object o) + { + return o instanceof LRecv; + } + +} + + + + + + + + + + + + + + + + + + +/* + @Override + public boolean isSingleConts(Set rvs) + { + return false; + } + + @Override + public ReachabilityEnv checkReachability(ReachabilityEnv env) + throws ScribException + { + return env; + } + + @Override + public void buildGraph(EGraphBuilderUtil2 b) + { + Role peer = this.src; + MessageId mid = this.msg.getId(); + Payload payload = this.msg.isMessageSig() // CHECKME: generalise? (e.g., hasPayload) + ? ((MessageSig) msg).payload + : Payload.EMPTY_PAYLOAD; + b.addEdge(b.getEntry(), b.ef.newEReceive(peer, mid, payload), b.getExit()); + } + */ diff --git a/scribble-core/src/main/java/org/scribble/core/type/session/local/LReq.java b/scribble-core/src/main/java/org/scribble/core/type/session/local/LReq.java new file mode 100644 index 000000000..9be292488 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/session/local/LReq.java @@ -0,0 +1,121 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.session.local; + +import org.antlr.runtime.tree.CommonTree; +import org.scribble.core.type.kind.Local; +import org.scribble.core.type.name.Role; +import org.scribble.core.type.session.ConnectAction; +import org.scribble.core.type.session.Msg; + +// CHECKME: factor out LConnect? +public class LReq extends ConnectAction implements LType +{ + + // this.src == Role.SELF + protected LReq(CommonTree source, + Msg msg, Role dst) + { + super(source, msg, Role.SELF, dst); + } + + // CHECKME: remove unnecessary src ? + @Override + public LReq reconstruct( + CommonTree source, Msg msg, Role src, + Role dst) + { + return new LReq(source, msg, dst); + } + + @Override + public String toString() + { + return this.msg + " request " + this.dst + ";"; + } + + @Override + public int hashCode() + { + int hash = 10597; + hash = 31 * hash + super.hashCode(); + return hash; + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof LReq)) + { + return false; + } + return super.equals(o); // Does canEquals + } + + @Override + public boolean canEquals(Object o) + { + return o instanceof LReq; + } + +} + + + + + + + + + + + + + + + + + + +/* + + @Override + public boolean isSingleConts(Set rvs) + { + return false; + } + + @Override + public ReachabilityEnv checkReachability(ReachabilityEnv env) + throws ScribException + { + return env; + } + + @Override + public void buildGraph(EGraphBuilderUtil2 b) + { + Role peer = this.dst; + MessageId mid = this.msg.getId(); + Payload payload = this.msg.isMessageSig() // CHECKME: generalise? (e.g., hasPayload) + ? ((MessageSig) msg).payload + : Payload.EMPTY_PAYLOAD; + // TODO: add toAction method to base Interaction + b.addEdge(b.getEntry(), b.ef.newERequest(peer, mid, payload), b.getExit()); + } +*/ \ No newline at end of file diff --git a/scribble-core/src/main/java/org/scribble/core/type/session/local/LSend.java b/scribble-core/src/main/java/org/scribble/core/type/session/local/LSend.java new file mode 100644 index 000000000..fd2646197 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/session/local/LSend.java @@ -0,0 +1,122 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.session.local; + +import org.antlr.runtime.tree.CommonTree; +import org.scribble.core.type.kind.Local; +import org.scribble.core.type.name.Role; +import org.scribble.core.type.session.Msg; +import org.scribble.core.type.session.MsgTransfer; + +public class LSend extends MsgTransfer + implements LType +{ + + // this.src == Role.SELF + protected LSend(CommonTree source, + Msg msg, Role dst) + { + super(source, msg, Role.SELF, dst); + } + + // CHECKME: remove unnecessary src ? + @Override + public LSend reconstruct( + CommonTree source, Msg msg, Role src, + Role dst) + { + return new LSend(source, msg, dst); + } + + @Override + public String toString() + { + return this.msg + " to " + this.dst + ";"; + } + + @Override + public int hashCode() + { + int hash = 1481; + hash = 31 * hash + super.hashCode(); + return hash; + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof LSend)) + { + return false; + } + return super.equals(o); // Does canEquals + } + + @Override + public boolean canEquals(Object o) + { + return o instanceof LSend; + } + +} + + + + + + + + + + + + + + + + + + + + +/* + @Override + public boolean isSingleConts(Set rvs) + { + return false; + } + + @Override + public ReachabilityEnv checkReachability(ReachabilityEnv env) + throws ScribException + { + return env; + } + + @Override + public void buildGraph(EGraphBuilderUtil2 b) + { + Role peer = this.dst; + MessageId mid = this.msg.getId(); + Payload payload = this.msg.isMessageSig() // CHECKME: generalise? (e.g., hasPayload) + ? ((MessageSig) msg).payload + : Payload.EMPTY_PAYLOAD; + // TODO: add toAction method to base Interaction + b.addEdge(b.getEntry(), b.ef.newESend(peer, mid, payload), b.getExit()); + } +*/ \ No newline at end of file diff --git a/scribble-core/src/main/java/org/scribble/core/type/session/local/LSeq.java b/scribble-core/src/main/java/org/scribble/core/type/session/local/LSeq.java new file mode 100644 index 000000000..1fb2eaf99 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/session/local/LSeq.java @@ -0,0 +1,176 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.session.local; + +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.antlr.runtime.tree.CommonTree; +import org.scribble.core.type.kind.Local; +import org.scribble.core.type.session.SType; +import org.scribble.core.type.session.Seq; +import org.scribble.core.visit.STypeAgg; +import org.scribble.core.visit.STypeAggNoThrow; +import org.scribble.util.ScribException; + +public class LSeq extends Seq implements LType +{ + // GInteractionSeq or GBlock better as source? + //protected LSeq(CommonTree source, List> elems) + protected LSeq(CommonTree source, List elems) + { + super(source, elems); + } + + @Override + public LSeq reconstruct(CommonTree source, + List> elems) + { + return new LSeq(source, + castElems(elems.stream()).collect(Collectors.toList())); + } + + protected static Stream castElems( + Stream> elems) + { + return elems.map(x -> (LType) x); + } + + @Override + public T visitWith(STypeAgg v) throws ScribException + { + return v.visitSeq(this); + } + + @Override + public T visitWithNoThrow(STypeAggNoThrow v) + { + return v.visitSeq(this); + } + + @Override + public List getElements() + { + return castElems(this.elems.stream()).collect(Collectors.toList()); + } + + @Override + public int hashCode() + { + int hash = 29; + hash = 31 * hash + super.hashCode(); + return hash; + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof LSeq)) + { + return false; + } + return super.equals(o); // Does canEquals + } + + @Override + public boolean canEquals(Object o) + { + return o instanceof LSeq; + } +} + + + + + + + + + + + + + + + + + + + + + + +/* + @Override + public boolean isSingleConts(Set rvs) + { + return this.elems.size() == 1 + && ((LType) this.elems.get(0)).isSingleConts(rvs); + } + + @Override + public ReachabilityEnv checkReachability(ReachabilityEnv env) + throws ScribException + { + LType prev = null; + LType next = null; + for (Iterator i = getElements().iterator(); i.hasNext(); ) + { + prev = next; + next = i.next(); + if (!env.isSeqable()) + { + throw new ScribException( + "Illegal sequence: " + (prev == null ? "" : prev + "\n") + next); + } + env = next.checkReachability(env); + } + return env; + } + + @Override + public void buildGraph(EGraphBuilderUtil2 b) + { + EState entry = b.getEntry(); + EState exit = b.getExit(); + List elems = getElements(); + if (elems.isEmpty()) + { + throw new RuntimeException("Shouldn't get here: " + this); + } + for (Iterator i = getElements().iterator(); i.hasNext(); ) + { + LType next = i.next(); + if (!i.hasNext()) + { + b.setExit(exit); + next.buildGraph(b); + } + else + { + EState tmp = b.newState(Collections.emptySet()); + b.setExit(tmp); + next.buildGraph(b); + b.setEntry(b.getExit()); + // CHECKME: exit may not be tmp, entry/exit can be modified, e.g. continue + } + } + b.setEntry(entry); + } +*/ \ No newline at end of file diff --git a/scribble-core/src/main/java/org/scribble/core/type/session/local/LSkip.java b/scribble-core/src/main/java/org/scribble/core/type/session/local/LSkip.java new file mode 100644 index 000000000..ef45b05f0 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/session/local/LSkip.java @@ -0,0 +1,174 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.session.local; + +import java.util.function.Function; +import java.util.stream.Stream; + +import org.scribble.core.type.kind.Local; +import org.scribble.core.type.session.SType; +import org.scribble.core.type.session.STypeBase; +import org.scribble.core.visit.STypeAgg; +import org.scribble.core.visit.STypeAggNoThrow; + +// Used only *during* projection -- filtered out by GSeq::projection +// CHECKME: can use empty Seq, and do "seq injection" in visitSeq overrides? (cf. RecPruner) +public class LSkip extends STypeBase implements LType +{ + public static final LSkip SKIP = new LSkip(); + + private LSkip() + { + super(null); + } + + @Override + public T visitWith(STypeAgg v) + { + throw new RuntimeException("Unsupported for Skip: " + this); + } + + @Override + public T visitWithNoThrow(STypeAggNoThrow v) + { + throw new RuntimeException("Unsupported for Skip: " + this); + } + + @Override + public Stream gather(Function, Stream> f) + { + throw new RuntimeException("Unsupported for Skip: " + this); + } + + @Override + public String toString() + { + return "[skip];"; + } + + @Override + public int hashCode() + { + int hash = 2833; + hash = 31 * hash + super.hashCode(); + return hash; + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof LSkip)) + { + return false; + } + return ((LSkip) o).canEquals(this); + } + + @Override + public boolean canEquals(Object o) + { + return o instanceof LSkip; + } + + + + + + + + + + + + + /*@Override + public Set getRoles() + { + throw new RuntimeException("Unsupported for Skip: " + this); + } + + @Override + public Set> getMessageIds() + { + throw new RuntimeException("Unsupported for Skip: " + this); + } + + @Override + public Set getRecVars() + { + throw new RuntimeException("Unsupported for Skip: " + this); + } + + @Override + public LSkip getInlined(STypeInliner i) + { + return this; + } + + @Override + public LType unfoldAllOnce(STypeUnfolder u) + { + throw new RuntimeException("Unsupported for Skip: " + this); + } + + @Override + public List> getProtoDependencies() + { + throw new RuntimeException("Unsupported for Skip: " + this); + } + + @Override + public List> getNonProtoDependencies() + { + throw new RuntimeException("Unsupported for Skip: " + this); + } + + @Override + public LSkip pruneRecs() + { + throw new RuntimeException("Unsupported for Skip: " + this); + } + + @Override + public LSkip substitute(Substitutions subs) + { + return this; + } + + @Override + public boolean isSingleConts(Set rvs) + { + throw new RuntimeException("Unsupported for Skip:\n" + this); + } + + @Override + public ReachabilityEnv checkReachability(ReachabilityEnv env) + throws ScribException + { + throw new RuntimeException("Unsupported for: " + this); + } + + @Override + public void buildGraph(EGraphBuilderUtil2 b) + { + throw new RuntimeException("Unsupported for: " + this); + } + */ +} + + diff --git a/scribble-core/src/main/java/org/scribble/core/type/session/local/LType.java b/scribble-core/src/main/java/org/scribble/core/type/session/local/LType.java new file mode 100644 index 000000000..534a6f4c6 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/session/local/LType.java @@ -0,0 +1,64 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.session.local; + +import org.scribble.core.lang.local.LNode; +import org.scribble.core.type.kind.Local; +import org.scribble.core.type.session.SType; + +public interface LType extends SType, LNode +{ + //Role getSelf(); // CHECKME: useful? maybe only specifically for interactions + + //void buildGraph(EGraphBuilderUtil2 b); +} + + + + + + + + + + + + + + + + + + + + + + /*@Override + LType substitute(Substitutions subs);*/ // Otherwise causes return type inconsistency with base abstract classes + + /*// LType returns cause "conflicts" in implementing subclasses -- SType would need itself as another generic param, but not worth it + @Override + SType getInlined(STypeInliner v); + + @Override + SType unfoldAllOnce(STypeUnfolder u); + + // Return true iff this LType is "equivalent" to a single "continue X", where X is in rvs + boolean isSingleConts(Set rvs); + + // Return: (new) env post visiting + // cf. GType "visitor" methods: same pattern, just env as a bespoke data type wrapper + ReachabilityEnv checkReachability(ReachabilityEnv env) + throws ScribException; + */ diff --git a/scribble-core/src/main/java/org/scribble/core/type/session/local/LTypeFactory.java b/scribble-core/src/main/java/org/scribble/core/type/session/local/LTypeFactory.java new file mode 100644 index 000000000..ced6d8ba2 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/session/local/LTypeFactory.java @@ -0,0 +1,50 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.session.local; + +import java.util.List; + +import org.antlr.runtime.tree.CommonTree; +import org.scribble.core.type.kind.Local; +import org.scribble.core.type.kind.NonRoleParamKind; +import org.scribble.core.type.name.ProtoName; +import org.scribble.core.type.name.RecVar; +import org.scribble.core.type.name.Role; +import org.scribble.core.type.session.Arg; +import org.scribble.core.type.session.Msg; + +public interface LTypeFactory +{ + + LAcc LAcc(CommonTree source, Role src, Msg msg); + + LChoice LChoice(CommonTree source, Role subj, List blocks); + + LContinue LContinue(CommonTree source, RecVar recvar); + + LDisconnect LDisconnect(CommonTree source, Role peer); + + LDo LDo(CommonTree source, ProtoName proto, List roles, + List> args); + + LRecursion LRecursion(CommonTree source, RecVar recvar, LSeq body); + + LRecv LRecv(CommonTree source, Role src, Msg msg); + + LReq LReq(CommonTree source, Msg msg, Role dst); + + LSend LSend(CommonTree source, Msg msg, Role dst); + + LSeq LSeq(CommonTree source, List elems); +} diff --git a/scribble-core/src/main/java/org/scribble/core/type/session/local/LTypeFactoryImpl.java b/scribble-core/src/main/java/org/scribble/core/type/session/local/LTypeFactoryImpl.java new file mode 100644 index 000000000..2f3e244f0 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/type/session/local/LTypeFactoryImpl.java @@ -0,0 +1,91 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.type.session.local; + +import java.util.List; + +import org.antlr.runtime.tree.CommonTree; +import org.scribble.core.type.kind.Local; +import org.scribble.core.type.kind.NonRoleParamKind; +import org.scribble.core.type.name.ProtoName; +import org.scribble.core.type.name.RecVar; +import org.scribble.core.type.name.Role; +import org.scribble.core.type.session.Arg; +import org.scribble.core.type.session.Msg; + +public class LTypeFactoryImpl implements LTypeFactory +{ + + @Override + public LAcc LAcc(CommonTree source, Role src, Msg msg) + { + return new LAcc(source, src, msg); + } + + @Override + public LChoice LChoice(CommonTree source, Role subj, List blocks) + { + return new LChoice(source, subj, blocks); + } + + @Override + public LContinue LContinue(CommonTree source, RecVar recvar) + { + return new LContinue(source, recvar); + } + + @Override + public LDisconnect LDisconnect(CommonTree source, Role peer) + { + return new LDisconnect(source, peer); + } + + @Override + public LDo LDo(CommonTree source, ProtoName proto, List roles, + List> args) + { + return new LDo(source, proto, roles, args); + } + + @Override + public LRecursion LRecursion(CommonTree source, RecVar recvar, LSeq body) + { + return new LRecursion(source, recvar, body); + } + + @Override + public LRecv LRecv(CommonTree source, Role src, Msg msg) + { + return new LRecv(source, src, msg); + } + + @Override + public LReq LReq(CommonTree source, Msg msg, Role dst) + { + return new LReq(source, msg, dst); + } + + @Override + public LSend LSend(CommonTree source, Msg msg, + Role dst) + { + return new LSend(source, msg, dst); + } + + @Override + public LSeq LSeq(CommonTree source, List elems) + { + return new LSeq(source, elems); + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/visit/RecPruner.java b/scribble-core/src/main/java/org/scribble/core/visit/RecPruner.java new file mode 100644 index 000000000..aca2f5352 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/visit/RecPruner.java @@ -0,0 +1,79 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.visit; + +import java.util.LinkedList; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; + +import org.scribble.core.type.kind.ProtoKind; +import org.scribble.core.type.name.RecVar; +import org.scribble.core.type.session.Choice; +import org.scribble.core.type.session.Recursion; +import org.scribble.core.type.session.SType; +import org.scribble.core.type.session.Seq; +import org.scribble.core.visit.gather.RecVarGatherer; + +// Assumes no shadowing, e.g., use after inlining recvar disamb (also used after projection) +public class RecPruner> + extends STypeVisitorNoThrow +{ + protected RecPruner() + { + + } + + @Override + public SType visitChoice(Choice n) + { + List blocks = n.blocks.stream().map(x -> visitSeq(x)) + .filter(x -> !x.isEmpty()).collect(Collectors.toList()); + if (blocks.isEmpty()) + { + return n.blocks.get(0).reconstruct(null, blocks); // N.B. returning a Seq -- handled by visitSeq (similar to LSkip for locals) + } + return n.reconstruct(n.getSource(), n.subj, blocks); + } + + @Override + public SType visitRecursion(Recursion n) + { + // Assumes no shadowing (e.g., use after SType#getInlined recvar disamb) + Set rvs = n.body.gather(new RecVarGatherer()::visit) + .collect(Collectors.toSet()); + return rvs.contains(n.recvar) + ? n.reconstruct(n.getSource(), n.recvar, visitSeq(n.body)) + : n.body; // i.e., return a Seq, to be "inlined" by Seq.pruneRecs -- N.B. must handle empty Seq case + } + + @Override + public B visitSeq(B n) + { + List> elems = new LinkedList<>(); + for (SType e : n.elems) + { + SType e1 = (SType) e.visitWithNoThrow(this); + if (e1 instanceof Seq) // cf. visitRecursion (also cf. LSkip) + { + elems.addAll(((Seq) e1).elems);//getElements()); // Handles empty Seq case + } + else + { + elems.add(e1); + } + } + return n.reconstruct(n.getSource(), elems); + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/visit/STypeAgg.java b/scribble-core/src/main/java/org/scribble/core/visit/STypeAgg.java new file mode 100644 index 000000000..27fe1e1bf --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/visit/STypeAgg.java @@ -0,0 +1,114 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.visit; + +import java.util.LinkedList; +import java.util.List; +import java.util.stream.Stream; + +import org.scribble.core.type.kind.ProtoKind; +import org.scribble.core.type.session.Choice; +import org.scribble.core.type.session.Continue; +import org.scribble.core.type.session.DirectedInteraction; +import org.scribble.core.type.session.DisconnectAction; +import org.scribble.core.type.session.Do; +import org.scribble.core.type.session.Recursion; +import org.scribble.core.type.session.SType; +import org.scribble.core.type.session.Seq; +import org.scribble.util.ScribException; + +public abstract class STypeAgg, T> +{ + // Internal use + // Pre: agg(Stream.of(unit())) = unit() + protected abstract T unit(SType n) throws ScribException; + + // Internal use -- by default, agg is applied to the "compound" cases (choice, recursion, seq) + // Pre: agg(Stream.of(unit())) = unit() + protected abstract T agg(SType n, Stream ts) throws ScribException; // Cf. generic varargs, heap pollution issue + + public T visitChoice(Choice n) throws ScribException + { + List blocks = new LinkedList<>(); + for (B b : n.blocks) + { + //blocks.add(b.visitWith(this)); + blocks.add(visitSeq(b)); + } + return agg(n, blocks.stream()); + } + + public T visitContinue(Continue n) throws ScribException + { + return unit(n); + } + + public T visitDirectedInteraction(DirectedInteraction n) + throws ScribException + { + return unit(n); + } + + public T visitDisconnect(DisconnectAction n) throws ScribException + { + return unit(n); + } + + public T visitDo(Do n) throws ScribException + { + return unit(n); + } + + public T visitRecursion(Recursion n) throws ScribException + { + //return agg(n, Stream.of(n.body.visitWith(this))); + return agg(n, Stream.of(visitSeq(n.body))); + } + + // Param "hardcoded" to B (cf. Seq, or SType return) -- this visitor pattern depends on B for Choice/Recursion/etc reconstruction + public T visitSeq(B n) throws ScribException + { + List elems = new LinkedList<>(); + for (SType e : n.elems) + { + elems.add(e.visitWith(this)); + } + return agg(n, elems.stream()); + } +} + + + + + + + + + + + + + + + + + + + + +/*@FunctionalInterface +interface STypeVisitorFunction, R extends Stream> +{ + R f(SType n, STypeVisitor v); +}*/ diff --git a/scribble-core/src/main/java/org/scribble/core/visit/STypeAggNoThrow.java b/scribble-core/src/main/java/org/scribble/core/visit/STypeAggNoThrow.java new file mode 100644 index 000000000..2b3ab1216 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/visit/STypeAggNoThrow.java @@ -0,0 +1,100 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.visit; + +import java.util.stream.Stream; + +import org.scribble.core.type.kind.ProtoKind; +import org.scribble.core.type.session.Choice; +import org.scribble.core.type.session.Continue; +import org.scribble.core.type.session.DirectedInteraction; +import org.scribble.core.type.session.DisconnectAction; +import org.scribble.core.type.session.Do; +import org.scribble.core.type.session.Recursion; +import org.scribble.core.type.session.SType; +import org.scribble.core.type.session.Seq; + +// Worth it to maintain alongside STypeAgg? -- does touch a lot of places +public abstract class STypeAggNoThrow, T> + //extends STypeAgg // Not worth it, ex/no-ex method variants easily confused +{ + // Internal use + // Pre: agg(Stream.of(unit())) = unit() + protected abstract T unit(SType n); + + // Internal use -- by default, agg is applied to the "compound" cases (choice, recursion, seq) + // Pre: agg(Stream.of(unit())) = unit() + protected abstract T agg(SType n, Stream ts); // Cf. generic varargs, heap pollution issue + + public T visitContinue(Continue n) + { + return unit(n); + } + + public T visitChoice(Choice n) + { + return agg(n, n.blocks.stream().map(x -> visitSeq(x))); + } + + public T visitDirectedInteraction(DirectedInteraction n) + { + return unit(n); + } + + public T visitDisconnect(DisconnectAction n) + { + return unit(n); + } + + public T visitDo(Do n) + { + return unit(n); + } + + public T visitRecursion(Recursion n) + { + return agg(n, Stream.of(visitSeq(n.body))); + } + + // Param "hardcoded" to B (cf. Seq, or SType return) -- this visitor pattern depends on B for Choice/Recursion/etc reconstruction + public T visitSeq(B n) + { + return agg(n, n.elems.stream().map(x -> x.visitWithNoThrow(this))); + } +} + + + + + + + + + + + + + + + + + + + + +/*@FunctionalInterface +interface STypeVisitorFunction, R extends Stream> +{ + R f(SType n, STypeVisitor v); +}*/ diff --git a/scribble-core/src/main/java/org/scribble/core/visit/STypeInliner.java b/scribble-core/src/main/java/org/scribble/core/visit/STypeInliner.java new file mode 100644 index 000000000..fdc034485 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/visit/STypeInliner.java @@ -0,0 +1,183 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.visit; + +import java.util.Deque; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import org.antlr.runtime.tree.CommonTree; +import org.scribble.core.job.Core; +import org.scribble.core.lang.SubprotoSig; +import org.scribble.core.type.kind.ProtoKind; +import org.scribble.core.type.name.RecVar; +import org.scribble.core.type.session.Continue; +import org.scribble.core.type.session.Recursion; +import org.scribble.core.type.session.SType; +import org.scribble.core.type.session.Seq; + +public abstract class STypeInliner> + extends STypeVisitorNoThrow +{ + public final Core core; + + // Basically, "SubprotocolVisitor" -- factor out? + private final Deque stack = new LinkedList<>(); + + // To handle recvar shadowing in nested recs + private Map> recvars = new HashMap<>(); + private Map counter = new HashMap<>(); + + private final Map> recs = new HashMap<>(); + + public STypeInliner(Core core) + { + this.core = core; + } + + @Override + public SType visitContinue(Continue n) + { + RecVar rv = getInlinedRecVar(n.recvar); + return n.reconstruct(n.getSource(), rv); + } + + @Override + public SType visitRecursion(Recursion n) + { + CommonTree source = n.getSource(); // CHECKME: or empty source? + RecVar rv = enterRec(n.recvar); // FIXME: make GTypeInliner, and record recvars to check freshness (e.g., rec X in two choice cases) + //B body = n.body.visitWithNoEx(this); + B body = visitSeq(n.body);//.visitWithNoEx(this); + Recursion res = n.reconstruct(source, rv, body); + exitRec(n.recvar); + return res; + } + + @Override + public B visitSeq(B n) + { + List> elems = new LinkedList<>(); + for (SType e : n.elems) + { + SType e1 = e.visitWithNoThrow(this); + if (e1 instanceof Seq) + { + elems.addAll(((Seq) e1).elems); + } + else + { + elems.add(e1); + } + } + return n.reconstruct(n.getSource(), elems); + } + + protected void pushRec(RecVar rv, Seq body) + { + if (this.recs.containsKey(rv)) + { + throw new RuntimeException("Shouldn't get here: " + rv); + } + this.recs.put(rv, body); + } + + protected boolean hasRec(RecVar rv) + { + return this.recs.containsKey(rv); + } + + protected Seq getRec(RecVar rv) + { + return this.recs.get(rv); + } + + protected void popRec(RecVar rv) + { + this.recs.remove(rv); + } + + public void pushSig(SubprotoSig sig) + { + if (this.stack.contains(sig)) + { + throw new RuntimeException("Shouldn't get here: " + sig); + } + this.stack.push(sig); + } + + protected SubprotoSig peek() + { + return this.stack.peek(); + } + + protected boolean hasSig(SubprotoSig sig) + { + return this.stack.contains(sig); + } + + protected void popSig() + { + this.stack.pop(); + } + + // For Protocol/Do -- sig is for the current innermost proto (but not implicitly peek() for G/LDo convenience) + public RecVar getInlinedRecVar(SubprotoSig sig) + { + String lab = "__" + sig.fullname.toString().replaceAll("\\.", "_") + "__" + + sig.roles.stream().map(x -> x.toString()) + .collect(Collectors.joining("_")) + + "__" + sig.args.stream().map(x -> x.toString()) + .collect(Collectors.joining("_")); + return new RecVar(lab); + } + + protected RecVar enterRec(RecVar rv) + { + String text = getInlinedRecVar(this.stack.peek()) + "__" + rv; + if (this.counter.containsKey(rv)) + { + int i = this.counter.get(rv) + 1; + text += "_" + i; + this.counter.put(rv, i); + } + else + { + this.counter.put(rv, 0); + } + RecVar res = new RecVar(text); + Deque tmp = this.recvars.get(rv); + if (tmp == null) + { + tmp = new LinkedList<>(); + this.recvars.put(rv, tmp); + } + tmp.push(res); + return res; + } + + // For Continue + protected RecVar getInlinedRecVar(RecVar rv) + { + return this.recvars.get(rv).peek(); + } + + protected void exitRec(RecVar rv) + { + this.recvars.get(rv).pop(); + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/visit/STypeUnfolder.java b/scribble-core/src/main/java/org/scribble/core/visit/STypeUnfolder.java new file mode 100644 index 000000000..58ec79901 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/visit/STypeUnfolder.java @@ -0,0 +1,104 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.visit; + +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +import org.scribble.core.job.Core; +import org.scribble.core.type.kind.ProtoKind; +import org.scribble.core.type.name.RecVar; +import org.scribble.core.type.session.Do; +import org.scribble.core.type.session.Recursion; +import org.scribble.core.type.session.SType; +import org.scribble.core.type.session.Seq; + +// Pre: use on inlined -- not supported for Do +public abstract class STypeUnfolder> + extends STypeVisitorNoThrow +{ + public final Core core; + + private final Map> recs = new HashMap<>(); + + public STypeUnfolder(Core core) + { + this.core = core; + } + + @Override + public final SType visitDo(Do n) + { + throw new RuntimeException(this.getClass() + " unsupported for Do: " + n); + } + + @Override + public SType visitRecursion(Recursion n) + { + if (!hasRec(n.recvar)) // N.B. doesn't work if recvars shadowed + { + pushRec(n.recvar, n.body); + SType unf = visitSeq(n.body);//n.body.visitWithNoEx(this); + popRec(n.recvar); + // Needed for, e.g., repeat do's in separate choice cases -- cf. stack.pop in GDo::getInlined, must pop sig there for Seqs + return unf; + } + return n; + } + + @Override + public B visitSeq(B n) + { + List> elems = new LinkedList<>(); + for (SType e : n.elems) + { + SType e1 = e.visitWithNoThrow(this); + if (e1 instanceof Seq) + { + elems.addAll(((Seq) e1).elems); + } + else + { + elems.add(e1); + } + } + return n.reconstruct(n.getSource(), elems); + } + + protected void pushRec(RecVar rv, Seq body) + { + if (this.recs.containsKey(rv)) + { + throw new RuntimeException("Shouldn't get here: " + rv); + } + this.recs.put(rv, body); + } + + protected boolean hasRec(RecVar rv) + { + return this.recs.containsKey(rv); + } + + protected Seq getRec(RecVar rv) + { + return this.recs.get(rv); + } + + protected void popRec(RecVar rv) + { + this.recs.remove(rv); + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/visit/STypeVisitor.java b/scribble-core/src/main/java/org/scribble/core/visit/STypeVisitor.java new file mode 100644 index 000000000..df6862237 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/visit/STypeVisitor.java @@ -0,0 +1,191 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.visit; + +import java.util.LinkedList; +import java.util.List; +import java.util.stream.Stream; + +import org.scribble.core.type.kind.ProtoKind; +import org.scribble.core.type.session.Choice; +import org.scribble.core.type.session.Recursion; +import org.scribble.core.type.session.SType; +import org.scribble.core.type.session.Seq; +import org.scribble.util.ScribException; + +// "Instantiates" STypeAgg by implicitly treating Stream as always a singleton Stream of the *reconstructed* node. +// The main benefit is to reuse the SType.visitWith(STypeAgg) methods for STypeVisitors. +// +// Alternative characterisations of STypeVisitor as STypeAgg? +// T = SType, unit = empty, agg = reconstruct, ns = "structural" (i.e, B) children -- issues with generic cast to B inside agg +// T = SType, unit = n.getChildren(), agg = reconstruct, ns = all children -- all children require dynamic casts +// T = B ... ? Considering Stream like a Seq, and elems as singleton Seqs -- cf. Stream, for Choice/etc reconstruct +// The sticking issue is that the "compound" nodes are not quite uniform w.r.t. agg: Choice/Recursion have Seq children, Seq has SType (but not Seq) children +public abstract class STypeVisitor> + extends STypeAgg> // T = SType gives more flexibile/extensibile reconstruction patterns +{ + @Override + protected final SType unit(SType n) throws ScribException + { + return n; + } + + // Should disregard agg for STypeVisitors -- the STypeVisitor pattern is instead to manually reconstruct within each visit[Node] + @Override + protected final SType agg(SType n, Stream> ns) + throws ScribException + { + throw new RuntimeException("Disregarded for STypeVisitor: " + n + " ,, " + ns); + } + + @Override + public SType visitChoice(Choice n) throws ScribException + { + List blocks = new LinkedList<>(); + for (B b : n.blocks) + { + blocks.add(visitSeq(b)); + + } + return n.reconstruct(n.getSource(), n.subj, blocks); // Disregarding agg (reconstruction done here) + } + + @Override + public SType visitRecursion(Recursion n) throws ScribException + { + B body = visitSeq(n.body); + return n.reconstruct(n.getSource(), n.recvar, body); // Disregarding agg (reconstruction done here) + } + + // "Hardcoded" to B (cf. Seq, or SType return) -- this visitor pattern depends on B for Choice/Recursion/etc reconstruction + // This means a Visitor that needs to restructure a Seq should handle this within visitSeq + // E.g., Seq "injection" by inlining and unfolding (i.e., when a visited elem is a Seq) + // For this purpose, visited children passed "directly" instead of via a reconstruction (cf. above methods) -- ? + @Override + public B visitSeq(B n) throws ScribException + { + List> elems = new LinkedList<>(); + for (SType e : n.elems) + { + elems.add(e.visitWith(this)); + } + return n.reconstruct(n.getSource(), elems); // Disregarding agg (reconstruction done here) + } +} + + + + + + + + + + + + + + + + + + + + + + + /*// Should generally disregard agg for STypeVisitors -- pattern is now to manually do reconstruct within visit dispatches + @Override + protected final SType agg(SType n, Stream> ns) + throws ScribException + { + return ns.iterator().next(); + + // agg = reconstruct, ns = "structural" (i.e, B) children -- problem with generic casts + if (n instanceof Continue || n instanceof DirectedInteraction + || n instanceof DisconnectAction || n instanceof Do) + { + return ns.iterator().next(); + } + else if (n instanceof Choice) + { + Choice c = (Choice) n; + return c.reconstruct(c.getSource(), c.subj, + ns.map(x -> (B) x).collect(Collectors.toList())); + } + else if (n instanceof Recursion) + { + Recursion r = (Recursion) n; + return r.reconstruct(r.getSource(), r.recvar, (B) ns.iterator().next()); + } + else + { + throw new RuntimeException("Shouldn't get in here: " + n + " ,, " + ns); + // agg should only be called from internal visit dispatch methods, so n's type has already been cased + } + }*/ + + +/* + // SType return for extensibility/flexibility + public SType visitContinue(Continue n) throws ScribException + { + //return n.reconstruct(n.getSource(), n.recvar); + return n; + } + + public SType visitChoice(Choice n) throws ScribException + { + List blocks = new LinkedList<>(); + for (B b : n.blocks) + { + blocks.add(b.visitWith(this)); + } + return n.reconstruct(n.getSource(), n.subj, blocks); + } + + public SType visitDirectedInteraction(DirectedInteraction n) + throws ScribException + { + //return n.reconstruct(n.getSource(), n.msg, n.src, n.dst); + return n; + } + + public SType visitDisconnect(DisconnectAction n) + throws ScribException + { + //return n.reconstruct(n.getSource(), n.left, n.right); + return n; + } + + public > SType visitDo(Do n) + throws ScribException + { + //return n.reconstruct(n.getSource(), n.proto, n.roles, n.args); + return n; + } + + public SType visitRecursion(Recursion n) throws ScribException + { + B body = n.body.visitWith(this); + return n.reconstruct(n.getSource(), n.recvar, body); + } +*/ + + +/*@FunctionalInterface +interface STypeVisitorFunction, R extends Stream> +{ + R f(SType n, STypeVisitor v); +}*/ diff --git a/scribble-core/src/main/java/org/scribble/core/visit/STypeVisitorFactory.java b/scribble-core/src/main/java/org/scribble/core/visit/STypeVisitorFactory.java new file mode 100644 index 000000000..34d78b1c8 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/visit/STypeVisitorFactory.java @@ -0,0 +1,56 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.visit; + +import java.util.List; + +import org.scribble.core.type.kind.NonRoleParamKind; +import org.scribble.core.type.kind.ProtoKind; +import org.scribble.core.type.name.MemberName; +import org.scribble.core.type.name.Role; +import org.scribble.core.type.session.Arg; +import org.scribble.core.type.session.Seq; +import org.scribble.core.visit.global.GTypeVisitorFactory; +import org.scribble.core.visit.local.LTypeVisitorFactory; + +// Not an interface due to fields +public abstract class STypeVisitorFactory +{ + public final GTypeVisitorFactory global; + public final LTypeVisitorFactory local; + + public STypeVisitorFactory(GTypeVisitorFactory global, + LTypeVisitorFactory local) + { + this.global = global; + this.local = local; + } + + public > Substitutor + Substitutor(List rold, List rnew, + List> aold, + List> anew) + { + return Substitutor(rold, rnew, aold, anew, false); + } + + public abstract > Substitutor + Substitutor(List rold, List rnew, + List> aold, + List> anew, boolean passive); + + public abstract > RecPruner + RecPruner(); + +} diff --git a/scribble-core/src/main/java/org/scribble/core/visit/STypeVisitorFactoryImpl.java b/scribble-core/src/main/java/org/scribble/core/visit/STypeVisitorFactoryImpl.java new file mode 100644 index 000000000..691719c32 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/visit/STypeVisitorFactoryImpl.java @@ -0,0 +1,51 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.visit; + +import java.util.List; + +import org.scribble.core.type.kind.NonRoleParamKind; +import org.scribble.core.type.kind.ProtoKind; +import org.scribble.core.type.name.MemberName; +import org.scribble.core.type.name.Role; +import org.scribble.core.type.session.Arg; +import org.scribble.core.type.session.Seq; +import org.scribble.core.visit.global.GTypeVisitorFactory; +import org.scribble.core.visit.local.LTypeVisitorFactory; + +// No interface due to fields -- CHECKME: factor out "neutral" factory field for RecPruner etc. +public class STypeVisitorFactoryImpl extends STypeVisitorFactory +{ + public STypeVisitorFactoryImpl(GTypeVisitorFactory global, + LTypeVisitorFactory local) + { + super(global, local); + } + + @Override + public > Substitutor + Substitutor(List rold, List rnew, + List> aold, + List> anew, boolean passive) + { + return new Substitutor<>(rold, rnew, aold, anew, passive); + } + + @Override + public > RecPruner + RecPruner() + { + return new RecPruner<>(); + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/visit/STypeVisitorNoThrow.java b/scribble-core/src/main/java/org/scribble/core/visit/STypeVisitorNoThrow.java new file mode 100644 index 000000000..fadce814c --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/visit/STypeVisitorNoThrow.java @@ -0,0 +1,138 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.visit; + +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.scribble.core.type.kind.ProtoKind; +import org.scribble.core.type.session.Choice; +import org.scribble.core.type.session.Recursion; +import org.scribble.core.type.session.SType; +import org.scribble.core.type.session.Seq; + +// For comments, see STypeVisitor +public abstract class STypeVisitorNoThrow> + extends STypeAggNoThrow> +{ + @Override + protected final SType unit(SType n) + { + return n; + } + + // Should disregard agg for STypeVisitors -- the STypeVisitor pattern is instead to manually reconstruct within each visit[Node] + @Override + protected final SType agg(SType n, Stream> ns) + { + throw new RuntimeException("Disregarded for STypeVisitorNoEx: " + n + " ,, " + ns); + } + + @Override + public SType visitChoice(Choice n) + { + List blocks = n.blocks.stream().map(x -> visitSeq(x)) + .collect(Collectors.toList()); + return n.reconstruct(n.getSource(), n.subj, blocks); // Disregarding agg (reconstruction done here) + } + + @Override + public SType visitRecursion(Recursion n) + { + B body = visitSeq(n.body); + return n.reconstruct(n.getSource(), n.recvar, body); // Disregarding agg (reconstruction done here) + } + + @Override + public B visitSeq(B n) + { + List> elems = n.elems.stream().map(x -> x.visitWithNoThrow(this)) + .collect(Collectors.toList()); + return n.reconstruct(n.getSource(), elems); // Disregarding agg (reconstruction done here) + } + +} + + + + + + + + + + + + + + + + + + + /* + public SType visitContinue(Continue n) + { + return n; + } + + public SType visitChoice(Choice n) + { + List blocks = n.blocks.stream().map(x -> x.visitWithNoEx(this)) + .collect(Collectors.toList()); + return n.reconstruct(n.getSource(), n.subj, blocks); + } + + public SType visitDirectedInteraction(DirectedInteraction n) + { + //return n.reconstruct(n.getSource(), n.msg, n.src, n.dst); + return n; + } + + public SType visitDisconnect(DisconnectAction n) + { + //return n.reconstruct(n.getSource(), n.left, n.right); + return n; + } + + public > SType visitDo(Do n) + { + //return n.reconstruct(n.getSource(), n.proto, n.roles, n.args); + return n; + } + + public SType visitRecursion(Recursion n) + { + B body = n.body.visitWithNoEx(this); + return n.reconstruct(n.getSource(), n.recvar, body); + } + + // "Hardcoded" to B (cf. Seq, or SType return) -- this visitor pattern depends on B for Choice/Recursion/etc reconstruction + // This means a Visitor that needs to restructure a Seq should handle this within visitSeq + // E.g., Seq "injection" by inlining and unfolding + // For this purpose, visited children passed "directly" instead of via a reconstruction (cf. above methods) + public B visitSeq(B n) + { + List> elems = n.elems.stream().map(x -> x.visitWithNoEx(this)) + .collect(Collectors.toList()); + return n.reconstruct(n.getSource(), elems); + }*/ + + +/*@FunctionalInterface +interface STypeVisitorFunction, R extends Stream> +{ + R f(SType n, STypeVisitor v); +}*/ diff --git a/scribble-core/src/main/java/org/scribble/core/visit/Substitutor.java b/scribble-core/src/main/java/org/scribble/core/visit/Substitutor.java new file mode 100644 index 000000000..b5259d7b4 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/visit/Substitutor.java @@ -0,0 +1,108 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.visit; + +import java.util.LinkedList; +import java.util.List; +import java.util.stream.Collectors; + +import org.scribble.core.type.kind.NonRoleParamKind; +import org.scribble.core.type.kind.ProtoKind; +import org.scribble.core.type.name.DataName; +import org.scribble.core.type.name.MemberName; +import org.scribble.core.type.name.Role; +import org.scribble.core.type.name.SigName; +import org.scribble.core.type.name.Substitutions; +import org.scribble.core.type.session.Arg; +import org.scribble.core.type.session.Choice; +import org.scribble.core.type.session.DirectedInteraction; +import org.scribble.core.type.session.DisconnectAction; +import org.scribble.core.type.session.Do; +import org.scribble.core.type.session.Msg; +import org.scribble.core.type.session.SType; +import org.scribble.core.type.session.Seq; + +public class Substitutor> + extends STypeVisitorNoThrow +{ + private Substitutions subs; + private boolean passive; + + protected Substitutor(List rold, List rnew, + List> aold, + List> anew, boolean passive) + { + this.subs = new Substitutions(rold, rnew, aold, anew); + this.passive = passive; + } + + @Override + public SType visitChoice(Choice n) + { + List blocks = n.blocks.stream().map(x -> visitSeq(x)) + .collect(Collectors.toList()); + return n.reconstruct(n.getSource(), + this.subs.subsRole(n.subj, this.passive), blocks); + } + + @Override + public SType visitDirectedInteraction(DirectedInteraction n) + { + Msg msg = n.msg; + if (msg instanceof MemberName) + { + MemberName name = (MemberName) msg; + if (this.subs.hasArg(name)) + { + msg = (Msg) this.subs.subsArg(name, this.passive); + } + } + return n.reconstruct(n.getSource(), msg, + this.subs.subsRole(n.src, this.passive), + this.subs.subsRole(n.dst, this.passive)); + } + + @Override + public SType visitDisconnect(DisconnectAction n) + { + return n.reconstruct(n.getSource(), + this.subs.subsRole(n.left, this.passive), + this.subs.subsRole(n.right, this.passive)); + } + + @Override + public SType visitDo(Do n) + { + List roles = n.roles.stream() + .map(x -> this.subs.subsRole(x, this.passive)) + .collect(Collectors.toList()); + List> args = new LinkedList<>(); + for (Arg a : n.args) + { + if (a instanceof MemberName && this.subs.hasArg((MemberName) a)) + { + if (a instanceof DataName) + { + a = this.subs.subsArg((DataName) a, this.passive); + } + else if (a instanceof SigName) + { + a = this.subs.subsArg((SigName) a, this.passive); + } + } + args.add(a); + } + return n.reconstruct(n.getSource(), n.proto, roles, args); + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/visit/gather/MessageIdGatherer.java b/scribble-core/src/main/java/org/scribble/core/visit/gather/MessageIdGatherer.java new file mode 100644 index 000000000..09639baee --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/visit/gather/MessageIdGatherer.java @@ -0,0 +1,33 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.visit.gather; + +import java.util.stream.Stream; + +import org.scribble.core.type.kind.ProtoKind; +import org.scribble.core.type.name.MsgId; +import org.scribble.core.type.session.DirectedInteraction; +import org.scribble.core.type.session.Seq; + +public class MessageIdGatherer> + extends STypeGatherer> +{ + + @Override + public Stream> visitDirectedInteraction( + DirectedInteraction n) + { + return Stream.of(n.msg.getId()); + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/visit/gather/NonProtoDepsGatherer.java b/scribble-core/src/main/java/org/scribble/core/visit/gather/NonProtoDepsGatherer.java new file mode 100644 index 000000000..362fe80d5 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/visit/gather/NonProtoDepsGatherer.java @@ -0,0 +1,96 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.visit.gather; + +import java.util.LinkedList; +import java.util.List; +import java.util.stream.Stream; + +import org.scribble.core.type.kind.ProtoKind; +import org.scribble.core.type.name.DataName; +import org.scribble.core.type.name.GDelegType; +import org.scribble.core.type.name.MemberName; +import org.scribble.core.type.name.PayElemType; +import org.scribble.core.type.name.SigName; +import org.scribble.core.type.session.Choice; +import org.scribble.core.type.session.ConnectAction; +import org.scribble.core.type.session.DirectedInteraction; +import org.scribble.core.type.session.Do; +import org.scribble.core.type.session.Payload; +import org.scribble.core.type.session.Seq; +import org.scribble.core.type.session.SigLit; + + +// Result should not contain duplicates (i.e., due to Choice/Seq) +// Result does not necessarily contain root proto (protodecl is not an SType), but may do so via dependencies +// N.B. delegation payloads currently gathered here, not by getProtoDependencies -- CHECKME: refactor? +public class NonProtoDepsGatherer> + extends STypeGatherer> +{ + @Override + public Stream> visitChoice(Choice n) + { + return super.visitChoice(n).distinct(); + } + + @Override + public Stream> visitSeq(Seq n) + { + return super.visitSeq(n).distinct(); + } + + @Override + public Stream> visitDirectedInteraction(DirectedInteraction n) + { + { + List> res = new LinkedList<>(); + if (n.msg.isSigName()) + { + res.add((SigName) n.msg); + } + else //if (this.msg.isMessageSig) + { + Payload pay = ((SigLit) n.msg).payload; + for (PayElemType p : pay.elems) + { + if (p.isDataName()) + { + res.add((DataName) p); + } + else if (p.isGDelegationType()) // TODO FIXME: should be projected to local name + { + if (n instanceof ConnectAction) + { + throw new RuntimeException("Shouldn't get in here: " + n); + } + res.add(((GDelegType) p).getGlobalProtocol()); + } + else + { + throw new RuntimeException("[TODO]: " + this); + } + } + } + return res.stream(); + } + } + + @Override + public Stream> visitDo(Do n) + { + return n.args.stream() + .filter(x -> (x instanceof SigLit) || (x instanceof DataName)) // CHECKME: refactor? + .map(x -> (MemberName) x); + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/visit/gather/ProtoDepsCollector.java b/scribble-core/src/main/java/org/scribble/core/visit/gather/ProtoDepsCollector.java new file mode 100644 index 000000000..cf5fcc334 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/visit/gather/ProtoDepsCollector.java @@ -0,0 +1,47 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.visit.gather; + +import java.util.stream.Stream; + +import org.scribble.core.type.kind.ProtoKind; +import org.scribble.core.type.name.ProtoName; +import org.scribble.core.type.session.Choice; +import org.scribble.core.type.session.Do; +import org.scribble.core.type.session.Seq; + +// Result should not contain duplicates (i.e., due to Choice/Seq) +// Result does not necessarily contain root proto (protodecl is not an SType), but may do so via dependencies +public class ProtoDepsCollector> + extends STypeGatherer> +{ + + @Override + public Stream> visitChoice(Choice n) + { + return super.visitChoice(n).distinct(); + } + + @Override + public Stream> visitSeq(Seq n) + { + return super.visitSeq(n).distinct(); + } + + @Override + public Stream> visitDo(Do n) + { + return Stream.of(n.proto); // Should be full names + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/visit/gather/RecVarGatherer.java b/scribble-core/src/main/java/org/scribble/core/visit/gather/RecVarGatherer.java new file mode 100644 index 000000000..644713613 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/visit/gather/RecVarGatherer.java @@ -0,0 +1,31 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.visit.gather; + +import java.util.stream.Stream; + +import org.scribble.core.type.kind.ProtoKind; +import org.scribble.core.type.name.RecVar; +import org.scribble.core.type.session.Continue; +import org.scribble.core.type.session.Seq; + +public class RecVarGatherer> + extends STypeGatherer +{ + @Override + public Stream visitContinue(Continue n) + { + return Stream.of(n.recvar); + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/visit/gather/RoleGatherer.java b/scribble-core/src/main/java/org/scribble/core/visit/gather/RoleGatherer.java new file mode 100644 index 000000000..bd84ecb58 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/visit/gather/RoleGatherer.java @@ -0,0 +1,47 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.visit.gather; + +import java.util.stream.Stream; + +import org.scribble.core.type.kind.ProtoKind; +import org.scribble.core.type.name.Role; +import org.scribble.core.type.session.Choice; +import org.scribble.core.type.session.DirectedInteraction; +import org.scribble.core.type.session.DisconnectAction; +import org.scribble.core.type.session.Seq; + +// N.B. does *not* gather do-args, nor follow subprotos +public class RoleGatherer> + extends STypeGatherer +{ + + @Override + public Stream visitChoice(Choice n) + { + return Stream.of(n.subj); + } + + @Override + public Stream visitDirectedInteraction(DirectedInteraction n) + { + return Stream.of(n.src, n.dst); + } + + @Override + public Stream visitDisconnect(DisconnectAction n) + { + return Stream.of(n.left, n.right); + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/visit/gather/STypeGatherer.java b/scribble-core/src/main/java/org/scribble/core/visit/gather/STypeGatherer.java new file mode 100644 index 000000000..57f90ec37 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/visit/gather/STypeGatherer.java @@ -0,0 +1,97 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.visit.gather; + +import java.util.Optional; +import java.util.stream.Stream; + +import org.scribble.core.type.kind.ProtoKind; +import org.scribble.core.type.session.Choice; +import org.scribble.core.type.session.Continue; +import org.scribble.core.type.session.DirectedInteraction; +import org.scribble.core.type.session.DisconnectAction; +import org.scribble.core.type.session.Do; +import org.scribble.core.type.session.Recursion; +import org.scribble.core.type.session.SType; +import org.scribble.core.type.session.Seq; + +// Refactor as special case of Agg? +public abstract class STypeGatherer, T> +{ + // Pass this to SType.gather, e.g., n.gather(new RoleGatherer()::visit) + public Stream visit(SType n) + { + return typeSwitch(n).get(); + } + + // Can override by adding new cases when super call returns empty + protected Optional> typeSwitch(SType n) + { + return (n instanceof DirectedInteraction) + ? Optional.of(visitDirectedInteraction((DirectedInteraction) n)) + : (n instanceof DisconnectAction) + ? Optional.of(visitDisconnect((DisconnectAction) n)) + : (n instanceof Choice) + ? Optional.of(visitChoice((Choice) n)) + : (n instanceof Seq) + ? Optional.of(visitSeq((Seq) n)) + : (n instanceof Continue) + ? Optional.of(visitContinue((Continue) n)) + : (n instanceof Recursion) + ? Optional.of(visitRecursion((Recursion) n)) + : (n instanceof Do) + ? Optional.of(this.visitDo((Do) n)) + : Optional.empty(); + // Better for extensibility than "manually" throwing Exception (e.g., for overriding) + // N.B. currently causes exception on get in visit + } + + public Stream visitContinue(Continue n) + { + return Stream.of(); + } + + public Stream visitChoice(Choice n) + { + return Stream.of(); + } + + // CHECKME: split into ConnectionAction and MessageTransfer? cf. NonProtoDepsCollector -- and how about locals? + // This is the "level" of reconstruct, though + // Or offer all, with ConnectionAction and MessageTransfer delegating to DirectedInteraction by default? (must order correctly in typeSwitch) + public Stream visitDirectedInteraction(DirectedInteraction n) + { + return Stream.of(); + } + + public Stream visitDisconnect(DisconnectAction n) + { + return Stream.of(); + } + + public Stream visitDo(Do n) + { + return Stream.of(); + } + + public Stream visitRecursion(Recursion n) + { + return Stream.of(); + } + + public Stream visitSeq(Seq n) + { + return Stream.of(); + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/visit/global/ConnectionChecker.java b/scribble-core/src/main/java/org/scribble/core/visit/global/ConnectionChecker.java new file mode 100644 index 000000000..b0776d67b --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/visit/global/ConnectionChecker.java @@ -0,0 +1,134 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.visit.global; + +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.scribble.core.type.kind.Global; +import org.scribble.core.type.name.Role; +import org.scribble.core.type.session.Choice; +import org.scribble.core.type.session.ConnectAction; +import org.scribble.core.type.session.DirectedInteraction; +import org.scribble.core.type.session.DisconnectAction; +import org.scribble.core.type.session.Do; +import org.scribble.core.type.session.SType; +import org.scribble.core.type.session.global.GSeq; +import org.scribble.core.visit.STypeVisitor; +import org.scribble.util.ScribException; + +// Pre: use on inlined or later (unsupported for Do, also Protocol) +// CHECKME: connection check at global vs. local level? +public class ConnectionChecker extends STypeVisitor +{ + protected enum Status { CONN, DIS, AMBIG } + + public final Set roles; + public final boolean implicit; + + protected final Map, Status> conns; + + protected ConnectionChecker(Set roles, boolean implicit) + { + this.roles = Collections.unmodifiableSet(roles); + this.implicit = implicit; + this.conns = roles.stream() + .flatMap(x -> roles.stream().filter(y -> !y.equals(x)) + .map(y -> Stream.of(x, y).collect(Collectors.toSet()))) + .distinct() + .collect( + Collectors.toMap(x -> x, x -> implicit ? Status.CONN : Status.DIS)); + } + + // Copy constructor + protected ConnectionChecker(ConnectionChecker v) + { + this.roles = v.roles; + this.implicit = v.implicit; + this.conns = new HashMap<>(v.conns); + } + + @Override + public SType visitChoice(Choice n) + throws ScribException + { + List, Status>> blocks = new LinkedList<>(); + for (GSeq block : n.blocks) + { + ConnectionChecker nested = new ConnectionChecker(this); + block.visitWith(nested); + blocks.add(nested.conns); + } + blocks.stream() + .reduce((x, y) -> x.keySet().stream() + .collect(Collectors.toMap(k -> k, + k -> x.get(k).equals(y.get(k)) ? x.get(k) : Status.AMBIG))) + .get().entrySet() + .forEach(x -> this.conns.put(x.getKey(), x.getValue())); + return n; // super would do reconstruct + } + + @Override + public SType visitDirectedInteraction( + DirectedInteraction n) throws ScribException + { + Set rs = Stream.of(n.src, n.dst).collect(Collectors.toSet()); + if (n instanceof ConnectAction) + { + switch (this.conns.get(rs)) + { + case AMBIG: throw new ScribException("Roles may already be connected: " + n); + case CONN: throw new ScribException("Roles already connected: " + n); + default: this.conns.put(rs, Status.CONN); + } + } + else + { + switch (this.conns.get(rs)) + { + case AMBIG: throw new ScribException("Roles may be disconnected: " + n); + case DIS: throw new ScribException("Roles disconnected: " + n); + default: + } + } + return super.visitDirectedInteraction(n); + } + + @Override + public SType visitDisconnect(DisconnectAction n) + throws ScribException + { + Set rs = Stream.of(n.left, n.right).collect(Collectors.toSet()); + switch (this.conns.get(rs)) + { + case AMBIG: throw new ScribException("Roles may already be disconnected: " + n); + case DIS: throw new ScribException("Roles already disconnected: " + n); + default: this.conns.put(rs, Status.DIS); + } + return super.visitDisconnect(n); + } + + @Override + public final SType visitDo(Do n) throws ScribException + { + throw new RuntimeException(this.getClass() + " unsupported for Do: " + n); + } + +} diff --git a/scribble-core/src/main/java/org/scribble/core/visit/global/ExtChoiceConsistencyChecker.java b/scribble-core/src/main/java/org/scribble/core/visit/global/ExtChoiceConsistencyChecker.java new file mode 100644 index 000000000..143f4bf1a --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/visit/global/ExtChoiceConsistencyChecker.java @@ -0,0 +1,116 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.visit.global; + +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.scribble.core.type.kind.Global; +import org.scribble.core.type.name.Role; +import org.scribble.core.type.session.Choice; +import org.scribble.core.type.session.DirectedInteraction; +import org.scribble.core.type.session.Do; +import org.scribble.core.type.session.SType; +import org.scribble.core.type.session.global.GSeq; +import org.scribble.core.visit.STypeVisitor; +import org.scribble.util.ScribException; + +// Pre: use on inlined or later (unsupported for Do, also Protocol) +public class ExtChoiceConsistencyChecker extends STypeVisitor +{ + private Map enablers; // Invariant: unmodifiable + + protected ExtChoiceConsistencyChecker(Map enabled) + { + setEnablers(enabled); + } + + public SType visitChoice(Choice n) + throws ScribException + { + Map subj = Stream.of(n.subj) + .collect(Collectors.toMap(x -> x, x -> x)); + List> blocks = new LinkedList<>(); + ExtChoiceConsistencyChecker nested = new ExtChoiceConsistencyChecker(subj); + // Arg redundant, but better to keep a single constructor, for factory pattern + for (GSeq block : n.blocks) + { + nested.setEnablers(subj); + nested.visitSeq(block); + blocks.add(nested.getEnablers()); + } + Map res = new HashMap<>(getEnablers()); + Set> all = blocks.stream() + .flatMap(x -> x.entrySet().stream()).collect(Collectors.toSet()); + for (Entry e : all) + { + Role enabled = e.getKey(); + Role enabler = e.getValue(); + if (all.stream().anyMatch( + x -> x.getKey().equals(enabled) && !x.getValue().equals(enabler))) + { + throw new ScribException( + "Inconsistent external choice subjects for " + enabled + ": " + + all.stream().filter(x -> x.getKey().equals(enabled)) + .collect(Collectors.toList())); + } + if (!res.containsKey(enabled)) + { + res.put(enabled, enabler); + } + } + setEnablers(res); + return n; + } + + @Override + public SType visitDirectedInteraction( + DirectedInteraction n) throws ScribException + { + Map enablers = getEnablers(); + if (enablers.containsKey(n.dst)) + + { + return n; + } + Map res = new HashMap<>(enablers); + res.put(n.dst, n.src); + setEnablers(res); + return n; + } + + @Override + public final SType visitDo(Do n) throws ScribException + { + throw new RuntimeException(this.getClass() + " unsupported for Do: " + n); + } + + protected Map getEnablers() + { + return this.enablers; + } + + // Guards this.enablers unmodifiable + protected void setEnablers(Map enabled) + { + this.enablers = Collections.unmodifiableMap(enabled); + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/visit/global/GTypeInliner.java b/scribble-core/src/main/java/org/scribble/core/visit/global/GTypeInliner.java new file mode 100644 index 000000000..7085e5df5 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/visit/global/GTypeInliner.java @@ -0,0 +1,55 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.visit.global; + +import org.scribble.core.job.Core; +import org.scribble.core.lang.SubprotoSig; +import org.scribble.core.lang.global.GProtocol; +import org.scribble.core.type.kind.Global; +import org.scribble.core.type.name.ProtoName; +import org.scribble.core.type.name.RecVar; +import org.scribble.core.type.session.Do; +import org.scribble.core.type.session.SType; +import org.scribble.core.type.session.global.GSeq; +import org.scribble.core.visit.STypeInliner; +import org.scribble.core.visit.Substitutor; + +public class GTypeInliner extends STypeInliner +{ + protected GTypeInliner(Core core) + { + super(core); + } + + @Override + public SType visitDo(Do n) + { + ProtoName fullname = n.proto; + SubprotoSig sig = new SubprotoSig(fullname, n.roles, n.args); + RecVar rv = getInlinedRecVar(sig); + if (hasSig(sig)) + { + return this.core.config.tf.global.GContinue(n.getSource(), rv); + } + pushSig(sig); + GProtocol g = this.core.getContext().getIntermediate(fullname); + Substitutor subs = this.core.config.vf.Substitutor(g.roles, + n.roles, g.params, n.args); + //GSeq inlined = (GSeq) g.def.visitWithNoEx(subs).visitWithNoEx(this); + GSeq inlined = visitSeq(subs.visitSeq(g.def)); + // i.e. returning a GSeq -- rely on parent GSeq to inline + popSig(); + return this.core.config.tf.global.GRecursion(null, rv, inlined); + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/visit/global/GTypeUnfolder.java b/scribble-core/src/main/java/org/scribble/core/visit/global/GTypeUnfolder.java new file mode 100644 index 000000000..b6a33d057 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/visit/global/GTypeUnfolder.java @@ -0,0 +1,37 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.visit.global; + +import org.scribble.core.job.Core; +import org.scribble.core.type.kind.Global; +import org.scribble.core.type.session.Continue; +import org.scribble.core.type.session.global.GSeq; +import org.scribble.core.type.session.global.GType; +import org.scribble.core.visit.STypeUnfolder; + +public class GTypeUnfolder extends STypeUnfolder +{ + + protected GTypeUnfolder(Core core) + { + super(core); + } + + @Override + public GType visitContinue(Continue n) + { + return this.core.config.tf.global.GRecursion(n.getSource(), n.recvar, + (GSeq) getRec(n.recvar)); + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/visit/global/GTypeVisitorFactory.java b/scribble-core/src/main/java/org/scribble/core/visit/global/GTypeVisitorFactory.java new file mode 100644 index 000000000..585539d7b --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/visit/global/GTypeVisitorFactory.java @@ -0,0 +1,40 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.visit.global; + +import java.util.Map; +import java.util.Set; + +import org.scribble.core.job.Core; +import org.scribble.core.type.name.Role; + +public interface GTypeVisitorFactory +{ + GTypeInliner GTypeInliner(Core core); + + GTypeUnfolder GTypeUnfolder(Core core); + + RoleEnablingChecker RoleEnablingChecker(Set rs); + + ExtChoiceConsistencyChecker ExtChoiceConsistencyChecker( + Map enabled); + + ConnectionChecker ConnectionChecker(Set rs, boolean implicit); + + InlinedProjector InlinedProjector(Core core, Role self); + + // CHECKME: deprecate? + SubprotoProjector Projector(Core core, Role self); + +} diff --git a/scribble-core/src/main/java/org/scribble/core/visit/global/GTypeVisitorFactoryImpl.java b/scribble-core/src/main/java/org/scribble/core/visit/global/GTypeVisitorFactoryImpl.java new file mode 100644 index 000000000..5d481ab5e --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/visit/global/GTypeVisitorFactoryImpl.java @@ -0,0 +1,69 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.visit.global; + +import java.util.Map; +import java.util.Set; + +import org.scribble.core.job.Core; +import org.scribble.core.type.name.Role; + +public class GTypeVisitorFactoryImpl implements GTypeVisitorFactory +{ + + @Override + public GTypeInliner GTypeInliner(Core core) + { + return new GTypeInliner(core); + } + + @Override + public GTypeUnfolder GTypeUnfolder(Core core) + { + return new GTypeUnfolder(core); + } + + @Override + public RoleEnablingChecker RoleEnablingChecker(Set rs) + { + return new RoleEnablingChecker(rs); + } + + @Override + public ExtChoiceConsistencyChecker ExtChoiceConsistencyChecker( + Map enabled) + { + return new ExtChoiceConsistencyChecker(enabled); + } + + @Override + public ConnectionChecker ConnectionChecker(Set roles, boolean implicit) + { + return new ConnectionChecker(roles, implicit); + } + + @Override + public InlinedProjector InlinedProjector(Core core, Role self) + { + return new InlinedProjector(core, self); + } + + // CHECKME: deprecate? + @Override + public SubprotoProjector Projector(Core core, Role self) + { + return new SubprotoProjector(core, self); + } + +} diff --git a/scribble-core/src/main/java/org/scribble/core/visit/global/InlinedProjector.java b/scribble-core/src/main/java/org/scribble/core/visit/global/InlinedProjector.java new file mode 100644 index 000000000..51a82d531 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/visit/global/InlinedProjector.java @@ -0,0 +1,246 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.visit.global; + +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.scribble.core.job.Core; +import org.scribble.core.type.kind.Global; +import org.scribble.core.type.kind.Local; +import org.scribble.core.type.name.LProtoName; +import org.scribble.core.type.name.ModuleName; +import org.scribble.core.type.name.ProtoName; +import org.scribble.core.type.name.RecVar; +import org.scribble.core.type.name.Role; +import org.scribble.core.type.session.Choice; +import org.scribble.core.type.session.Continue; +import org.scribble.core.type.session.DirectedInteraction; +import org.scribble.core.type.session.DisconnectAction; +import org.scribble.core.type.session.Do; +import org.scribble.core.type.session.Recursion; +import org.scribble.core.type.session.SType; +import org.scribble.core.type.session.global.GConnect; +import org.scribble.core.type.session.global.GSeq; +import org.scribble.core.type.session.local.LContinue; +import org.scribble.core.type.session.local.LSeq; +import org.scribble.core.type.session.local.LSkip; +import org.scribble.core.type.session.local.LType; +import org.scribble.core.type.session.local.LTypeFactory; +import org.scribble.core.visit.STypeAggNoThrow; + +// Pre: use on inlined (i.e., "do" inlined, roles pruned) +public class InlinedProjector extends STypeAggNoThrow +{ + //protected final Set unguarded; + protected final Set unguarded; + // Projection "prunes" unguarded continues from choice cases, e.g., mu X.(A->B:1.X + A->B:2.A->C:2) for C, i.e., travel agent + // ...this can be followed by RecPruner to remove recs that are "orphaned" by continue pruning + // N.B. projection does not "merge" choice cases in , e.g., rec X { 1() from A; choice at A { continue X; } or { continue X; } }... + // ...that is a non-det branch, same as rec X { choice at A { 1() from A; } or { 1() from A; } } + + public final Core core; + public final Role self; + + protected InlinedProjector(Core core, Role self) + { + this.core = core; + this.self = self; + this.unguarded = new HashSet<>(); + } + + // Copy constructor for dup + protected InlinedProjector(InlinedProjector v) + { + this.core = v.core; + this.self = v.self; + this.unguarded = new HashSet<>(v.unguarded); + } + + // Use to visit a node with a copy of the current context (this.unguarded), e.g., for "nested" context visiting (Choice) + // N.B. subclasses should override + protected InlinedProjector dup() + { + return new InlinedProjector(this); + } + + @Override + public LType visitChoice(Choice n) + { + List blocks = n.blocks.stream() + .map(x -> dup().visitSeq(x)) + .filter(x -> !x.isEmpty() && !isUnguardedSingleContinue(x)) + .collect(Collectors.toList()); + if (blocks.isEmpty()) + { + return LSkip.SKIP; // CHECKME: OK, or "empty" choice at subj still important? + } + this.unguarded.clear(); // At least one block is non-empty, consider continues guarded -- must clear here, blocks visited using dup's + + //InlinedEnablerInferer v = new InlinedEnablerInferer(this.unguarded); + Role subj = n.subj.equals(this.self) + ? Role.SELF // i.e., internal choice + : n.subj;//v.visitSeq(blocks.get(0)).get(); // CHECKME: consistent ext choice means can infer from any one seq? + // CHECKME: "self" also explcitily used for Do, but implicitly for MessageTransfer, inconsistent? + return this.core.config.tf.local.LChoice(null, subj, blocks); + } + + // N.B. won't prune unguarded continues that have a bad sequence, will be caught later by reachability checking (e.g., bad.reach.globals.gdo.Test04) + private boolean isUnguardedSingleContinue(LSeq block) + { + if (block.elems.size() != 1) + { + return false; + } + SType e = block.elems.get(0); + return (e instanceof LContinue) + && this.unguarded.contains(((LContinue) e).recvar); // Bound recvars already checked + } + + @Override + public LType visitContinue(Continue n) + { + return this.core.config.tf.local.LContinue(null, n.recvar); + } + + @Override + public LType visitDirectedInteraction(DirectedInteraction n) + { + /*if (n.src.equals(self) && n.dst.equals(self)) + { + // CHECKME: already checked? + }*/ + LTypeFactory lf = this.core.config.tf.local; + if (n instanceof GConnect) // FIXME + { + return n.src.equals(self) ? lf.LReq(null, n.msg, n.dst) + : n.dst.equals(self) ? lf.LAcc(null, n.src, n.msg) + : LSkip.SKIP; + } + else //if (n instanceof GMessageTransfer) + { + return n.src.equals(self) ? lf.LSend(null, n.msg, n.dst) + : n.dst.equals(self) ? lf.LRecv(null, n.src, n.msg) + : LSkip.SKIP; + } + } + + @Override + public LType visitDisconnect(DisconnectAction n) + { + /*if (n.src.equals(self) && n.dst.equals(self)) + { + // CHECKME: already checked? + }*/ + LTypeFactory lf = this.core.config.tf.local; + return n.left.equals(self) ? lf.LDisconnect(null, n.right) + : n.right.equals(self) ? lf.LDisconnect(null, n.left) + : LSkip.SKIP; + } + + @Override + public LType visitDo(Do n) + { + throw new RuntimeException("Unsupported for Do: " + n + " ,, " + this.getClass()); + } + + @Override + public LType visitRecursion(Recursion n) + { + this.unguarded.add(n.recvar); + LSeq body = visitSeq(n.body); // Single "nested" Seq, don't need to copy visitor + if (body.isEmpty()) // A simple special case of empty-rec pruning -- leave it to "official" rec pruning? + { + return LSkip.SKIP; + } + Set rvs = new HashSet<>(); + rvs.add(n.recvar); + //if (body.visitWithNoThrow(new SingleContinueChecker(rvs))) + // "Generalised" single-continue checked now unnecessary, single-continues pruned in choice visiting above + if (body.elems.size() == 1) + { + SType e = body.elems.get(0); + if(e instanceof LContinue && ((LContinue) e).recvar.equals(n.recvar)) + { + return LSkip.SKIP; + } + } + this.unguarded.remove(n.recvar); + return this.core.config.tf.local.LRecursion(null, n.recvar, body); + } + + // Param "hardcoded" to B (cf. Seq, or SType return) -- this visitor pattern depends on B for Choice/Recursion/etc reconstruction + @Override + public LSeq visitSeq(GSeq n) + { + List elems = new LinkedList<>(); + for (SType e : n.elems) + { + LType e1 = e.visitWithNoThrow(this); + if (!(e1 instanceof LSkip)) + { + elems.add(e1); + this.unguarded.clear(); + } + } + return this.core.config.tf.local.LSeq(null, elems); + // Empty seqs converted to LSkip by GChoice/Recursion projection + // And a WF top-level protocol cannot produce empty LSeq + // So a projection never contains an empty LSeq -- i.e., "empty choice/rec" pruning unnecessary + } + + // CHECKME: relocate? + public static LProtoName getSimpledProjectionName(ProtoName simpname, + Role role) + { + return new LProtoName(simpname.toString() + "_" + role.toString()); + } + + // Role is the target subprotocol parameter (not the current projector self -- actually the self just popped) -- ? + public static LProtoName getFullProjectionName(ProtoName fullname, + Role role) + { + ProtoName simplename = InlinedProjector.getSimpledProjectionName( + fullname.getSimpleName(), role); + ModuleName modname = getProjectionModuleName(fullname.getPrefix(), + simplename); + return new LProtoName(modname, simplename); + } + + // fullname is the un-projected name; localname is the already projected simple name + public static ModuleName getProjectionModuleName(ModuleName fullname, + ProtoName localname) + { + ModuleName simpname = new ModuleName( + fullname.getSimpleName().toString() + "_" + localname.toString()); + return new ModuleName(fullname.getPrefix(), simpname); // Supports unary fullname + } + + @Override + protected LType unit(SType n) + { + throw new RuntimeException("Unsupported for InlinedProjector: " + n); + } + + @Override + protected LType agg(SType n, Stream ts) + { + throw new RuntimeException( + "Unsupported for InlinedProjector: " + n + " ,, " + ts); + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/visit/global/RoleEnablingChecker.java b/scribble-core/src/main/java/org/scribble/core/visit/global/RoleEnablingChecker.java new file mode 100644 index 000000000..b63c2ce97 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/visit/global/RoleEnablingChecker.java @@ -0,0 +1,123 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.visit.global; + +import java.util.Collections; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.scribble.core.type.kind.Global; +import org.scribble.core.type.name.Role; +import org.scribble.core.type.session.Choice; +import org.scribble.core.type.session.DirectedInteraction; +import org.scribble.core.type.session.DisconnectAction; +import org.scribble.core.type.session.Do; +import org.scribble.core.type.session.SType; +import org.scribble.core.type.session.global.GSeq; +import org.scribble.core.visit.STypeVisitor; +import org.scribble.util.ScribException; + +// Pre: use on inlined or later (unsupported for Do, also Protocol) +public class RoleEnablingChecker extends STypeVisitor +{ + private Set enabled; // Invariant: unmodifiable + + protected RoleEnablingChecker(Set enabled) + { + setEnabled(enabled); + } + + public SType visitChoice(Choice n) + throws ScribException + { + Set enabled = getEnabled(); + if (!enabled.contains(n.subj)) + { + throw new ScribException("Subject not enabled: " + n.subj); + } + Set subj = Stream.of(n.subj).collect(Collectors.toSet()); + RoleEnablingChecker nested = new RoleEnablingChecker(subj); + // Arg redundant, but better to keep a single constructor, for factory pattern + List> blocks = new LinkedList<>(); + for (GSeq block : n.blocks) + { + nested.setEnabled(subj); // Copies defensively + nested.visitSeq(block); + blocks.add(nested.getEnabled()); + } + Set res = new HashSet<>(enabled); + Set tmp = blocks.stream().flatMap(x -> x.stream()) + .filter(x -> blocks.stream().allMatch(y -> y.contains(x))) + .collect(Collectors.toSet()); + res.addAll(tmp); + setEnabled(res); + return n; + } + + @Override + public SType visitDirectedInteraction( + DirectedInteraction n) throws ScribException + { + Set enabled = getEnabled(); + if (!enabled.contains(n.src)) + { + throw new ScribException("Source role not enabled: " + n.src); + } + if (enabled.contains(n.dst)) + { + return n; + } + Set res = new HashSet<>(enabled); + res.add(n.dst); + setEnabled(res); + return n; + } + + @Override + public final SType visitDo(Do n) throws ScribException + { + throw new RuntimeException(this.getClass() + " unsupported for Do: " + n); + } + + @Override + public SType visitDisconnect( + DisconnectAction n) throws ScribException + { + Set enabled = getEnabled(); + if (!enabled.contains(n.left)) + { + throw new ScribException("Role not enabled: " + n.left); + } + if (!enabled.contains(n.right)) + { + throw new ScribException("Role not enabled: " + n.right); + } + return n; + } + + public Set getEnabled() + { + return this.enabled; + } + + // Guards this.enabled unmodifiable + protected void setEnabled(Set enabled) + { + this.enabled = Collections.unmodifiableSet(enabled); + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/visit/global/SubprotoProjector.java b/scribble-core/src/main/java/org/scribble/core/visit/global/SubprotoProjector.java new file mode 100644 index 000000000..fcbf06e4f --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/visit/global/SubprotoProjector.java @@ -0,0 +1,83 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.visit.global; + +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; + +import org.scribble.core.job.Core; +import org.scribble.core.job.CoreContext; +import org.scribble.core.lang.global.GProtocol; +import org.scribble.core.type.kind.Global; +import org.scribble.core.type.name.LProtoName; +import org.scribble.core.type.name.ProtoName; +import org.scribble.core.type.name.Role; +import org.scribble.core.type.name.Substitutions; +import org.scribble.core.type.session.Do; +import org.scribble.core.type.session.global.GSeq; +import org.scribble.core.type.session.local.LSkip; +import org.scribble.core.type.session.local.LType; + +// Supports Do -- can use on parsed (intermed) +public class SubprotoProjector extends InlinedProjector // CHECKME: this way, or the other way round? +{ + protected SubprotoProjector(Core core, Role self) + { + super(core, self); + } + + // Copy constructor for dup + protected SubprotoProjector(SubprotoProjector v) + { + super(v); + } + + @Override + protected SubprotoProjector dup() + { + return new SubprotoProjector(this); + } + + @Override + public LType visitDo(Do n) + { + if (!n.roles.contains(this.self)) + { + return LSkip.SKIP; + } + + CoreContext corec = this.core.getContext(); + ProtoName proto = n.proto; + GProtocol imed = corec.getIntermediate(proto); + Role targSelf = imed.roles.get(n.roles.indexOf(this.self)); + if (!imed.roles.contains(targSelf)) // CHECKME: because roles already pruned for intermed decl? + { + return LSkip.SKIP; + } + + LProtoName fullname = InlinedProjector.getFullProjectionName(proto, + targSelf); + Substitutions subs = new Substitutions(imed.roles, n.roles, + Collections.emptyList(), Collections.emptyList()); + List used = corec.getInlined(proto).roles.stream() // N.B. global (inlined) roles -- still need to prune roles w.r.t. localised projection + .map(x -> subs.subsRole(x)).collect(Collectors.toList()); + List rs = n.roles.stream().filter(x -> used.contains(x)) + .map(x -> x.equals(this.self) ? Role.SELF : x) + // CHECKME: syntax: "self" explictly used for Choice subject, but implicitly for MessageTransfer, inconsistent? + .collect(Collectors.toList()); + return this.core.config.tf.local.LDo(null, fullname, rs, n.args); // TODO CHECKME: prune args? + } +} + diff --git a/scribble-core/src/main/java/org/scribble/core/visit/local/EGraphBuilder.java b/scribble-core/src/main/java/org/scribble/core/visit/local/EGraphBuilder.java new file mode 100644 index 000000000..416fb2cf5 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/visit/local/EGraphBuilder.java @@ -0,0 +1,243 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.visit.local; + +import java.util.Collections; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; + +import org.scribble.core.job.Core; +import org.scribble.core.model.endpoint.EGraph; +import org.scribble.core.model.endpoint.EGraphBuilderUtil; +import org.scribble.core.model.endpoint.EState; +import org.scribble.core.model.endpoint.actions.EAction; +import org.scribble.core.type.kind.Local; +import org.scribble.core.type.name.MsgId; +import org.scribble.core.type.name.Role; +import org.scribble.core.type.session.Choice; +import org.scribble.core.type.session.Continue; +import org.scribble.core.type.session.DirectedInteraction; +import org.scribble.core.type.session.DisconnectAction; +import org.scribble.core.type.session.Do; +import org.scribble.core.type.session.Payload; +import org.scribble.core.type.session.Recursion; +import org.scribble.core.type.session.SType; +import org.scribble.core.type.session.SigLit; +import org.scribble.core.type.session.local.LAcc; +import org.scribble.core.type.session.local.LContinue; +import org.scribble.core.type.session.local.LDisconnect; +import org.scribble.core.type.session.local.LRecursion; +import org.scribble.core.type.session.local.LRecv; +import org.scribble.core.type.session.local.LReq; +import org.scribble.core.type.session.local.LSend; +import org.scribble.core.type.session.local.LSeq; +import org.scribble.core.type.session.local.LType; +import org.scribble.core.visit.STypeVisitorNoThrow; + +// Pre: use on inlined or later (unsupported for Do, also Protocol) +// Uses EGraphBuilderUtil2 to build graph "progressively" (working graph is mutable) +// Must use build as top-level call (does EGraphBuilderUtil2.finalise -- "resets" the util) +public class EGraphBuilder extends STypeVisitorNoThrow +{ + public final Core core; + + private EGraphBuilderUtil util; + + protected EGraphBuilder(Core core) + { + this.core = core; + this.util = core.config.mf.local.EGraphBuilderUtil(); + } + + public EGraph finalise() + { + return this.util.finalise(); + } + + @Override + public SType visitChoice(Choice n) + { + EGraphBuilderUtil util = this.util; + util.enterChoice(); + for (LSeq block : n.blocks) + { + List elems = block.getElements(); + LType first = elems.get(0); + if (first instanceof LContinue) + { + // Cannot treat choice-unguarded-continue in "a single pass", because may not have built all recursion enacting edges yet + // (Single-pass building would be sensitive to order of choice block visiting) + LContinue cont = (LContinue) first; // First and only element + util.addUnguardedContinueEdge(util.getEntry(), cont.recvar); + } + else if (first instanceof LRecursion) // CHECKME: do this here? refactor into builderutil? + { + buildUnguardedRecursion(util, elems); + } + else + { + util.enterChoiceBlock(); + block.visitWithNoThrow(this); + util.leaveChoiceBlock(); + } + } + util.leaveChoice(); + return n; + } + + // Recursion is first element of choice case + private void buildUnguardedRecursion(EGraphBuilderUtil util, + List elems) + { + LRecursion first = (LRecursion) elems.get(0); + EState entry = util.getEntry(); + + EState nestedEntry = util.newState(Collections.emptySet()); + util.setEntry(nestedEntry); + if (elems.size() == 1) // Cf. visitSeq last element or not + { + first.visitWithNoThrow(this); + } + else + { + EState exit = util.getExit(); + EState nestedExit = util.newState(Collections.emptySet()); + util.setExit(nestedExit); + first.visitWithNoThrow(this); // entry to nestedExit -- reuse existing builder, to directly add continue-edges back to the "outer" graph + + util.setEntry(nestedExit); // Must be non null + util.setExit(exit); + LSeq tail = this.core.config.tf.local.LSeq(null, + elems.subList(1, elems.size())); + tail.visitWithNoThrow(this); // nestedExit to exit + } + + Iterator as = nestedEntry.getActions().iterator(); // "Enacting" actions + Iterator succs = nestedEntry.getSuccs().iterator(); + while (as.hasNext()) + { + EAction a = as.next(); + EState succ = succs.next(); + util.addEdge(entry, a, succ); // Add edges from original entry into "nested" graph, offset by enacting to nestedEntry succs + } + + util.setEntry(entry); // EGraphBuilderUtil contract, entry on leaving a node should be the same as on entering + } + + @Override + public SType visitContinue(Continue n) + { + // Choice-guarded continue -- choice-unguarded continue detected and handled above in visitChoice + EState curr = this.util.getEntry(); + for (EState pred : this.util.getPreds(curr)) // Does getSuccs (i.e., gets all), e.g., choice sequenced to continue + { + // CHECKME: identical edges? i.e. same pred/prev/succ (e.g. rec X { choice at A { A->B:1 } or { A->B:1 } continue X; }) + for (EAction a : new LinkedList<>(pred.getActions())) + { + // Following caters for non-det edges (to different succs) + for (EState succ : pred.getSuccs(a)) + { + if (succ.equals(curr)) + { + this.util.fixContinueEdge(pred, a, curr, n.recvar); + } + } + } + } + return n; + } + + @Override + public SType visitDirectedInteraction( + DirectedInteraction n) + { + Role peer = ((n instanceof LSend) || (n instanceof LReq)) ? n.dst // CHECKME: refactor LType getSelf/Peer? cf. ast + : ((n instanceof LRecv) || (n instanceof LAcc)) ? n.src + : null; + if (peer == null) + { + throw new RuntimeException("Unknown action type: " + n); + } + MsgId mid = n.msg.getId(); + Payload pay = n.msg.isSigLit() // CHECKME: generalise? (e.g., hasPayload) + ? ((SigLit) n.msg).payload + : Payload.EMPTY_PAYLOAD; + // TODO: add toAction method to BasicInteraction (cf. toName methods of NameNodes) + EAction a = (n instanceof LSend) ? this.util.mf.local.ESend(peer, mid, pay) + : (n instanceof LRecv) ? this.util.mf.local.ERecv(peer, mid, pay) + : (n instanceof LReq) ? this.util.mf.local.EReq(peer, mid, pay) + : //(n instanceof LAcc) ? + this.util.mf.local.EAcc(peer, mid, pay); // Action type already checked above + this.util.addEdge(this.util.getEntry(), a, this.util.getExit()); + return n; + } + + @Override + public SType visitDisconnect(DisconnectAction n) + { + Role peer = ((LDisconnect) n).getPeer(); // CHECKME -- ? + EAction a = this.util.mf.local.EDisconnect(peer); // TODO: add toAction method to BasicInteraction + this.util.addEdge(this.util.getEntry(), a, this.util.getExit()); + return n; + } + + @Override + public final SType visitDo(Do n) + { + throw new RuntimeException(this.getClass() + " unsupported for Do: " + n); + } + + @Override + public SType visitRecursion(Recursion n) + { + this.util.addEntryLabel(n.recvar); + this.util.enterRecursion(n.recvar, this.util.getEntry()); + n.body.visitWithNoThrow(this); + this.util.leaveRecursion(n.recvar); + return n; + } + + @Override + public LSeq visitSeq(LSeq n) + { + EGraphBuilderUtil util = this.util; + EState entry = util.getEntry(); + EState exit = util.getExit(); + List elems = n.getElements(); + if (elems.isEmpty()) + { + throw new RuntimeException("Shouldn't get here: " + this); + } + for (Iterator i = n.getElements().iterator(); i.hasNext(); ) + { + LType next = i.next(); + if (!i.hasNext()) + { + util.setExit(exit); + next.visitWithNoThrow(this); + } + else + { + EState tmp = util.newState(Collections.emptySet()); + util.setExit(tmp); + next.visitWithNoThrow(this); + util.setEntry(util.getExit()); + // CHECKME: exit may not be tmp, entry/exit can be modified, e.g. continue + } + } + util.setEntry(entry); // EGraphBuilderUtil contract, entry on leaving a node should be the same as on entering + return n; + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/visit/local/InlinedExtChoiceSubjFixer.java b/scribble-core/src/main/java/org/scribble/core/visit/local/InlinedExtChoiceSubjFixer.java new file mode 100644 index 000000000..ac476256e --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/visit/local/InlinedExtChoiceSubjFixer.java @@ -0,0 +1,171 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.visit.local; + +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.scribble.core.type.kind.Local; +import org.scribble.core.type.name.RecVar; +import org.scribble.core.type.name.Role; +import org.scribble.core.type.session.Choice; +import org.scribble.core.type.session.Continue; +import org.scribble.core.type.session.DirectedInteraction; +import org.scribble.core.type.session.Do; +import org.scribble.core.type.session.Recursion; +import org.scribble.core.type.session.SType; +import org.scribble.core.type.session.local.LSeq; +import org.scribble.core.visit.STypeAggNoThrow; +import org.scribble.core.visit.STypeVisitorNoThrow; + +// Easier to separate from InlinedProjector (i.e., finish projection first, then fix) +// (Doing "at the time" during projection requires, e.g., recursion body projections for "inference" on recursion entry, but the body can't really be projected yet without that upfront "inference") +public class InlinedExtChoiceSubjFixer extends STypeVisitorNoThrow +{ + protected final Map> recs = new HashMap<>(); + // Record on entering rec states, to give to InlinedEnablerInferer on nested choice states (for unguarded continues) + // CHECKME: Optional necessary? InlinedEnablerInferer may not succeed due to empty/bad contexts, but should that be reflected here? + + protected InlinedExtChoiceSubjFixer() + { + + } + + // To override for handling subproto + // Takes "this" (cf. this.recs), better pattern for extensibility + protected InlinedEnablerInferer getInferer(InlinedExtChoiceSubjFixer v)//Map> recs) + { + return new InlinedEnablerInferer(this); + } + + @Override + public Choice visitChoice(Choice n) + { + InlinedEnablerInferer v = getInferer(this); + Role subj = n.visitWithNoThrow(v).get(); // WF ensures result + return n.reconstruct(n.getSource(), subj, n.blocks); + } + + @Override + public SType visitDo(Do n) + { + throw new RuntimeException("Unsupported for Do: " + n); + } + + @Override + public Recursion visitRecursion(Recursion n) + { + InlinedEnablerInferer v = getInferer(this); // Pattern: Inferer to access (and copy) this.recs directly + Optional res = v.visitSeq(n.body); // Can be empty or OK + this.recs.put(n.recvar, res); + LSeq body = visitSeq(n.body); + return n.reconstruct(n.getSource(), n.recvar, body); + } +} + +class InlinedEnablerInferer extends STypeAggNoThrow> + // Optional.empty signifies "inference" did not succeed, either an outright bad (should be caught by WF somewhere) or an "empty" context +{ + private final Map> recs; + + public InlinedEnablerInferer(InlinedExtChoiceSubjFixer v)//Map> recs) + { + this.recs = Collections.unmodifiableMap(v.recs); + } + + @Override + public Optional visitChoice(Choice n) + { + // If inference does not succeed, keep the original + // Such bad cases due, e.g., any inconsistency, will be caught as bad WF somewhere else (e.g., reachability) + // Otherwise, should be "empty" cases, so keep original as a default + List> enablers = n.blocks.stream().map(x -> visitSeq(x)) + .collect(Collectors.toList()); // Each elem is null, empty or isPresent + if (enablers.stream().anyMatch(x -> !x.isPresent())) + { + //return Optional.empty(); + return Optional.of(n.subj); + // CHECKME: can enablers be empty? i.e., choice was "empty" somehow? + // Yes, when not assuming, e.g., empty block filtering by InlinedProject + } + Set rs = enablers.stream().map(x -> x.get()) + .collect(Collectors.toSet()); + return Optional.of(rs.size() > 1 ? n.subj : rs.iterator().next()); + } + + @Override + public Optional visitContinue(Continue n) + { + return this.recs.containsKey(n.recvar) + ? this.recs.get(n.recvar) + : Optional.empty(); + // Empty corner case, e.g., bad sequence after unguarded continue (will be caught be reachability, e.g., bad.reach.globals.gdo.Test04) + // Empty allows (bad) Seq to continue to next element + } + + @Override + public Optional visitDirectedInteraction( + DirectedInteraction n) + { + return Optional.of(n.src); + } + + @Override + public Optional visitDo(Do n) + { + throw new RuntimeException("Unsupported for Do: " + n); + } + + @Override + public Optional visitSeq(LSeq n) + { + for (SType e : n.elems) + { + Optional res = e.visitWithNoThrow(this); + if (res.isPresent()) + { + return res; + } + } + return Optional.empty(); + } + + @Override + protected Optional unit(SType n) + { + return Optional.empty(); + } + + // Currently only used by Recursion, Choice/Seq overrides don't use + @Override + protected Optional agg(SType n, Stream> ts) + { + List> enabs = ts.collect(Collectors.toList()); + if (enabs.stream().anyMatch(x -> !x.isPresent())) + { + return Optional.empty(); + // CHECKME: can enablers be empty? i.e., choice was "empty" somehow? + // Yes, when not assuming, e.g., empty block filtering by InlinedProject + } + Set rs = enabs.stream().map(x -> x.get()) + .collect(Collectors.toSet()); + return rs.size() > 1 ? Optional.empty() : Optional.of(rs.iterator().next()); + } +} \ No newline at end of file diff --git a/scribble-core/src/main/java/org/scribble/core/visit/local/LDoPruner.java b/scribble-core/src/main/java/org/scribble/core/visit/local/LDoPruner.java new file mode 100644 index 000000000..ebc1f717a --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/visit/local/LDoPruner.java @@ -0,0 +1,141 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.visit.local; + +import java.util.Deque; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; + +import org.scribble.core.job.Core; +import org.scribble.core.lang.SubprotoSig; +import org.scribble.core.lang.local.LProtocol; +import org.scribble.core.type.kind.Local; +import org.scribble.core.type.name.Role; +import org.scribble.core.type.session.Choice; +import org.scribble.core.type.session.Do; +import org.scribble.core.type.session.Recursion; +import org.scribble.core.type.session.SType; +import org.scribble.core.type.session.local.LSeq; +import org.scribble.core.type.session.local.LSkip; +import org.scribble.core.type.session.local.LType; +import org.scribble.core.visit.STypeVisitorNoThrow; + + + +// Pre: LRoleDeclAndDoArgFixer (for LSubprotoVisitorNoThrow visiting pattern) +// Cf. RecPruner +public class LDoPruner //extends DoPruner + extends STypeVisitorNoThrow + implements LSubprotoVisitorNoThrow> +{ + protected final Core core; + + private Role self; + + protected final Deque stack; + + protected final Set unguarded; // Cf. InlinedProjector (unguarded-continue pruning) + + protected LDoPruner(Core core) + { + this.core = core; + this.stack = new LinkedList<>(); + this.unguarded = new HashSet<>(); + } + + protected LDoPruner(LDoPruner v) + { + this.core = v.core; + this.self = v.self; + this.stack = new LinkedList<>(v.stack); + this.unguarded = new HashSet<>(v.unguarded); + } + + // Top-level entry, different to the other visit methods + public LProtocol visitLProtocol(LProtocol n) + { + this.self = n.self; + this.stack.clear(); + this.unguarded.clear(); + + SubprotoSig sig = new SubprotoSig(n); // N.B. overloaded constructor, param type important + this.stack.push(sig); + this.unguarded.add(sig); + LSeq def = visitSeq(n.def); + return n.reconstruct(n.getSource(), n.mods, n.fullname, n.roles, n.self, + n.params, def); + } + + @Override + public SType visitChoice(Choice n) + { + // Duplicated from InlinedProjector.visitChoice + List blocks = n.blocks.stream() + .map(x -> new LDoPruner(this).visitSeq(x)).filter(x -> !x.isEmpty()) + .collect(Collectors.toList()); + if (blocks.isEmpty()) + { + return LSkip.SKIP; // N.B. returning a Seq -- handled by visitSeq (similar to LSkip for locals) + } + this.unguarded.remove(this.stack.peek()); + return n.reconstruct(n.getSource(), n.subj, blocks); + } + + @Override + public SType visitDo(Do n) + { + SubprotoSig sig = new SubprotoSig(n.proto, n.roles, n.args); + if (this.stack.contains(sig)) + { + return this.unguarded.contains(sig) ? LSkip.SKIP : n; + } + + // Duplicated from SubprotoRoleCollector + this.stack.push(sig); + LSeq def = visitSeq(prepareSubprotoForVisit(this.core, n, true)); + // true (passive) to ignore non-fixed ext-choice subjs (e.g., good.efsm.gdo.Test11) + // Changes ultimately discarded: "nested" entries only do "info collection", actual AST modifications only recoded for the top-level Projection (cf. visitProjection) + this.stack.pop(); + return def.isEmpty() ? LSkip.SKIP : n; // Cf. unit(n) + } + + @Override + public SType visitRecursion(Recursion n) + { + LSeq body = visitSeq(n.body); + return body.isEmpty() + ? LSkip.SKIP + : n.reconstruct(n.getSource(), n.recvar, body); + } + + @Override + public LSeq visitSeq(LSeq n) + { + // Duplicated from InlinedProjector.visitSeq + List elems = new LinkedList<>(); + for (LType e : n.getElements()) + { + LType e1 = (LType) e.visitWithNoThrow(this); + if (!(e1 instanceof LSkip)) + { + elems.add(e1); + this.unguarded.clear(); + } + } + return this.core.config.tf.local.LSeq(null, elems); + } +} \ No newline at end of file diff --git a/scribble-core/src/main/java/org/scribble/core/visit/local/LRoleDeclAndDoArgPruner.java b/scribble-core/src/main/java/org/scribble/core/visit/local/LRoleDeclAndDoArgPruner.java new file mode 100644 index 000000000..5dd2a9fd2 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/visit/local/LRoleDeclAndDoArgPruner.java @@ -0,0 +1,171 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.visit.local; + +import java.util.Collections; +import java.util.Deque; +import java.util.LinkedList; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.scribble.core.job.Core; +import org.scribble.core.lang.SubprotoSig; +import org.scribble.core.lang.local.LProjection; +import org.scribble.core.lang.local.LProtocol; +import org.scribble.core.type.kind.Local; +import org.scribble.core.type.name.Role; +import org.scribble.core.type.session.DirectedInteraction; +import org.scribble.core.type.session.DisconnectAction; +import org.scribble.core.type.session.Do; +import org.scribble.core.type.session.SType; +import org.scribble.core.type.session.local.LSeq; +import org.scribble.core.visit.STypeAggNoThrow; +import org.scribble.core.visit.STypeVisitorNoThrow; +import org.scribble.core.visit.Substitutor; + +// Pre: SubprotoProjector -- "self" fixed for interactions, choice-subjs and do role-args +// Prunes LProto/Proj role decls and do role-args +public class LRoleDeclAndDoArgPruner extends STypeVisitorNoThrow +{ + private final Core core; + + protected LRoleDeclAndDoArgPruner(Core core) + { + this.core = core; + } + + // CHECKME: vf? + protected PreSubprotoRoleCollector newPreRoleCollector() // N.B. "Pre" role collector + { + return new PreSubprotoRoleCollector(this.core); + } + + public LProtocol visitLProtocol(LProtocol n) + { + // N.B. must use PreRoleCollector (on orig), standard subproto traversal not possible yet because target proto role decls not yet fixed (being done now) + Set used = n.def.visitWithNoThrow(newPreRoleCollector()); // CHECKME: vf? + List rs = n.roles.stream() + .filter(x -> used.contains(x) || x.equals(n.self)) // FIXME: self roledecl not actually being a self role is a mess + .collect(Collectors.toList()); + // N.B. *role decls* (cf. do-args) don't feature "self" (cf. LSelfDecl) + LSeq pruned = visitSeq(n.def); + return n.reconstruct(n.getSource(), n.mods, n.fullname, rs, n.self, + n.params, pruned); // CHECKME: prune params? + } + + public Do visitDo(Do n) + { + List fixed = new LinkedList<>(); + Set rs = n.visitWithNoThrow(newPreRoleCollector()); // N.B. does subproto visiting, unlike RoleGatherer + fixed = n.roles.stream() + /*.filter(x -> rs.contains(x) || x.equals(this.self)) + .map(x -> x.equals(this.self) ? Role.SELF : x) // FIXME: self roledecl not actually being a self role is a mess*/ + .filter(x -> rs.contains(x) || x.equals(Role.SELF)) + .collect(Collectors.toList()); + return n.reconstruct(n.getSource(), n.proto, fixed, n.args); // CHECKME: prune args? + } +} + + +// Role collector for pre do-arg pruning (i.e., only for use by LDoArgPruner): +// do-arg arity doesn't yet match target, and "self" not done in do-args (see InlinedProjector.visitDo) +class PreSubprotoRoleCollector extends SubprotoRoleCollector +{ + public PreSubprotoRoleCollector(Core core) + { + super(core); + } + + @Override + public Set visitDo(Do n) + { + SubprotoSig sig = new SubprotoSig(n.proto, n.roles, n.args); + if (this.stack.contains(sig)) + { + return unit(n); // empty set + } + + this.stack.push(sig); + LProjection target = (LProjection) n.getTarget(this.core); + List tmp = this.core.getContext().getInlined(target.global).roles + // Currently, do-args arity matches that of inlined, i.e., not necessarily the arity of the actual local target (cf. InlinedProjector.visitDo) + .stream()//.map(x -> x.equals(target.self) ? Role.SELF : x) + // "self" for do-args not done yet (cf., SubprotoProjector.visitDo), now being fixed by LDoArgPruner + // Cf., LSubprotoVisitorNoThrow.prepareSubprotoForVisit + .collect(Collectors.toList()); + Substitutor subs = this.core.config.vf + .Substitutor(tmp, n.roles, target.params, n.args, true); // true (passive) to ignore "self" // CHECKME: prune args? + Set res = target.def.visitWithNoThrow(subs).visitWithNoThrow(this); + this.stack.pop(); + return res; + } +} + + +// CHECKME: simply integrate into one with PreSubprotoRoleCollector? Or maybe still separately useful? +class SubprotoRoleCollector extends STypeAggNoThrow> + implements LSubprotoVisitorNoThrow> +{ + protected final Core core; + + protected Deque stack = new LinkedList<>(); + + public SubprotoRoleCollector(Core core) + { + this.core = core; + } + + @Override + public Set visitDirectedInteraction(DirectedInteraction n) + { + return Stream.of(n.src, n.dst).collect(Collectors.toSet()); + } + + @Override + public Set visitDisconnect(DisconnectAction n) + { + return Stream.of(n.left, n.right).collect(Collectors.toSet()); + } + + @Override + public Set visitDo(Do n) + { + SubprotoSig sig = new SubprotoSig(n.proto, n.roles, n.args); + if (this.stack.contains(sig)) + { + return unit(n); // empty set + } + + // Cf. LDoPruner.visitDo + this.stack.push(sig); + Set res = prepareSubprotoForVisit(this.core, n) // Non-passive, cf. PreSubprotoRoleCollector + .visitWithNoThrow(this); + this.stack.pop(); + return res; + } + + @Override + protected Set unit(SType n) + { + return Collections.emptySet(); + } + + @Override + protected Set agg(SType n, Stream> ts) + { + return ts.flatMap(x -> x.stream()).collect(Collectors.toSet()); + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/visit/local/LSubprotoVisitorNoThrow.java b/scribble-core/src/main/java/org/scribble/core/visit/local/LSubprotoVisitorNoThrow.java new file mode 100644 index 000000000..f0ea92a1e --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/visit/local/LSubprotoVisitorNoThrow.java @@ -0,0 +1,51 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.visit.local; + +import java.util.List; +import java.util.stream.Collectors; + +import org.scribble.core.job.Core; +import org.scribble.core.lang.local.LProtocol; +import org.scribble.core.type.kind.Local; +import org.scribble.core.type.name.Role; +import org.scribble.core.type.session.Do; +import org.scribble.core.type.session.local.LSeq; +import org.scribble.core.visit.Substitutor; + + +// Pre: LRoleDeclAndDoArgFixer (for imed LProjections) +public interface LSubprotoVisitorNoThrow // T should be SType for STypeVisitor +{ + + // Subclasses of "Inlined" visitors should re-override using prepareSubprotoForVisit -- cf. LSubprotoVisitorNoThrow.super.visitDo(n) + T visitDo(Do n); + + default LSeq prepareSubprotoForVisit(Core core, Do n) + { + return prepareSubprotoForVisit(core, n, false); + } + + default LSeq prepareSubprotoForVisit(Core core, Do n, + boolean passive) + { + LProtocol target = (LProtocol) n.getTarget(core); + List tmp = target.roles.stream() + .map(x -> x.equals(target.self) ? Role.SELF : x) // FIXME: self roledecl not actually being a self role is a mess + .collect(Collectors.toList()); + Substitutor subs = core.config.vf + .Substitutor(tmp, n.roles, target.params, n.args, passive); + return subs.visitSeq(target.def); + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/visit/local/LTypeInliner.java b/scribble-core/src/main/java/org/scribble/core/visit/local/LTypeInliner.java new file mode 100644 index 000000000..edc9b5d68 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/visit/local/LTypeInliner.java @@ -0,0 +1,55 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.visit.local; + +import org.scribble.core.job.Core; +import org.scribble.core.lang.SubprotoSig; +import org.scribble.core.lang.local.LProtocol; +import org.scribble.core.type.kind.Local; +import org.scribble.core.type.name.ProtoName; +import org.scribble.core.type.name.RecVar; +import org.scribble.core.type.session.Do; +import org.scribble.core.type.session.local.LSeq; +import org.scribble.core.type.session.local.LType; +import org.scribble.core.visit.STypeInliner; +import org.scribble.core.visit.Substitutor; + +public class LTypeInliner extends STypeInliner +{ + protected LTypeInliner(Core core) + { + super(core); + } + + @Override + public LType visitDo(Do n) + { + ProtoName fullname = n.proto; + SubprotoSig sig = new SubprotoSig(fullname, n.roles, n.args); + RecVar rv = getInlinedRecVar(sig); + if (hasSig(sig)) + { + return this.core.config.tf.local.LContinue(n.getSource(), rv); + } + pushSig(sig); + LProtocol p = this.core.getContext().getProjection(fullname); // This line differs from GDo version + Substitutor subs = this.core.config.vf.Substitutor(p.roles, + n.roles, p.params, n.args); + //LSeq inlined = (LSeq) p.def.visitWithNoThrow(subs).visitWithNoThrow(this); + LSeq inlined = visitSeq(subs.visitSeq(p.def)); + // i.e. returning a Seq -- rely on parent Seq to inline + popSig(); + return this.core.config.tf.local.LRecursion(null, rv, inlined); + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/visit/local/LTypeUnfolder.java b/scribble-core/src/main/java/org/scribble/core/visit/local/LTypeUnfolder.java new file mode 100644 index 000000000..63fdaa466 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/visit/local/LTypeUnfolder.java @@ -0,0 +1,37 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.visit.local; + +import org.scribble.core.job.Core; +import org.scribble.core.type.kind.Local; +import org.scribble.core.type.session.Continue; +import org.scribble.core.type.session.local.LSeq; +import org.scribble.core.type.session.local.LType; +import org.scribble.core.visit.STypeUnfolder; + +public class LTypeUnfolder extends STypeUnfolder +{ + + protected LTypeUnfolder(Core core) + { + super(core); + } + + @Override + public LType visitContinue(Continue n) + { + return this.core.config.tf.local.LRecursion(n.getSource(), n.recvar, + (LSeq) getRec(n.recvar)); + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/visit/local/LTypeVisitorFactory.java b/scribble-core/src/main/java/org/scribble/core/visit/local/LTypeVisitorFactory.java new file mode 100644 index 000000000..c525340b6 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/visit/local/LTypeVisitorFactory.java @@ -0,0 +1,32 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.visit.local; + +import org.scribble.core.job.Core; + +public interface LTypeVisitorFactory +{ + + InlinedExtChoiceSubjFixer InlinedExtChoiceSubjFixer(); + + ReachabilityChecker ReachabilityChecker(); + + EGraphBuilder EGraphBuilder(Core core); + + LRoleDeclAndDoArgPruner LDoArgPruner(Core core); + + LDoPruner LDoPruner(Core core); + + SubprotoExtChoiceSubjFixer SubprotoExtChoiceSubjFixer(Core core); +} diff --git a/scribble-core/src/main/java/org/scribble/core/visit/local/LTypeVisitorFactoryImpl.java b/scribble-core/src/main/java/org/scribble/core/visit/local/LTypeVisitorFactoryImpl.java new file mode 100644 index 000000000..c39307d12 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/visit/local/LTypeVisitorFactoryImpl.java @@ -0,0 +1,56 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.visit.local; + +import org.scribble.core.job.Core; + +public class LTypeVisitorFactoryImpl implements LTypeVisitorFactory +{ + + @Override + public InlinedExtChoiceSubjFixer InlinedExtChoiceSubjFixer() + { + return new InlinedExtChoiceSubjFixer(); + } + + @Override + public ReachabilityChecker ReachabilityChecker() + { + return new ReachabilityChecker(); + } + + @Override + public EGraphBuilder EGraphBuilder(Core core) + { + return new EGraphBuilder(core); + } + + @Override + public LRoleDeclAndDoArgPruner LDoArgPruner(Core core) + { + return new LRoleDeclAndDoArgPruner(core); + } + + @Override + public LDoPruner LDoPruner(Core core) + { + return new LDoPruner(core); + } + + @Override + public SubprotoExtChoiceSubjFixer SubprotoExtChoiceSubjFixer(Core core) + { + return new SubprotoExtChoiceSubjFixer(core); + } +} diff --git a/scribble-core/src/main/java/org/scribble/core/visit/local/ReachabilityChecker.java b/scribble-core/src/main/java/org/scribble/core/visit/local/ReachabilityChecker.java new file mode 100644 index 000000000..55711faf6 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/visit/local/ReachabilityChecker.java @@ -0,0 +1,148 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.visit.local; + +import java.util.Collections; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; + +import org.scribble.core.type.kind.Local; +import org.scribble.core.type.name.RecVar; +import org.scribble.core.type.session.Choice; +import org.scribble.core.type.session.Continue; +import org.scribble.core.type.session.Do; +import org.scribble.core.type.session.Recursion; +import org.scribble.core.type.session.SType; +import org.scribble.core.type.session.local.LSeq; +import org.scribble.core.type.session.local.LType; +import org.scribble.core.visit.STypeVisitor; +import org.scribble.util.ScribException; + +// Pre: use on inlined or later (unsupported for Do, also Protocol) +public class ReachabilityChecker extends STypeVisitor +{ + private ReachabilityEnv env; // Immutable + + protected ReachabilityChecker() + { + this.env = new ReachabilityEnv(false, Collections.emptySet()); + } + + @Override + public SType visitChoice(Choice n) + throws ScribException + { + ReachabilityEnv entry = getEnv(); + List blocks = new LinkedList<>(); + ReachabilityChecker nested = new ReachabilityChecker(); + for (LSeq block : n.blocks) + { + nested.setEnv(entry); + nested.visitSeq(block);//block.visitWith(nested); + blocks.add(nested.getEnv()); + } + boolean postcont = blocks.stream().allMatch(x -> x.postcont); // i.e., no exits + Set recvars = blocks.stream().flatMap(x -> x.recvars.stream()) + .collect(Collectors.toSet()); + setEnv(new ReachabilityEnv(postcont, recvars)); + return n; + } + + public SType visitContinue(Continue n) throws ScribException + { + ReachabilityEnv env = getEnv(); + Set tmp = new HashSet<>(env.recvars); + tmp.add(n.recvar); + setEnv(new ReachabilityEnv(true, tmp)); + return n; + } + + @Override + public final SType visitDo(Do n) throws ScribException + { + throw new RuntimeException(this.getClass() + " unsupported for Do: " + n); + } + + @Override + public SType visitRecursion(Recursion n) + throws ScribException + { + n.body.visitWith(this); + ReachabilityEnv env = getEnv(); + if (env.recvars.contains(n.recvar)) + { + Set tmp = new HashSet<>(env.recvars); + tmp.remove(n.recvar); + setEnv(new ReachabilityEnv(env.postcont, tmp)); + } + return n; + } + + @Override + public LSeq visitSeq(LSeq n) + throws ScribException + { + LType prev = null; + LType next = null; + for (Iterator i = n.getElements().iterator(); i.hasNext(); ) + { + prev = next; + next = i.next(); + ReachabilityEnv env = getEnv(); + if (!env.isSeqable()) + { + throw new ScribException( + "Illegal sequence: " + (prev == null ? "" : prev + "\n") + next); + } + next.visitWith(this); + } + return n; + } + + protected ReachabilityEnv getEnv() + { + return this.env; + } + + protected void setEnv(ReachabilityEnv env) + { + this.env = env; + } +} + + +// Immutable +class ReachabilityEnv +{ + // For checking bad sequencing of unreachable code: false after a continue; true if choice has an exit (false inherited for all other constructs) + public final boolean postcont; + + // For checking "reachable code" also satisfies tail recursion (e.g., after choice-with-exit) + public final Set recvars; + + public ReachabilityEnv(boolean postcont, Set recvars) + { + this.postcont = postcont; + this.recvars = Collections.unmodifiableSet(recvars); + } + + public boolean isSeqable() + { + return !this.postcont && this.recvars.isEmpty(); + } +} \ No newline at end of file diff --git a/scribble-core/src/main/java/org/scribble/core/visit/local/SubprotoExtChoiceSubjFixer.java b/scribble-core/src/main/java/org/scribble/core/visit/local/SubprotoExtChoiceSubjFixer.java new file mode 100644 index 000000000..70f546172 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/core/visit/local/SubprotoExtChoiceSubjFixer.java @@ -0,0 +1,101 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.core.visit.local; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; + +import org.scribble.core.job.Core; +import org.scribble.core.lang.Protocol; +import org.scribble.core.type.kind.Local; +import org.scribble.core.type.name.LProtoName; +import org.scribble.core.type.name.Role; +import org.scribble.core.type.session.Do; +import org.scribble.core.type.session.SType; +import org.scribble.core.type.session.local.LSeq; + +// Pre: LRoleDeclAndDoArgFixer (for LSubprotoVisitorNoThrow visiting pattern), LDoPruner (to avoid infinite looping when "stackless" subproto visiting) +// super takes care of rec/continue, here just additionally handle "do" +// A "stackless" subproto visitor, c.f. LDoPruner +public class SubprotoExtChoiceSubjFixer extends InlinedExtChoiceSubjFixer +{ + protected final Core core; + + protected final Map> protos = new HashMap<>(); + + protected SubprotoExtChoiceSubjFixer(Core core) + { + this.core = core; + } + + // To visit top-level proto, reconstruct for fixed subjs -- nested visting (by Inferer) only does passive inference (no reconstruct) + // Must enter here, for initial this.protos entry + public Protocol visitProtocol( + Protocol n) + { + this.protos.clear(); // Reusable + + // Cf. InlinedExtChoiceSubjFixer.visitRecursion + InlinedEnablerInferer v = getInferer(this); + Optional res = v.visitSeq(n.def); + this.protos.put(n.fullname, res); + LSeq def = visitSeq(n.def); + return n.reconstruct(n.getSource(), n.mods, n.fullname, n.roles, n.params, + def); + // N.B. this reconstruct implicitly retains n.self + } + + @Override + protected SubprotoEnablerInferer getInferer(InlinedExtChoiceSubjFixer v) + { + return new SubprotoEnablerInferer(v); + } + + @Override + public SType visitDo(Do n) + { + return unit(n); // From STypeAggNoThrow + } +} + +class SubprotoEnablerInferer extends InlinedEnablerInferer // super takes care of rec/continue + implements LSubprotoVisitorNoThrow> +{ + private final Core core; + + private final Map> protos; + + public SubprotoEnablerInferer(InlinedExtChoiceSubjFixer v) + { + super(v); + SubprotoExtChoiceSubjFixer cast = (SubprotoExtChoiceSubjFixer) v; + this.core = cast.core; + this.protos = Collections.unmodifiableMap(cast.protos); + } + + @Override + public Optional visitDo(Do n) + { + if (this.protos.containsKey(n.proto)) + { + return this.protos.get(n.proto); + } + + // Cf. LDoPruner.visitDo + return visitSeq(prepareSubprotoForVisit(this.core, n, true)); + // true (passive) for fixing ext-choice subjs (e.g., bad.liveness.roleprog.unfair.Test06) + } +} diff --git a/scribble-core/src/main/java/org/scribble/util/AntlrSourceException.java b/scribble-core/src/main/java/org/scribble/util/AntlrSourceException.java new file mode 100644 index 000000000..4ab03191b --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/util/AntlrSourceException.java @@ -0,0 +1,81 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.util; + +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +import org.antlr.runtime.tree.CommonTree; + +public class AntlrSourceException extends Exception +{ + /** + * + */ + private static final long serialVersionUID = 1L; + + public AntlrSourceException() + { + // TODO Auto-generated constructor stub + } + + public AntlrSourceException(CommonTree blame, String arg0) + { + // char position indexes are obscure because only certain (child) nodes/tokens are actually recorded, e.g., name nodes (the keyword nodes, e.g., global, have been discarded) + // ...although even taking the above into account, indexes still seem off? -- may be due to tabs (counted as single chars) + super(getRootModuleName(blame) + "(line " + blame.getLine() + ":" + + (blame.getCharPositionInLine()) + "): " + arg0); + // Cf., getTokenStartIndex/getTokenStopIndex ? blame.token.getCharPositionInLine()? + } + + // Cf., AntlrModule/AntlrModuleDecl -- but can't access parser classes from core (Maven dependencies) + protected static String getRootModuleName(CommonTree blame) // Means root of this CommonTree (not the Scribble job root, i.e. main) + { + CommonTree root = blame; + while (root.parent != null) + { + root = root.parent; + } + CommonTree moddecl = (CommonTree) root.getChild(0).getChild(0); + int count = moddecl.getChildCount(); + return IntStream.range(0, count) + .mapToObj(i -> moddecl.getChild(i).getText()) + .collect(Collectors.joining(".")); + } + + public AntlrSourceException(String arg0) + { + super(arg0); + // TODO Auto-generated constructor stub + } + + public AntlrSourceException(Throwable arg0) + { + super(arg0); + // TODO Auto-generated constructor stub + } + + public AntlrSourceException(String arg0, Throwable arg1) + { + super(arg0, arg1); + // TODO Auto-generated constructor stub + } + + public AntlrSourceException(String arg0, Throwable arg1, boolean arg2, + boolean arg3) + { + super(arg0, arg1, arg2, arg3); + // TODO Auto-generated constructor stub + } +} diff --git a/scribble-core/src/main/java/org/scribble/util/Caller.java b/scribble-core/src/main/java/org/scribble/util/Caller.java new file mode 100644 index 000000000..a15dd64c8 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/util/Caller.java @@ -0,0 +1,35 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.util; + +import java.util.concurrent.Callable; + +public class Caller +{ + public T call(Callable c) + { + try + { + return c.call(); + } + catch (Exception e) + { + if (e instanceof RuntimeException) + { + throw ((RuntimeException) e); + } + throw new RuntimeException(e); + } + } +} \ No newline at end of file diff --git a/scribble-core/src/main/java/org/scribble/util/ConnectedMap.java b/scribble-core/src/main/java/org/scribble/util/ConnectedMap.java new file mode 100644 index 000000000..2273b5942 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/util/ConnectedMap.java @@ -0,0 +1,232 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.util; + +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import org.scribble.core.type.name.Role; + +// FIXME: factor out with MessageIdMap +// FIXME: cf, WFBuffers.connected +// Mutable +public class ConnectedMap +{ + public static enum ConnectedStatus { TRUE, FALSE, AMBIG, } + + // dest -> (src -> isConnected) + private Map> map = new HashMap<>(); + + private static ConnectedStatus convertStatus(boolean b) + { + return b ? ConnectedStatus.TRUE : ConnectedStatus.FALSE; + } + + public ConnectedMap(Set roles, boolean implicit) + { + roles.forEach((k) -> + { + HashMap tmp = new HashMap<>(); + this.map.put(k, tmp); + roles.forEach((k2) -> + { + if (!k.equals(k2)) + { + tmp.put(k2, convertStatus(implicit)); + } + }); + }); + } + + public ConnectedMap(ConnectedMap map) + { + for (Role dest : map.getDestinations()) + { + for (Role src : map.map.get(dest).keySet()) + { + setConnected(dest, src, map.isConnected(dest, src)); + } + } + } + + // FIXME: refactor + public ConnectedMap merge(ConnectedMap them) + { + Map> ours = this.map; + Map> theirs = them.map; + ConnectedMap res = new ConnectedMap(Collections.emptySet(), false); + Set rs = new HashSet<>(ours.keySet()); // keySet should be sufficient + rs.addAll(theirs.keySet()); + for (Role r1 : rs) + { + for (Role r2 : rs) + { + if (this.containsRolePair(r1, r2)) + { + ConnectedStatus c1 = ours.get(r1).get(r2); + if (them.containsRolePair(r1, r2)) + { + ConnectedStatus c2 = theirs.get(r1).get(r2); + ConnectedStatus c = (c1 == c2) ? c1 : ConnectedStatus.AMBIG; + res.setConnected(r1, r2, c); + } + else + { + res.setConnected(r1, r2, c1); + } + } + else if (them.containsRolePair(r1, r2)) + { + ConnectedStatus c2 = theirs.get(r1).get(r2); + res.setConnected(r1, r2, c2); + } + } + } + /*/ + ConnectedMap res = new ConnectedMap(this); + for (Role r1 : them.getDestinations()) + { + for (Role r2 : them.getSources(r1)) + { + ConnectedStatus c2 = them.map.get(r1).get(r2); + if (this.containsRolePair(r1, r2)) + { + ConnectedStatus c1 = res.map.get(r1).get(r2); + ConnectedStatus c = (c1 == c2) ? c1 : ConnectedStatus.AMBIG; + res.setConnected(r1, r2, c); + } + else + { + res.setConnected(r1, r2, c2); + } + } + } + //*/ + return res; + } + + public void connect(Role dest, Role src) + { + setConnected(dest, src, true); + } + + public void disconnect(Role dest, Role src) + { + setConnected(dest, src, false); + } + + protected void setConnected(Role dest, Role src, ConnectedStatus status) + { + addRolePair(dest, src); + //this.map.get(dest).put(src, isConnected); + ConnectedStatus b = status; + this.map.get(dest).put(src, b); + addRolePair(src, dest); + this.map.get(src).put(dest, b); + } + + public void setConnected(Role dest, Role src, boolean isConnected) + { + setConnected(dest, src, convertStatus(isConnected)); + } + + public Set getDestinations() + { + return this.map.keySet(); + } + + public boolean containsDestination(Role dest) + { + return this.map.containsKey(dest); + } + + public Set getSources(Role dest) + { + return this.map.containsKey(dest) ? this.map.get(dest).keySet() : Collections.emptySet(); + } + + // FIXME: null guards not needed any more + public boolean isConnected(Role dest, Role src) + { + //Map tmp = this.map.get(dest); + Map tmp = this.map.get(dest); + if (tmp != null) + { + /*Boolean b = tmp.get(src); + return b != null && b;*/ + ConnectedStatus b = tmp.get(src); + return b == ConnectedStatus.TRUE; + } + return false; + } + + public boolean containsRolePair(Role dest, Role src) + { + return this.map.keySet().contains(dest) && this.map.get(dest).containsKey(src); + } + + public void clear() + { + this.map.clear(); + } + + private void addRolePair(Role dest, Role src) + { + if (!this.map.containsKey(dest)) + { + //Map map = new HashMap<>(); + Map map = new HashMap<>(); + this.map.put(dest, map); + //map.put(src, false); + map.put(src, ConnectedStatus.FALSE); + } + else if (!this.map.get(dest).containsKey(src)) + { + //this.map.get(dest).put(src, false); + //this.map.get(dest).put(src, false); + this.map.get(dest).put(src, ConnectedStatus.FALSE); + } + } + + @Override + public String toString() + { + return this.map.toString(); + } + + @Override + public int hashCode() + { + int hash = 1033; + hash = 31 * hash + super.hashCode(); + return hash; + } + + @Override + public boolean equals(Object o) + { + if (o == null) + { + return false; + } + if (!(o instanceof ConnectedMap)) + { + return false; + } + return this.map.equals(((ConnectedMap) o).map); + } +} diff --git a/scribble-core/src/main/java/org/scribble/util/Constants.java b/scribble-core/src/main/java/org/scribble/util/Constants.java new file mode 100644 index 000000000..610243763 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/util/Constants.java @@ -0,0 +1,60 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.util; + + +// FIXME: cannot use Antlr constants from org.scribble.parser (e.g., ScribbleParser) due to Maven dependency restrictions +public class Constants +{ + public static final String SCRIBBLE_FILE_EXTENSION = "scr"; // Used within core to obtain path from ModuleName for imports + + // Duplicated from AntlrConstants due to Maven dependency restrictions + public static final String MODULE_KW = "module"; + public static final String IMPORT_KW = "import"; + public static final String DATA_KW = "data"; + public static final String TYPE_KW = "type"; // CHECKME: deprecate ? + public static final String PROTOCOL_KW = "protocol"; + public static final String GLOBAL_KW = "global"; + public static final String LOCAL_KW = "local"; + public static final String ROLE_KW = "role"; + public static final String ACCEPT_KW = "accept"; + public static final String SELF_KW = "self"; + public static final String SIG_KW = "sig"; + public static final String INSTANTIATES_KW = "instantiates"; + public static final String AS_KW = "as"; + + public static final String CONNECT_KW = "connect"; + public static final String DISCONNECT_KW = "disconnect"; + public static final String WRAP_KW = "wrap"; + public static final String FROM_KW = "from"; + public static final String TO_KW = "to"; + public static final String CHOICE_KW = "choice"; + public static final String AT_KW = "at"; + public static final String OR_KW = "or"; + public static final String REC_KW = "rec"; + public static final String CONTINUE_KW = "continue"; + //public static final String PAR_KW = "par"; + public static final String AND_KW = "and"; + /*public static final String INTERRUPTIBLE_KW = "interruptible"; + public static final String WITH_KW = "with"; + public static final String BY_KW = "by"; + public static final String THROWS_KW = "throws"; + public static final String CATCHES_KW = "catches";*/ + public static final String DO_KW = "do"; + //public static final String SPAWN_KW = "spawn"; + + public static final String REQUEST_KW = "request"; + public static final String CLIENTWRAP_KW = "cwrap"; + public static final String SERVERWRAP_KW = "swrap"; +} diff --git a/scribble-core/src/main/java/org/scribble/util/MessageIdMap.java b/scribble-core/src/main/java/org/scribble/util/MessageIdMap.java new file mode 100644 index 000000000..6f8e95dc6 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/util/MessageIdMap.java @@ -0,0 +1,157 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.util; + +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import org.scribble.core.type.name.MsgId; +import org.scribble.core.type.name.Role; + +// Mutable +public class MessageIdMap +{ + // dest -> (src -> mids) + private Map>>> map = new HashMap<>(); + + public MessageIdMap() + { + + } + + public MessageIdMap(MessageIdMap map) + { + for (Role dest : map.getDestinations()) + { + for (Role src : map.map.get(dest).keySet()) + { + putMessages(dest, src, map.getMessages(dest, src)); + } + } + } + + /*public void merge(MessageIdMap map) + { + for (Role dest : map.getDestinations()) + { + for (Role src : map.getSources(dest)) + { + putMessages(dest, src, map.getMessages(dest, src)); + } + } + }*/ + + public void putMessage(Role dest, Role src, MsgId msg) + { + addRolePair(dest, src); + this.map.get(dest).get(src).add(msg); + } + + /*public void removeMessage(Role dest, Role src, MessageId msg) + { + addRolePair(dest, src); + this.map.get(dest).get(src).remove(msg); + }*/ + /*public void removeMessages(Role dest) + { + Map>> tmp = this.map.get(dest); + for (Role r : tmp.keySet()) + { + tmp.remove(r); + } + }*/ + + public void putMessages(Role dest, Role src, Set> msgs) + { + addRolePair(dest, src); + this.map.get(dest).get(src).addAll(msgs); + } + + public Set getDestinations() + { + return this.map.keySet(); + } + + public boolean containsDestination(Role dest) + { + return this.map.containsKey(dest); + } + + /*public boolean containsSource(Role src) + { + return getAllSources().contains(src); + }*/ + + public Set getSources(Role dest) + { + return this.map.containsKey(dest) ? this.map.get(dest).keySet() : Collections.emptySet(); + } + + /*public Set getAllSources() + { + Set srcs = new HashSet<>(); + this.map.keySet().forEach((dest) -> srcs.addAll(this.map.get(dest).keySet())); + return srcs; + }*/ + + public Set> getMessages(Role dest, Role src) + { + return this.map.get(dest).get(src); + } + + public Set> getMessages(Role dest) + { + Set> tmp = new HashSet<>(); + getSources(dest).forEach((src) -> tmp.addAll(getMessages(dest, src))); + return tmp; + } + + public boolean containsRolePair(Role dest, Role src) + { + return this.map.keySet().contains(dest) && this.map.get(dest).containsKey(src); + } + + /*public boolean containsMessageSignature(Role dest, Role src, Message msg) + { + return containsRolePair(dest, src) && getMessages(dest, src).contains(msg); + }*/ + + public void clear() + { + this.map.clear(); + } + + private void addRolePair(Role dest, Role src) + { + if (!this.map.containsKey(dest)) + { + Map>> map = new HashMap<>(); + this.map.put(dest, map); + map.put(src, new HashSet<>()); + } + else if (!this.map.get(dest).containsKey(src)) + { + this.map.get(dest).put(src, new HashSet<>()); + } + } + + @Override + public String toString() + { + return this.map.toString(); + } +} diff --git a/scribble-core/src/main/java/org/scribble/util/Pair.java b/scribble-core/src/main/java/org/scribble/util/Pair.java new file mode 100644 index 000000000..249590cb1 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/util/Pair.java @@ -0,0 +1,50 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.util; + +public class Pair +{ + public final T1 left; + public final T2 right; + + public Pair(T1 t1, T2 t2) + { + this.left = t1; + this.right = t2; + } + + @Override + public int hashCode() + { + int hash = 11; + hash = 31 * hash + this.left.hashCode(); + hash = 31 * hash + this.right.hashCode(); + return hash; + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof Pair)) + { + return false; + } + Pair them = (Pair) o; + return this.left.equals(them.left) && this.right.equals(them.right); + } +} diff --git a/scribble-core/src/main/java/org/scribble/util/RuntimeScribException.java b/scribble-core/src/main/java/org/scribble/util/RuntimeScribException.java new file mode 100644 index 000000000..a67e31bda --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/util/RuntimeScribException.java @@ -0,0 +1,62 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.util; + +import org.antlr.runtime.tree.CommonTree; + +public class RuntimeScribException extends RuntimeException +{ + /** + * + */ + private static final long serialVersionUID = 1L; + + public RuntimeScribException(CommonTree blame, String arg0) + { + // Duplicated from AntlrSourceException + super(AntlrSourceException.getRootModuleName(blame) + "(line " + + blame.getLine() + ":" + (blame.getCharPositionInLine()) + "): " + + arg0); + } + + public RuntimeScribException() + { + // TODO Auto-generated constructor stub + } + + public RuntimeScribException(String arg0) + { + super(arg0); + // TODO Auto-generated constructor stub + } + + public RuntimeScribException(Throwable arg0) + { + super(arg0); + // TODO Auto-generated constructor stub + } + + public RuntimeScribException(String arg0, Throwable arg1) + { + super(arg0, arg1); + // TODO Auto-generated constructor stub + } + + public RuntimeScribException(String arg0, Throwable arg1, boolean arg2, + boolean arg3) + { + super(arg0, arg1, arg2, arg3); + // TODO Auto-generated constructor stub + } +} diff --git a/scribble-core/src/main/java/org/scribble/util/ScribException.java b/scribble-core/src/main/java/org/scribble/util/ScribException.java new file mode 100644 index 000000000..4ff805c57 --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/util/ScribException.java @@ -0,0 +1,59 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.util; + +import org.antlr.runtime.tree.CommonTree; + +public class ScribException extends AntlrSourceException +{ + /** + * + */ + private static final long serialVersionUID = 1L; + + public ScribException(CommonTree blame, String arg0) + { + super(blame, arg0); + } + + public ScribException() + { + // TODO Auto-generated constructor stub + } + + public ScribException(String arg0) + { + super(arg0); + // TODO Auto-generated constructor stub + } + + public ScribException(Throwable arg0) + { + super(arg0); + // TODO Auto-generated constructor stub + } + + public ScribException(String arg0, Throwable arg1) + { + super(arg0, arg1); + // TODO Auto-generated constructor stub + } + + public ScribException(String arg0, Throwable arg1, boolean arg2, + boolean arg3) + { + super(arg0, arg1, arg2, arg3); + // TODO Auto-generated constructor stub + } +} diff --git a/scribble-core/src/main/java/org/scribble/util/ScribParserException.java b/scribble-core/src/main/java/org/scribble/util/ScribParserException.java new file mode 100644 index 000000000..662d23f5d --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/util/ScribParserException.java @@ -0,0 +1,53 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.util; + +// CHECKME: should be in parser module? -- maybe make a ModuleLoadingException wrapper? +public class ScribParserException extends Exception +{ + /** + * + */ + private static final long serialVersionUID = 1L; + + public ScribParserException() + { + // TODO Auto-generated constructor stub + } + + public ScribParserException(String arg0) + { + super(arg0); + // TODO Auto-generated constructor stub + } + + public ScribParserException(Throwable arg0) + { + super(arg0); + // TODO Auto-generated constructor stub + } + + public ScribParserException(String arg0, Throwable arg1) + { + super(arg0, arg1); + // TODO Auto-generated constructor stub + } + + public ScribParserException(String arg0, Throwable arg1, boolean arg2, + boolean arg3) + { + super(arg0, arg1, arg2, arg3); + // TODO Auto-generated constructor stub + } +} diff --git a/scribble-core/src/main/java/org/scribble/util/ScribUtil.java b/scribble-core/src/main/java/org/scribble/util/ScribUtil.java new file mode 100644 index 000000000..94002fd7f --- /dev/null +++ b/scribble-core/src/main/java/org/scribble/util/ScribUtil.java @@ -0,0 +1,91 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.util; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.concurrent.Callable; + +public class ScribUtil +{ + public static T handleLambdaScribbleException(Callable c) + { + try + { + return c.call(); + } + catch (Exception se) + { + throw new RuntimeScribException(se); + // Maybe this hack is not worth it? Better to throw directly as ScribbleException from a regular foreach + } + } + + // Returns [ stdout, stderr ] + public static String[] runProcess(String... cmdAndArgs) + throws ScribException + { + try + { + ProcessBuilder pb = new ProcessBuilder(cmdAndArgs); + Process p = pb.start(); + p.waitFor(); + + InputStream is = p.getInputStream(), eis = p.getErrorStream(); + InputStreamReader isr = new InputStreamReader(is); + InputStreamReader eisr = new InputStreamReader(eis); + BufferedReader br = new BufferedReader(isr); + BufferedReader ebr = new BufferedReader(eisr); + String stdout = "", stderr = "", line; + while ((line = br.readLine()) != null) + { + stdout += line + "\n"; + } + while ((line = ebr.readLine()) != null) + { + stderr += line + "\n"; + } + return new String[] { stdout, stderr }; + } + catch (IOException | InterruptedException e) + { + throw new ScribException(e); + } + } + + // Warning: doesn't check if file exists + public static void writeToFile(String path, String text) + throws ScribException + { + File file = new File(path); + File parent = file.getParentFile(); + if (parent != null) + { + parent.mkdirs(); + } + //try (Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "utf-8"))) // Doesn't create missing directories + try (FileWriter writer = new FileWriter(file)) + { + writer.write(text); + } + catch (IOException e) + { + throw new ScribException(e); + } + } +} diff --git a/scribble-core/src/main/resources/org/scribble/protocol/Messages.properties b/scribble-core/src/main/resources/org/scribble/protocol/Messages.properties new file mode 100644 index 000000000..b291d4c92 --- /dev/null +++ b/scribble-core/src/main/resources/org/scribble/protocol/Messages.properties @@ -0,0 +1,32 @@ +# +# Copyright 2008 The Scribble 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 +# +# http://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. +# + +# Export messages +_EXPORT_FAILED=Export failed due to: {0} + +# Validation rule messages +_AMBIGUOUS_CHOICE=Choice is ambiguous, multiple paths have a common interaction(s) ''{0}'' +_CANNOT_USE_RESERVED_WORD= Name ''{0}'' is a reserved word +_EXISTING_DECLARATION=Declaration already exists for name ''{0}'' +_NO_ENCLOSING_RECUR=No enclosing block found with label ''{0}'' +_NO_TYPE_IMPORT=Import statement does not exist for type ''{0}'' +_NOT_FOUND_BOUND_DECLARATION=Bound declaration ''{0}'' not found in definition ''{1}'' +_NOT_FOUND_REFERENCE=Definition ''{0}'' of type ''{1}'' could not be found +_INTERACTION_ROLE=Interaction needs to define a ''{0}'' role +_NAME_ALREADY_DEFINED=Name ''{0}'' has already been declared +_RAISED_TYPE_NOT_CAUGHT=Raised type ''{0}'' is not caught within the enclosing definition +_UNKNOWN_ROLE=Unknown role ''{0}'' +_UNCONNECTED_ROLE=Activity at role ''{0}'' is not connected to preceding activities +_UNPROJECTABLE_ROLES=Role(s) ''{0}'' cannot be projected +_UNRELATED_TO_LOCATED_ROLE=Unrelated to located role ''{0}'' diff --git a/scribble-demos/pom.xml b/scribble-demos/pom.xml new file mode 100644 index 000000000..7e15c327b --- /dev/null +++ b/scribble-demos/pom.xml @@ -0,0 +1,61 @@ + + + 4.0.0 + + + scribble-demos + jar + + + + org.scribble + scribble-core + + + org.scribble + scribble-parser + + + org.scribble + scribble-runtime + + + + + org.scribble + parent + 0.5.1-SNAPSHOT + ../pom.xml + + + + + + + + com.mycila + license-maven-plugin + + + **/*.scr + **/*.java + **/*.policy + **/*.xml + **/*.html + **/stylesheet.css + **/script.js + **/package-list + **/*.versionsBackup + **/Makefile.copyme + **/Makefile + + + + + + + + scribble-demos + + diff --git a/scribble-demos/scrib/Makefile.copyme b/scribble-demos/scrib/Makefile.copyme new file mode 100644 index 000000000..a2dd28a38 --- /dev/null +++ b/scribble-demos/scrib/Makefile.copyme @@ -0,0 +1,300 @@ +# +# Copyright 2008 The Scribble 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 +# +# http://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. +# + +SCRIBBLE_HOME ?= ../.. +SCRIBBLEC ?= $(SCRIBBLE_HOME)/scribblec.sh +JAVAC = javac + +.PHONY: help +help: + @echo "Set \$$SCRIBBLE_HOME (as for scribblec.sh), and \$$SCRIBBLEC to scribblec.sh." + @echo "Example usages:" + @echo " make tutorial" + @echo " make clean-tutorial" + @echo " make all" + @echo " make clean-all" + +.PHONY: all +all: betty16 bettybook coco fase16 fib game http loan nego rpc smtp threebuyer travel tutorial twobuyer fase17 supplierinfo highlow + +.PHONY: clean-all +clean-all: clean-betty16 clean-bettybook clean-coco clean-fase16 clean-fib clean-http clean-loan clean-smtp clean-travel clean-tutorial clean-fase17 clean-highlow + +.PHONY: betty16 +betty16: + @$(call scribc_apigen2,betty16/src,betty16/lec1/httplong/HttpLong.scr,Http,C,S) + @$(call javac,betty16/src,betty16/lec1/httplong/HttpLongC.java) + @$(call javac,betty16/src,betty16/lec1/httplong/HttpLongS.java) + @$(call scribc_apigen2,betty16/src,betty16/lec1/httpshort/HttpShort.scr,Http,C,S) + @$(call javac,betty16/src,betty16/lec1/httpshort/HttpShortC.java) + @$(call javac,betty16/src,betty16/lec1/httpshort/HttpShortS.java) + @$(call scribc_ko,betty16/src/betty16/lec1/misc/Choice1.scr) + @$(call scribc_ok,betty16/src/betty16/lec1/misc/Choice2.scr) + @$(call scribc_ko,betty16/src/betty16/lec1/misc/Choice3.scr) + @$(call scribc_ko,betty16/src/betty16/lec1/misc/Choice4.scr) + @$(call scribc_ok,betty16/src/betty16/lec1/misc/LocatedChoice.scr) + @$(call scribc_ok,betty16/src/betty16/lec1/misc/LocatedChoice2.scr) + @$(call scribc_ok,betty16/src/betty16/lec1/misc/Messaging.scr) + @$(call scribc_ok,betty16/src/betty16/lec1/misc/Protocol1a.scr) + @$(call scribc_ko,betty16/src/betty16/lec1/misc/Protocol1b.scr) + @$(call scribc_ko,betty16/src/betty16/lec1/misc/Protocol1c.scr) + @$(call scribc_ko,betty16/src/betty16/lec1/misc/Protocol2.scr) + @$(call scribc_ko,betty16/src/betty16/lec1/misc/Recursion1.scr) + @$(call scribc_ko,betty16/src/betty16/lec1/misc/Recursion2.scr) + @$(call scribc_ok,betty16/src/betty16/lec1/misc/Recursion3.scr) + @$(call scribc_ko,betty16/src/betty16/lec1/misc/RoleEnabling.scr) + @$(call scribc_ok,betty16/src/betty16/lec1/nego/Negotiate.scr) + +.PHONY: clean-betty16 +clean-betty16: + @$(call rm_apigen,betty16/src,betty16/lec1/httplong/HttpLong,Http) + @$(call rm_apigen,betty16/src,betty16/lec1/httpshort/HttpShort,Http) + +.PHONY: bettybook +bettybook: + @$(call scribc_apigen2,bettybook/src,bettybook/http/longv/HttpLong.scr,Http,C,S) + @$(call javac,bettybook/src,bettybook/http/longv/HttpLongC.java) + @$(call javac,bettybook/src,bettybook/http/longv/HttpLongS.java) + @$(call scribc_apigen2,bettybook/src,bettybook/http/shortv/HttpShort.scr,Http,C,S) + @$(call javac,bettybook/src,bettybook/http/shortv/HttpShortC.java) + @$(call javac,bettybook/src,bettybook/http/shortv/HttpShortS.java) + @$(call scribc_apigen2,bettybook/src,bettybook/math/scrib/Math.scr,MathService,C,S) + @$(call javac,bettybook/src,bettybook/math/scrib/MathC.java) + @$(call javac,bettybook/src,bettybook/math/scrib/MathS1.java) + @$(call javac,bettybook/src,bettybook/math/scrib/MathS2.java) + +.PHONY: clean-bettybook +clean-bettybook: + @$(call rm_apigen,bettybook/src,bettybook/http/longv/HttpLong,Http) + @$(call rm_apigen,bettybook/src,bettybook/http/shortv/HttpShort,Http) + @$(call rm_apigen,bettybook/src,bettybook/math/scrib/Math,MathService) + +.PHONY: coco +coco: + @$(call scribc_apigen2,coco/src,coco/fibo/Fibo.scr,Fibonacci,A,B) + @$(call javac,coco/src,coco/fibo/FiboMain.java) + @$(call scribc_apigen2,coco/src,coco/smtp/Smtp.scr,Smtp,C,S) + @$(call javac,coco/src,coco/smtp/SmtpC1.java) + @$(call javac,coco/src,coco/smtp/SmtpC2.java) + @$(call javac,coco/src,coco/smtp/SmtpC3.java) + +.PHONY: clean-coco +clean-coco: + @$(call rm_apigen,coco/src,coco/fibo/Fibo,Fibonacci) + @$(call rm_apigen,coco/src,coco/smtp/Smtp,Smtp) + +.PHONY: fase16 +fase16: + @$(call scribc_apigen2,fase16/src,fase16/adder/Adder.scr,Adder,C,S) + @$(call javac,fase16/src,fase16/adder/AdderC.java) + @$(call javac,fase16/src,fase16/adder/AdderS.java) + @$(call scribc_apigen2,fase16/src,fase16/smtp/Smtp.scr,Smtp,C,S) + @$(call javac,fase16/src,fase16/smtp/SmtpC.java) + +.PHONY: clean-fase16 +clean-fase16: + @$(call rm_apigen,fase16/src,fase16/adder/Adder,Adder) + @$(call rm_apigen,fase16/src,fase16/smtp/Smtp,Smtp) + +.PHONY: fib +fib: + @$(call scribc_apigen2,fib/src,fib/Fib.scr,Adder,C,S) + @$(call javac,fib/src,fib/AdderClient.java) + @$(call javac,fib/src,fib/AdderServer.java) + @$(call javac,fib/src,fib/FibClient.java) + @$(call scribc_apigen2,fib/src,fib/Fib.scr,Fibonacci,A,B) + @$(call javac,fib/src,fib/Fibo.java) + +.PHONY: clean-fib +clean-fib: +#$(call rm_apigen,fib/src,fib/Fib,Adder) + @rm -rf fib/src/fib/Fib/Adder # HACK + @$(call rm_apigen,fib/src,fib/Fib,Fibonacci) + +.PHONY: game +game: + @$(call scribc_ok,game/src/game/Game1.scr) + @$(call scribc_ok,game/src/game/Game2.scr) + +.PHONY: http +http: + @$(call scribc_apigen2,http/src,http/longvers/HttpLong.scr,Http,C,S) + @$(call javac,http/src,http/longvers/HttpLongC.java) + @$(call javac,http/src,http/longvers/HttpLongS.java) + @$(call scribc_apigen2,http/src,http/shortvers/HttpShort.scr,Http,C,S) + @$(call javac,http/src,http/shortvers/HttpShortC.java) + @$(call javac,http/src,http/shortvers/HttpShortS.java) + +.PHONY: clean-http +clean-http: + @$(call rm_apigen,http/src,http/longvers/HttpLong,Http) + @$(call rm_apigen,http/src,http/shortvers/HttpShort,Http) + +.PHONY: loan +loan: + @$(call scribc_apigen4,loan/src,loan/LoanApplication.scr,BuyerBrokerSupplier,Applicant,ApplicationPortal,ProcessingDept,FinanceDept) + @$(call javac,loan/src,loan/LoanApplicant.java) + @$(call javac,loan/src,loan/LoanApplicationPortal.java) + @$(call javac,loan/src,loan/LoanFinanceDept.java) + @$(call javac,loan/src,loan/LoanProcessingDept.java) + +.PHONY: clean-loan +clean-loan: + @$(call rm_apigen,loan/src,loan/LoanApplication,BuyerBrokerSupplier) + +.PHONY: nego +nego: + @$(call scribc_ok,nego/src/nego/Nego1.scr) + @$(call scribc_ok,nego/src/nego/Nego2.scr) + @$(call scribc_ok,nego/src/nego/Nego3.scr) + +.PHONY: rpc +rpc: + @$(call scribc_ok,rpc/src/rpc/RPC.scr) + +.PHONY: smtp +smtp: + @$(call scribc_apigen2,smtp/src,smtp/Smtp.scr,Smtp,C,S,-subtypes) + @$(call javac,smtp/src,smtp/SimpleSmtpC.java) + @$(call javac,smtp/src,smtp/SmtpC.java) + +.PHONY: clean-smtp +clean-smtp: + @$(call rm_apigen,smtp/src,smtp/Smtp,Smtp) + +.PHONY: threebuyer +threebuyer: + @$(call scribc_ok,threebuyer/src/threebuyer/ThreeBuyer.scr) + @$(call scribc_ok,threebuyer/src/threebuyer/ThreeBuyer2.scr) + +.PHONY: travel +travel: + @$(call scribc_apigen3,travel/src,travel/Travel.scr,Booking,A,C,S) + @$(call javac,travel/src,travel/BookingA.java) + @$(call javac,travel/src,travel/BookingC.java) + @$(call javac,travel/src,travel/BookingS.java) + +.PHONY: clean-travel +clean-travel: + @$(call rm_apigen,travel/src,travel/Travel,Booking) + +.PHONY: tutorial +tutorial: + @$(call scribc_apigen2,tutorial/src,tutorial/adder/Adder.scr,Adder,C,S) + @$(call javac,tutorial/src,tutorial/adder/AdderC.java) + @$(call javac,tutorial/src,tutorial/adder/AdderS.java) + +.PHONY: clean-tutorial +clean-tutorial: + @$(call rm_apigen,tutorial/src,tutorial/adder/Adder,Adder) + +.PHONY: twobuyer +twobuyer: + @$(call scribc_ok,twobuyer/src/twobuyer/TwoBuyer.scr) + +.PHONY: fase17 +fase17: + @$(call scribc_ko,$(SCRIBBLE_HOME)/scribble-test/src/test/scrib/demo/fase17/intro/FirstL.scr) + @$(call scribc_ok,$(SCRIBBLE_HOME)/scribble-test/src/test/scrib/demo/fase17/intro/FirstL.scr,-fair) + @$(call scribc_ko,$(SCRIBBLE_HOME)/scribble-test/src/test/scrib/demo/fase17/overview/P1.scr) + @$(call scribc_apigen3,$(SCRIBBLE_HOME)/scribble-test/src/test/scrib,demo/fase17/travel/TravelAgent.scr,TravelAgent,A,C,S) + @$(call javac,$(SCRIBBLE_HOME)/scribble-test/src/test/scrib,demo/fase17/travel/TravelA.java) + @$(call javac,$(SCRIBBLE_HOME)/scribble-test/src/test/scrib,demo/fase17/travel/TravelC.java) + @$(call javac,$(SCRIBBLE_HOME)/scribble-test/src/test/scrib,demo/fase17/travel/TravelS.java) + @$(call scribc_apigen3,$(SCRIBBLE_HOME)/scribble-test/src/test/scrib,demo/fase17/travel2/TravelAgent2.scr,TravelAgent2,A,C,S) + @$(call javac,$(SCRIBBLE_HOME)/scribble-test/src/test/scrib,demo/fase17/travel2/Travel2A.java) + @$(call javac,$(SCRIBBLE_HOME)/scribble-test/src/test/scrib,demo/fase17/travel2/Travel2C.java) + @$(call javac,$(SCRIBBLE_HOME)/scribble-test/src/test/scrib,demo/fase17/travel2/Travel2S.java) + +.PHONY: clean-fase17 +clean-fase17: + @$(call rm_apigen,$(SCRIBBLE_HOME)/scribble-test/src/test/scrib,demo/fase17/travel/TravelAgent,TravelAgent) + @$(call rm_apigen,$(SCRIBBLE_HOME)/scribble-test/src/test/scrib,demo/fase17/travel2/TravelAgent2,TravelAgent2) + +.PHONY: supplierinfo +supplierinfo: + @$(call scribc_ok,$(SCRIBBLE_HOME)/scribble-test/src/test/scrib/demo/supplierinfo/SupplierInfoExplicit.scr,-fair) + @$(call scribc_ok,$(SCRIBBLE_HOME)/scribble-test/src/test/scrib/demo/supplierinfo/SupplierInfoNoFair.scr) + +.PHONY: highlow +highlow: + @$(call scribc_apigen3,$(SCRIBBLE_HOME)/scribble-test/src/test/scrib/demo/,highlow/HighLow.scr,HighLow,A,B,C) + @$(call scribc_cbapigen3,$(SCRIBBLE_HOME)/scribble-test/src/test/scrib/demo/,highlow/HighLow.scr,HighLow,A,B,C) + @$(call javac,$(SCRIBBLE_HOME)/scribble-test/src/test/scrib/demo,highlow/HighLowA.java) + @$(call javac,$(SCRIBBLE_HOME)/scribble-test/src/test/scrib/demo,highlow/HighLowB.java) + @$(call javac,$(SCRIBBLE_HOME)/scribble-test/src/test/scrib/demo,highlow/HighLowC.java) + @$(call javac,$(SCRIBBLE_HOME)/scribble-test/src/test/scrib/demo,highlow/cb/MyA.java) + @$(call javac,$(SCRIBBLE_HOME)/scribble-test/src/test/scrib/demo,highlow/cb/MyB.java) + @$(call javac,$(SCRIBBLE_HOME)/scribble-test/src/test/scrib/demo,highlow/cb/MyC.java) + +.PHONY: clean-highlow +clean-highlow: + @$(call rm_apigen,$(SCRIBBLE_HOME)/scribble-test/src/test/scrib/demo/,highlow/HighLow,HighLow) + + +# filename, extra +define scribc_ok + echo "Validate OK: "$(1); \ + $(SCRIBBLEC) $(1) $(2) +endef + +# filename +define scribc_ko + echo "Validate KO: "$(1); \ + $(SCRIBBLEC) $(1) 2> /dev/null; \ + EXIT=$$?; if [ $$EXIT -eq 0 ]; then \ + echo "Expected protocol validation error, but none occurred."; \ + exit 1; \ + fi; +endef + +# dir, filename, proto, role1, role2, extra +define scribc_apigen2 + echo "API gen: "$(1)"/"$(2)", "$(3)" @ "$(4)", "$(5); \ + $(SCRIBBLEC) -d $(1) $(1)/$(2) -api $(3) $(4) -api $(3) $(5) $(6) +endef + +# dir, filename, proto, role1, role2, role3 +define scribc_apigen3 + echo "API gen: "$(1)"/"$(2)", "$(3)" @ "$(4)", "$(5)", "$(6); \ + $(SCRIBBLEC) -d $(1) $(1)/$(2) -api $(3) $(4) -api $(3) $(5) -api $(3) $(6) +endef + +# dir, filename, proto, role1, role2, role3 +define scribc_cbapigen3 +echo "CB API gen: "$(1)"/"$(2)", "$(3)" @ "$(4)", "$(5)", "$(6); \ + $(SCRIBBLEC) -d $(1) $(1)/$(2) -cbapi $(3) $(4) -cbapi $(3) $(5) -cbapi $(3) $(6) +endef + +# dir, filename, proto, role1, role2, role3, role4 +define scribc_apigen4 + echo "API gen: "$(1)"/"$(2)", "$(3)" @ "$(4)", "$(5)", "$(6)", "$(7); \ + $(SCRIBBLEC) -d $(1) $(1)/$(2) -api $(3) $(4) -api $(3) $(5) -api $(3) $(6) -api $(3) $(7) +endef + +# dir, dir, proto +define rm_apigen + echo "Deleting: "$(1)/$(2)/$(3); \ + rm -rf $(1)/$(2)/$(3); \ + rm -fd $(1)/$(2) +endef + +# dir, filename +define javac + echo "Compiling: "$(1)/$(2); \ + mkdir -p $(SCRIBBLE_HOME)/scribble-demos/target/test-classes; \ + javac -cp $(SCRIBBLE_HOME)/scribble-ast/target/classes:$(SCRIBBLE_HOME)/scribble-cli/target/classes:$(SCRIBBLE_HOME)/scribble-codegen/target/classes:$(SCRIBBLE_HOME)/scribble-core/target/classes:$(SCRIBBLE_HOME)/scribble-main/target/classes:$(SCRIBBLE_HOME)/scribble-parser/target/classes:$(SCRIBBLE_HOME)/scribble-parser/lib/antlr-3.5.2-complete.jar:$(SCRIBBLE_HOME)/scribble-runtime/target/classes:$(1) \ + $(1)/$(2) -d $(SCRIBBLE_HOME)/scribble-demos/target/test-classes +endef + diff --git a/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/HttpLong.scr b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/HttpLong.scr new file mode 100644 index 000000000..a1fc9349d --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/HttpLong.scr @@ -0,0 +1,212 @@ +/** + * Assuming scribblec.sh in scribble-java root directory: + * + * ./scribblec.sh -d scribble-demos/scrib/betty16/src scribble-demos/scrib/betty16/src/betty16/lec1/httplong/HttpLong.scr -api Http C + * + * $ javadoc -cp scribble-core/target/classes:scribble-runtime/target/classes:scribble-demos/scrib/betty16/src -subpackages betty16.lec1.httplong.HttpLong.Http -d scribble-demos/scrib/betty16/javadoc/httplong + * + */ + + +module betty16.lec1.httplong.HttpLong; + + +sig "betty16.lec1.httplong.message.client.RequestLine" + from "betty16/lec1/httplong/message/RequestLine.java" + as REQUESTL; // GET /~rhu/ HTTP/1.1 + +sig "betty16.lec1.httplong.message.client.Host" + from "betty16/lec1/httplong/message/Host.java" + as HOST; // host: www.doc.ic.ac.uk + +sig "betty16.lec1.httplong.message.Body" + from "betty16/lec1/httplong/message/Body.java" + as BODY; // ... + +sig "betty16.lec1.httplong.message.client.UserAgent" + from "betty16/lec1/httplong/message/UserAgent.java" + as USERA; // User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; rv:38.0) Gecko/20100101 Firefox/38.0 + +sig "betty16.lec1.httplong.message.client.Accept" + from "betty16/lec1/httplong/message/Accept.java" + as ACCEPT; // Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 + +sig "betty16.lec1.httplong.message.client.AcceptLanguage" + from "betty16/lec1/httplong/message/AcceptLanguage.java" + as ACCEPTL; // Accept-Language: en-GB,en;q=0.5 + +sig "betty16.lec1.httplong.message.client.AcceptEncoding" + from "betty16/lec1/httplong/message/AcceptEncoding.java" + as ACCEPTE; // Accept-Encoding: gzip, deflate + +sig "betty16.lec1.httplong.message.client.DoNotTrack" + from "betty16/lec1/httplong/message/DoNotTrack.java" + as DNT; // DNT: 1 + +sig "betty16.lec1.httplong.message.client.Connection" + from "betty16/lec1/httplong/message/Connection.java" + as CONN; // Connection: keep-alive + +sig "betty16.lec1.httplong.message.client.UpgradeInsecureRequests" + from "betty16/lec1/httplong/message/UpgradeInsecureRequests.java" + as UPGRADEIR; // Upgrade-Insecure-Requests: 1 + +sig "betty16.lec1.httplong.message.client.Cookie" + from "betty16/lec1/httplong/message/Cookie.java" + as COOKIE; // Cookie: __utma=111872281.1372348290.1498163262.1498163262.1498163262.1; __utmz=111872281.1498163262.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none) + +sig "betty16.lec1.httplong.message.client.Pragma" + from "betty16/lec1/httplong/message/Pragma.java" + as PRAGMA; // Pragma: no-cache + +/*sig "betty16.lec1.httplong.message.client.CacheControl" + from "betty16/lec1/httplong/message/CacheControl.java" + as CACHEC; // Cache-Control: max-age=0*/ + + +sig "betty16.lec1.httplong.message.server.HttpVersion" + from "betty16/lec1/httplong/message/HttpVersion.java" + as HTTPV; // HTTP/1.1 + +sig "betty16.lec1.httplong.message.server._200" // "Status" line (with HTTPV) + from "betty16/lec1/httplong/message/_200.java" + as 200; // 200 OK + +sig "betty16.lec1.httplong.message.server._404" + from "betty16/lec1/httplong/message/_404.java" + as 404; + +sig "betty16.lec1.httplong.message.server.Date" + from "betty16/lec1/httplong/message/Date.java" + as DATE; // Date: Sun, 24 May 2015 21:04:36 GMT + +sig "betty16.lec1.httplong.message.server.Server" + from "betty16/lec1/httplong/message/Server.java" + as SERVER; // Server: Apache + +sig "betty16.lec1.httplong.message.server.StrictTransportSecurity" + from "betty16/lec1/httplong/message/StrictTransportSecurity.java" + as STRICTTS; // Strict-Transport-Security: max-age=31536000; preload; includeSubDomains + +sig "betty16.lec1.httplong.message.server.LastModified" + from "betty16/lec1/httplong/message/LastModified.java" + as LASTM; // Last-Modified: Sat, 23 Jul 2011 09:38:43 GMT + +sig "betty16.lec1.httplong.message.server.ETag" + from "betty16/lec1/httplong/message/ETag.java" + as ETAG; // ETag: "ac6fa008-559-4a8b95908aec0" + +sig "betty16.lec1.httplong.message.server.AcceptRanges" + from "betty16/lec1/httplong/message/AcceptRanges.java" + as ACCEPTR; // Accept-Ranges: bytes + +sig "betty16.lec1.httplong.message.server.ContentLength" + from "betty16/lec1/httplong/message/ContentLength.java" + as CONTENTL; // Content-Length: 1369 + +sig "betty16.lec1.httplong.message.server.Vary" + from "betty16/lec1/httplong/message/Vary.java" + as VARY; // Vary: Accept-Encoding + +sig "betty16.lec1.httplong.message.server.ContentType" + from "betty16/lec1/httplong/message/ContentType.java" + as CONTENTT; // Content-Type: text/html + +sig "betty16.lec1.httplong.message.server.Via" + from "betty16/lec1/httplong/message/Via.java" + as VIA; // Via: 1.1 www.doc.ic.ac.uk + + +global protocol Http(role C, role S) { + do Request(C, S); + do Response(C, S); +} + +aux global protocol Request(role C, role S) { + choice at C { + REQUESTL from C to S; // GET /~rhu/ HTTP/1.1 + rec X { + choice at C { + HOST from C to S; // Host: www.doc.ic.ac.uk + continue X; + } or { + USERA from C to S; // User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; rv:38.0) Gecko/20100101 Firefox/38.0 + continue X; + } or { + ACCEPT from C to S; // Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 + continue X; + } or { + ACCEPTL from C to S; // Accept-Language: en-GB,en;q=0.5 + continue X; + } or { + ACCEPTE from C to S; // Accept-Encoding: gzip, deflate + continue X; + } or { + DNT from C to S; // DNT: 1 + continue X; + } or { + CONN from C to S; // Connection: keep-alive + continue X; + } or { + UPGRADEIR from C to S; // Upgrade-Insecure-Requests: 1 + continue X; + } or { + COOKIE from C to S; // Cookie: __utma=111872281.1372348290.1498163262.1498163262.1498163262.1; __utmz=111872281.1498163262.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none) + continue X; + } or { + PRAGMA from C to S; // Pragma: no-cache + continue X; + /*} or { + CACHEC from C to S; // Cache-Control: max-age=0 + continue X; + */} or { + BODY from C to S; + } + } + } +} + +aux global protocol Response(role C, role S) { + HTTPV from S to C; // HTTP/1.1 + choice at S { + 200 from S to C; // 200 OK + } or { + 404 from S to C; + } + + rec Y { + choice at S { + DATE from S to C; // Date: Sun, 24 May 2015 21:04:36 GMT + continue Y; + } or { + SERVER from S to C; // Server: Apache + continue Y; + } or { + STRICTTS from S to C; // Strict-Transport-Security: max-age=31536000; preload; includeSubDomains + continue Y; + } or { + LASTM from S to C; // Last-Modified: Sat, 23 Jul 2011 09:38:43 GMT + continue Y; + } or { + ETAG from S to C; // ETag: "ac6fa008-559-4a8b95908aec0" + continue Y; + } or { + ACCEPTR from S to C; // Accept-Ranges: bytes + continue Y; + } or { + CONTENTL from S to C; // Content-Length: 1369 + continue Y; + } or { + VARY from S to C; // Vary: Accept-Encoding + continue Y; + } or { + CONTENTT from S to C; // Content-Type: text/html + continue Y; + } or { + VIA from S to C; // Via: 1.1 www.doc.ic.ac.uk + continue Y; + } or { + BODY from S to C; // Message length indicated by Content-Length + } + } +} diff --git a/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/HttpLongC.java b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/HttpLongC.java new file mode 100644 index 000000000..787219c6e --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/HttpLongC.java @@ -0,0 +1,106 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package betty16.lec1.httplong; + +import static betty16.lec1.httplong.HttpLong.Http.Http.ACCEPTR; +import static betty16.lec1.httplong.HttpLong.Http.Http.BODY; +import static betty16.lec1.httplong.HttpLong.Http.Http.C; +import static betty16.lec1.httplong.HttpLong.Http.Http.CONTENTL; +import static betty16.lec1.httplong.HttpLong.Http.Http.CONTENTT; +import static betty16.lec1.httplong.HttpLong.Http.Http.DATE; +import static betty16.lec1.httplong.HttpLong.Http.Http.ETAG; +import static betty16.lec1.httplong.HttpLong.Http.Http.HTTPV; +import static betty16.lec1.httplong.HttpLong.Http.Http.LASTM; +import static betty16.lec1.httplong.HttpLong.Http.Http.S; +import static betty16.lec1.httplong.HttpLong.Http.Http.SERVER; +import static betty16.lec1.httplong.HttpLong.Http.Http.STRICTTS; +import static betty16.lec1.httplong.HttpLong.Http.Http.VARY; +import static betty16.lec1.httplong.HttpLong.Http.Http.VIA; +import static betty16.lec1.httplong.HttpLong.Http.Http._200; +import static betty16.lec1.httplong.HttpLong.Http.Http._404; + +import org.scribble.runtime.net.SocketChannelEndpoint; +import org.scribble.runtime.session.MPSTEndpoint; +import org.scribble.runtime.util.Buf; + +import betty16.lec1.httplong.HttpLong.Http.Http; +import betty16.lec1.httplong.HttpLong.Http.roles.C; +import betty16.lec1.httplong.HttpLong.Http.statechans.C.EndSocket; +import betty16.lec1.httplong.HttpLong.Http.statechans.C.Http_C_1; +import betty16.lec1.httplong.HttpLong.Http.statechans.C.Http_C_3; +import betty16.lec1.httplong.HttpLong.Http.statechans.C.Http_C_4_Cases; +import betty16.lec1.httplong.HttpLong.Http.statechans.C.Http_C_5; +import betty16.lec1.httplong.HttpLong.Http.statechans.C.Http_C_5_Cases; +import betty16.lec1.httplong.message.Body; +import betty16.lec1.httplong.message.HttpLongMessageFormatter; +import betty16.lec1.httplong.message.client.Host; +import betty16.lec1.httplong.message.client.RequestLine; + + +public class HttpLongC { + + public static void main(String[] args) throws Exception { + Http http = new Http(); + try (MPSTEndpoint client = new MPSTEndpoint<>(http, C, + new HttpLongMessageFormatter())) { + String host = "example.com"; int port = 80; String file = "/"; + //String host = "localhost"; int port = 8080; String file = "/"; + + client.request(S, SocketChannelEndpoint::new, host, port); + new HttpLongC().run(new Http_C_1(client), host, file); + } + } + + public EndSocket run(Http_C_1 c, String host, String file) throws Exception { + return doResponse(doRequest(c, host, file)); + } + + private Http_C_3 doRequest(Http_C_1 c1, String host, String file) throws Exception { + return c1.send(S, new RequestLine(file, "1.1")) + .send(S, new Host(host)) + .send(S, new Body("")); + } + + private EndSocket doResponse(Http_C_3 c3) throws Exception { + Http_C_4_Cases cases = c3.async(S, HTTPV).branch(S); + switch (cases.op) { + case _200: return doResponseAux(cases.receive(_200)); + case _404: return doResponseAux(cases.receive(_404)); + default: throw new RuntimeException("[TODO]: " + cases.op); + } + } + + private EndSocket doResponseAux(Http_C_5 c5) throws Exception { + Http_C_5_Cases cases = c5.branch(S); + switch (cases.op) { + case ACCEPTR: return doResponseAux(cases.receive(ACCEPTR)); + case CONTENTL: return doResponseAux(cases.receive(CONTENTL)); + case CONTENTT: return doResponseAux(cases.receive(CONTENTT)); + case DATE: return doResponseAux(cases.receive(DATE)); + case ETAG: return doResponseAux(cases.receive(ETAG)); + case LASTM: return doResponseAux(cases.receive(LASTM)); + case SERVER: return doResponseAux(cases.receive(SERVER)); + case STRICTTS: return doResponseAux(cases.receive(STRICTTS)); + case VARY: return doResponseAux(cases.receive(VARY)); + case VIA: return doResponseAux(cases.receive(VIA)); + case BODY: { + Buf buf_body = new Buf<>(); + EndSocket end = cases.receive(BODY, buf_body); + System.out.println(buf_body.val.getBody()); + return end; + } + default: throw new RuntimeException("[TODO]: " + cases.op); + } + } +} diff --git a/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/HttpLongS.java b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/HttpLongS.java new file mode 100644 index 000000000..5b2f03b9b --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/HttpLongS.java @@ -0,0 +1,118 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package betty16.lec1.httplong; + +import static betty16.lec1.httplong.HttpLong.Http.Http.ACCEPT; +import static betty16.lec1.httplong.HttpLong.Http.Http.ACCEPTE; +import static betty16.lec1.httplong.HttpLong.Http.Http.ACCEPTL; +import static betty16.lec1.httplong.HttpLong.Http.Http.BODY; +import static betty16.lec1.httplong.HttpLong.Http.Http.C; +import static betty16.lec1.httplong.HttpLong.Http.Http.CONN; +import static betty16.lec1.httplong.HttpLong.Http.Http.COOKIE; +import static betty16.lec1.httplong.HttpLong.Http.Http.DNT; +import static betty16.lec1.httplong.HttpLong.Http.Http.HOST; +import static betty16.lec1.httplong.HttpLong.Http.Http.REQUESTL; +import static betty16.lec1.httplong.HttpLong.Http.Http.S; +import static betty16.lec1.httplong.HttpLong.Http.Http.UPGRADEIR; +import static betty16.lec1.httplong.HttpLong.Http.Http.USERA; +import static betty16.lec1.httplong.HttpLong.Http.Http.PRAGMA; +//import static betty16.lec1.httplong.HttpLong.Http.Http.CACHEC; + +import java.io.IOException; + +import org.scribble.main.ScribRuntimeException; +import org.scribble.runtime.net.ScribServerSocket; +import org.scribble.runtime.net.SocketChannelServer; +import org.scribble.runtime.session.MPSTEndpoint; +import org.scribble.runtime.util.Buf; + +import betty16.lec1.httplong.HttpLong.Http.Http; +import betty16.lec1.httplong.HttpLong.Http.roles.S; +import betty16.lec1.httplong.HttpLong.Http.statechans.S.EndSocket; +import betty16.lec1.httplong.HttpLong.Http.statechans.S.Http_S_1; +import betty16.lec1.httplong.HttpLong.Http.statechans.S.Http_S_2; +import betty16.lec1.httplong.HttpLong.Http.statechans.S.Http_S_2_Cases; +import betty16.lec1.httplong.message.Body; +import betty16.lec1.httplong.message.HttpLongMessageFormatter; +import betty16.lec1.httplong.message.server.ContentLength; +import betty16.lec1.httplong.message.server.HttpVersion; +import betty16.lec1.httplong.message.server._200; + + +/** TODO: + * Cannot parse header field: Pragma: no-cache + * at betty16.lec1.httplong.message.HttpLongMessageFormatter.fromBytes(HttpLongMessageFormatter.java:197) + * + * java.lang.RuntimeException: Cannot parse header field: Cache-Control: max-age=0 + * at betty16.lec1.httplong.message.HttpLongMessageFormatter.fromBytes(HttpLongMessageFormatter.java:197) + */ + +public class HttpLongS +{ + public static void main(String[] args) throws Exception + { + try (ScribServerSocket ss = new SocketChannelServer(8080)) { + while (true) { + Http http = new Http(); + try (MPSTEndpoint server = new MPSTEndpoint<>(http, S, + new HttpLongMessageFormatter())) { + server.accept(ss, C); + + run(new Http_S_1(server)); + } + catch (IOException | ClassNotFoundException + | ScribRuntimeException e) + { + e.printStackTrace(); + } + } + } + } + + private static EndSocket run(Http_S_1 s1) + throws ClassNotFoundException, ScribRuntimeException, IOException { + Buf buf = new Buf<>(); + + Http_S_2 s2 = s1.receive(C, REQUESTL, buf); + System.out.println("Requested: " + buf.val); + + while (true) { + Http_S_2_Cases cases = s2.branch(C); + switch (cases.op) { + case ACCEPT: s2 = cases.receive(ACCEPT, buf); break; + case ACCEPTE: s2 = cases.receive(ACCEPTE, buf); break; + case ACCEPTL: s2 = cases.receive(ACCEPTL, buf); break; + case BODY: + { + String body = "Hello, World!"; + return + cases.receive(BODY, buf) + .send(C, new HttpVersion("1.1")) + .send(C, new _200("OK")) + .send(C, new ContentLength(body.length())) + .send(C, new Body(body)); + } + case CONN: s2 = cases.receive(CONN, buf); break; + case DNT: s2 = cases.receive(DNT, buf); break; + case UPGRADEIR: s2 = cases.receive(UPGRADEIR, buf); break; + case COOKIE: s2 = cases.receive(COOKIE, buf); break; + case HOST: s2 = cases.receive(HOST, buf); break; + case USERA: s2 = cases.receive(USERA, buf); break; + case PRAGMA: s2 = cases.receive(PRAGMA, buf); break; + //case CACHEC: s2 = cases.receive(CACHEC, buf); break; + default: throw new RuntimeException("Missing field case: " + cases.op); + } + } + } +} diff --git a/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/Body.java b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/Body.java new file mode 100644 index 000000000..67235da3b --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/Body.java @@ -0,0 +1,32 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package betty16.lec1.httplong.message; + +import betty16.lec1.httplong.HttpLong.Http.Http; + +public class Body extends HttpLongMessage +{ + private static final long serialVersionUID = 1L; + + public Body(String body) + { + super(Http.BODY, body); + } + + @Override + public byte[] toBytes() + { + return (getOpString(this.op) + getBody()).getBytes(HttpLongMessageFormatter.cs); // opString should be empty + } +} diff --git a/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/HeaderField.java b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/HeaderField.java new file mode 100644 index 000000000..f8869fc91 --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/HeaderField.java @@ -0,0 +1,26 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package betty16.lec1.httplong.message; + +import org.scribble.core.type.name.Op; + +public abstract class HeaderField extends HttpLongMessage +{ + private static final long serialVersionUID = 1L; + + public HeaderField(Op name, String value) + { + super(name, ": " + value + " "); + } +} diff --git a/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/HttpLongMessage.java b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/HttpLongMessage.java new file mode 100644 index 000000000..ea02f8a8f --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/HttpLongMessage.java @@ -0,0 +1,158 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package betty16.lec1.httplong.message; + +import org.scribble.runtime.message.ScribMessage; +import org.scribble.core.type.name.Op; + +import betty16.lec1.httplong.HttpLong.Http.Http; + +// Unlike ScribMessage, HttpMessage is not actually "sent", but we use it as the base class since the socket API takes ScribMessages +public abstract class HttpLongMessage extends ScribMessage +{ + private static final long serialVersionUID = 1L; + + // TODO: make case-insensitive + // " " after ops done by HeaderField + public static final String GET = "GET"; + public static final String HTTP = "HTTP"; + public static final String HOST = "Host"; + + public static final String USER_AGENT = "User-Agent"; + public static final String ACCEPT = "Accept"; + public static final String ACCEPT_LANGUAGE = "Accept-Language"; + public static final String ACCEPT_ENCODING = "Accept-Encoding"; + public static final String DO_NOT_TRACK = "DNT"; + public static final String CONNECTION = "Connection"; + public static final String UPGRADE_INSECURE_REQUESTS = "Upgrade-Insecure-Requests"; + public static final String COOKIE = "Cookie"; + public static final String PRAGMA = "Pragma"; + //public static final String CACHE_CONTROL = "Cache-Control"; + + public static final String DATE = "Date"; + public static final String CONTENT_TYPE = "Content-Type"; + public static final String _404 = "404"; + public static final String _200 = "200"; + public static final String ACCEPT_RANGES = "Accept-Ranges"; + public static final String LAST_MODIFIED = "Last-Modified"; + public static final String VARY = "Vary"; + public static final String SERVER = "Server"; + public static final String STRICT_TRANSPORT_SECURITY = "Strict-Transport-Security"; + public static final String VIA = "Via"; + public static final String ETAG = "ETag"; + public static final String CONTENT_LENGTH = "Content-Length"; + + protected static final String CRLF = "\r\n"; + + public HttpLongMessage(Op op) + { + super(op); + } + + public HttpLongMessage(Op op, String body) + { + super(op, body); + } + + public String getBody() + { + return (this.payload.length == 0) ? "" : (String) this.payload[0]; + } + + public byte[] toBytes() + { + return (getOpString(this.op) + getBody() + HttpLongMessage.CRLF) + .getBytes(HttpLongMessageFormatter.cs); + // Can give "utf-8" as arg directly + } + + @Override + public String toString() + { + return new String(toBytes()); + } + + // " " after ops done by HeaderField + protected static String getOpString(Op op) + { + if (op.equals(Http.CONTENTL)) + { + return HttpLongMessage.CONTENT_LENGTH; + } + else if (op.equals(Http.ETAG)) + { + return HttpLongMessage.ETAG; + } + else if (op.equals(Http.BODY)) + { + return HttpLongMessage.CRLF; // This CRLF "op" actually enacts the empty line for end-of-headers + } + else if (op.equals(Http.VIA)) + { + return HttpLongMessage.VIA; + } + else if (op.equals(Http.SERVER)) + { + return HttpLongMessage.SERVER; + } + else if (op.equals(Http.VARY)) + { + return HttpLongMessage.VARY; + } + else if (op.equals(HttpLongMessage.CRLF)) + { + return ""; + } + else if (op.equals(Http.REQUESTL)) // FIXME: not just GET (POST..) + { + return HttpLongMessage.GET; + } + else if (op.equals(Http.LASTM)) + { + return HttpLongMessage.LAST_MODIFIED; + } + else if (op.equals(Http.ACCEPTR)) + { + return HttpLongMessage.ACCEPT_RANGES; + } + else if (op.equals(Http.HOST)) + { + return HttpLongMessage.HOST; + } + else if (op.equals(Http.HTTPV)) + { + return HttpLongMessage.HTTP; + } + else if (op.equals(Http._200)) + { + return HttpLongMessage._200; + } + else if (op.equals(Http._404)) + { + return HttpLongMessage._404; + } + else if (op.equals(Http.CONTENTT)) + { + return HttpLongMessage.CONTENT_TYPE; + } + else if (op.equals(Http.DATE)) + { + return HttpLongMessage.DATE; + } + else + { + throw new RuntimeException("TODO: " + op); + } + } +} diff --git a/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/HttpLongMessageFormatter.java b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/HttpLongMessageFormatter.java new file mode 100644 index 000000000..8a46665ac --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/HttpLongMessageFormatter.java @@ -0,0 +1,402 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package betty16.lec1.httplong.message; + +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.Charset; + +import betty16.lec1.httplong.message.client.*; +import betty16.lec1.httplong.message.server.*; +import org.scribble.runtime.message.ScribMessage; +import org.scribble.runtime.message.ScribMessageFormatter; + +public class HttpLongMessageFormatter implements ScribMessageFormatter +{ + public static final Charset cs = Charset.forName("UTF8"); + //private static CharsetDecoder cd = cs.newDecoder(); + + private int len = -1; + + public HttpLongMessageFormatter() + { + + } + + @Override + public byte[] toBytes(ScribMessage m) throws IOException + { + return ((HttpLongMessage) m).toBytes(); + } + + @Override + public ScribMessage fromBytes(ByteBuffer bb) throws IOException, ClassNotFoundException + { + bb.flip(); + int rem = bb.remaining(); + if (rem < 2) + { + bb.compact(); + return null; + } + + int pos = bb.position(); + String front = new String(new byte[] { bb.get(pos), bb.get(pos + 1) }, HttpLongMessageFormatter.cs); + if (front.equals(HttpLongMessage.CRLF)) // not sound? -- actually, due to sess types it is safe (same reason why interpreting any of these messages without context is sound) -- parsing doesn't have to follow the *full protocol* BNF any more to be sound + { + if (this.len == -1) + { + return new Body(""); + } + if (rem < this.len + 2) + { + bb.compact(); + return null; + } + //String body = readLine(dis) + HttpMessage.CRLF; // HACK: assumes at least 1 CRLF + StringBuffer sb = new StringBuffer(); + //for (int i = body.length(); i < this.len; i++) + for (int i = 0; i < this.len; i++) // CHECKME: Client-side len out by 1? e.g., example.com + { + sb.append((char) bb.get()); + } + this.len = -1; + //return new Body(body + sb.toString()); + return new Body(sb.toString()); + } + + if (rem < pos + 4) + { + bb.compact(); + return null; + } + //byte[] bs = new byte[2]; + //dis.readFully(bs); + front += new String(new byte[] { bb.get(pos + 2), bb.get(pos + 3) }, HttpLongMessageFormatter.cs); + // FIXME: factor out with HttpMessage op strings + int code = isStatusCode(front); + if (code > -1) + { + String reason = readLine(bb, pos + 4).trim(); // Whitespace already built into the message classes + bb.compact(); + if (reason == null) + { + return null; + } + switch (code) + { + case 200: return new _200(reason); + case 404: return new _404(reason); + default: throw new RuntimeException("Unknown status code: " + code); + } + } + else if (front.startsWith(HttpLongMessage.GET)) + { + String reql = readLine(bb, pos + 4).trim(); + bb.compact(); + if (reql == null) + { + return null; + } + String target = reql.substring(0, reql.indexOf(' ')); + String vers = reql.substring(reql.indexOf(' ') + 1).trim(); + vers = vers.substring(vers.indexOf('/') + 1); + return new RequestLine(target, vers); + } + else if (front.equals(HttpLongMessage.HTTP)) + { + //dis.read(); // '/' + if (rem < pos + 5) + { + bb.compact(); + return null; + } + String word = readWord(bb, pos + 5); + bb.compact(); + if (word == null) + { + return null; + } + return new HttpVersion(word); + } + else + { + String line = readLine(bb, pos + 4); + bb.compact(); + if (line == null) + { + return null; + } + line = front + line; + int colon = line.indexOf(':'); + if (colon > -1) + { + String name = line.substring(0, colon); + String value = line.substring(colon + 1).trim(); // Whitespace already built into the message classes + switch (name) + { + case HttpLongMessage.HOST: return new Host(value); + case HttpLongMessage.USER_AGENT: return new UserAgent(value); + case HttpLongMessage.ACCEPT: return new Accept(value); + case HttpLongMessage.ACCEPT_LANGUAGE: return new AcceptLanguage(value); + case HttpLongMessage.ACCEPT_ENCODING: return new AcceptEncoding(value); + case HttpLongMessage.DO_NOT_TRACK: return new DoNotTrack(Integer.parseInt(value)); + case HttpLongMessage.CONNECTION: return new Connection(value); + case HttpLongMessage.UPGRADE_INSECURE_REQUESTS: return new UpgradeInsecureRequests(Integer.parseInt(value)); + case HttpLongMessage.COOKIE: return new Cookie(value); + case HttpLongMessage.PRAGMA: return new Pragma(value); + //case HttpLongMessage.CACHE_CONTROL: return new CacheControl(value); + + case HttpLongMessage.DATE: return new Date(value); + case HttpLongMessage.SERVER: return new Server(value); + case HttpLongMessage.STRICT_TRANSPORT_SECURITY: return new StrictTransportSecurity(value); + case HttpLongMessage.LAST_MODIFIED: return new LastModified(value); + case HttpLongMessage.ETAG: return new ETag(value); + case HttpLongMessage.ACCEPT_RANGES: return new AcceptRanges(value); + case HttpLongMessage.CONTENT_LENGTH: + { + len = Integer.parseInt(value.trim()); + return new ContentLength(len); + } + case HttpLongMessage.VARY: return new Vary(value); + case HttpLongMessage.CONTENT_TYPE: return new ContentType(value); + case HttpLongMessage.VIA: return new Via(value); + default: { + //throw new RuntimeException("Cannot parse header field: " + line); + System.err.println("Cannot parse header field, attempting to skip: " + line); + return fromBytes(bb); + } + } + } + else + { + throw new RuntimeException("Cannot parse message: " + line); + } + } + } + + private static String readLine(ByteBuffer bb, int i) throws IOException + { + StringBuilder sb = new StringBuilder(); + for (int limit = bb.limit(); i <= limit; ) + { + char c = (char) bb.get(i++); // readChar is not the same + sb.append(c); + if (c == '\r') + { + if (i > limit) + { + return null; + } + c = (char) bb.get(i++); + sb.append(c); + if (c == '\n') + { + bb.position(i); + return sb.substring(0, sb.length() - 2).toString(); + } + } + } + return null; + } + + private static String readWord(ByteBuffer bb, int i) throws IOException + { + StringBuilder sb = new StringBuilder(); + for (int limit = bb.limit(); i <= limit; ) + { + char c = (char) bb.get(i++); + if (c == ' ') + { + bb.position(i); + return sb.toString(); + } + sb.append(c); + } + return null; + } + + //private int isStatusCode(byte[] bs) + private int isStatusCode(String front) + { + String code = ""; + for (int i = 0; i < 4; i++) + { + //char c = (char) bs[i]; + char c = front.charAt(i); + if (i < 3) + { + if (c < '0' || c > '9') + { + return -1; + } + code += c; + } + else + { + if (c != ' ') + { + return -1; + } + } + } + return Integer.parseInt(code); + } + + + + + + + + + + + // FIXME: delete + @Deprecated @Override + public void writeMessage(DataOutputStream dos, ScribMessage m) throws IOException + { + dos.write(((HttpLongMessage) m).toBytes()); + dos.flush(); + } + + @Deprecated @Override + public ScribMessage readMessage(DataInputStream dis) throws IOException + { + byte[] bs = new byte[2]; + dis.readFully(bs); + String front = new String(bs, HttpLongMessageFormatter.cs); + if (front.equals(HttpLongMessage.CRLF)) // not sound? -- actually, due to sess types it is safe (same reason why interpreting any of these messages without context is sound) -- parsing doesn't have to follow the *full protocol* BNF any more to be sound + { + if (this.len == -1) + { + return new Body(""); + } + //String body = readLine(dis) + HttpMessage.CRLF; // HACK: assumes at least 1 CRLF + StringBuffer sb = new StringBuffer(); + //for (int i = body.length(); i < this.len; i++) + for (int i = 0; i < this.len; i++) + { + sb.append((char) dis.read()); + } + this.len = -1; + //return new Body(body + sb.toString()); + return new Body(sb.toString()); + } + + bs = new byte[2]; + dis.readFully(bs); + front += new String(bs, HttpLongMessageFormatter.cs); + // FIXME: factor out with HttpMessage op strings + int code = isStatusCode(front); + if (code > -1) + { + String reason = readLine(dis).trim(); // Whitespace already built into the message classes + switch (code) + { + case 200: return new _200(reason); + case 404: return new _404(reason); + default: throw new RuntimeException("Unknown status code: " + code); + } + } + else if (front.startsWith(HttpLongMessage.GET)) + { + String reql = readLine(dis).trim(); + String target = reql.substring(0, reql.indexOf(' ')); + String vers = reql.substring(reql.indexOf(' ') + 1).trim(); + vers = vers.substring(vers.indexOf('/') + 1); + return new RequestLine(target, vers); + } + else if (front.equals(HttpLongMessage.HTTP)) + { + dis.read(); // '/' + String word = readWord(dis); + return new HttpVersion(word); + } + else + { + String line = front + readLine(dis); + int colon = line.indexOf(':'); + if (colon > -1) + { + String name = line.substring(0, colon); + String value = line.substring(colon + 1).trim(); // Whitespace already built into the message classes + switch (name) + { + case HttpLongMessage.HOST: return new Host("value"); + case HttpLongMessage.USER_AGENT: return new UserAgent(value); + case HttpLongMessage.ACCEPT: return new Accept(value); + case HttpLongMessage.ACCEPT_LANGUAGE: return new AcceptLanguage(value); + case HttpLongMessage.ACCEPT_ENCODING: return new AcceptEncoding(value); + case HttpLongMessage.DO_NOT_TRACK: return new DoNotTrack(Integer.parseInt(value)); + case HttpLongMessage.CONNECTION: return new Connection(value); + + case HttpLongMessage.DATE: return new Date(value); + case HttpLongMessage.SERVER: return new Server(value); + case HttpLongMessage.LAST_MODIFIED: return new LastModified(value); + case HttpLongMessage.ETAG: return new ETag(value); + case HttpLongMessage.ACCEPT_RANGES: return new AcceptRanges(value); + case HttpLongMessage.CONTENT_LENGTH: + { + len = Integer.parseInt(value.trim()); + return new ContentLength(len); + } + case HttpLongMessage.VARY: return new Vary(value); + case HttpLongMessage.CONTENT_TYPE: return new ContentType(value); + case HttpLongMessage.VIA: return new Via(value); + default: throw new RuntimeException("Cannot parse header field: " + line); + } + } + else + { + throw new RuntimeException("Cannot parse message: " + line); + } + } + } + + private static String readLine(DataInputStream dis) throws IOException + { + StringBuilder sb = new StringBuilder(); + for (; true; ) + { + char c = (char) dis.read(); // readChar is not the same + sb.append(c); + if (c == '\r') + { + c = (char) dis.read(); + sb.append(c); + if (c == '\n') + { + return sb.substring(0, sb.length() - 2).toString(); + } + } + } + } + + private static String readWord(DataInputStream dis) throws IOException + { + StringBuilder sb = new StringBuilder(); + for (; true; ) + { + char c = (char) dis.read(); + if (c == ' ') + { + return sb.toString(); + } + sb.append(c); + } + } +} diff --git a/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/StartLine.java b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/StartLine.java new file mode 100644 index 000000000..d7eba14ef --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/StartLine.java @@ -0,0 +1,26 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package betty16.lec1.httplong.message; + +import org.scribble.core.type.name.Op; + +public abstract class StartLine extends HttpLongMessage +{ + private static final long serialVersionUID = 1L; + + public StartLine(Op op, String body) + { + super(op, body); + } +} diff --git a/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/client/Accept.java b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/client/Accept.java new file mode 100644 index 000000000..c3fdce712 --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/client/Accept.java @@ -0,0 +1,27 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package betty16.lec1.httplong.message.client; + +import betty16.lec1.httplong.HttpLong.Http.Http; +import betty16.lec1.httplong.message.HeaderField; + +public class Accept extends HeaderField +{ + private static final long serialVersionUID = 1L; + + public Accept(String text) + { + super(Http.ACCEPT, text); + } +} diff --git a/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/client/AcceptEncoding.java b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/client/AcceptEncoding.java new file mode 100644 index 000000000..c94c3dc10 --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/client/AcceptEncoding.java @@ -0,0 +1,27 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package betty16.lec1.httplong.message.client; + +import betty16.lec1.httplong.HttpLong.Http.Http; +import betty16.lec1.httplong.message.HeaderField; + +public class AcceptEncoding extends HeaderField +{ + private static final long serialVersionUID = 1L; + + public AcceptEncoding(String text) + { + super(Http.ACCEPTE, text); + } +} diff --git a/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/client/AcceptLanguage.java b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/client/AcceptLanguage.java new file mode 100644 index 000000000..3d8970bd5 --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/client/AcceptLanguage.java @@ -0,0 +1,27 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package betty16.lec1.httplong.message.client; + +import betty16.lec1.httplong.HttpLong.Http.Http; +import betty16.lec1.httplong.message.HeaderField; + +public class AcceptLanguage extends HeaderField +{ + private static final long serialVersionUID = 1L; + + public AcceptLanguage(String text) + { + super(Http.ACCEPTL, text); + } +} diff --git a/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/client/CacheControl.java b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/client/CacheControl.java new file mode 100644 index 000000000..986af0286 --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/client/CacheControl.java @@ -0,0 +1,29 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package betty16.lec1.httplong.message.client; + +import betty16.lec1.httplong.HttpLong.Http.Http; +import betty16.lec1.httplong.message.HeaderField; + +public class CacheControl extends HeaderField +{ + private static final long serialVersionUID = 1L; + + public CacheControl(String text) + { + //super(Http.CACHEC, text); + super(Http.PRAGMA, text); // FIXME + throw new RuntimeException("TODO"); + } +} diff --git a/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/client/Connection.java b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/client/Connection.java new file mode 100644 index 000000000..6fe6f347c --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/client/Connection.java @@ -0,0 +1,27 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package betty16.lec1.httplong.message.client; + +import betty16.lec1.httplong.HttpLong.Http.Http; +import betty16.lec1.httplong.message.HeaderField; + +public class Connection extends HeaderField +{ + private static final long serialVersionUID = 1L; + + public Connection(String text) + { + super(Http.CONN, text); + } +} diff --git a/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/client/Cookie.java b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/client/Cookie.java new file mode 100644 index 000000000..fb672a646 --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/client/Cookie.java @@ -0,0 +1,27 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package betty16.lec1.httplong.message.client; + +import betty16.lec1.httplong.HttpLong.Http.Http; +import betty16.lec1.httplong.message.HeaderField; + +public class Cookie extends HeaderField +{ + private static final long serialVersionUID = 1L; + + public Cookie(String val) + { + super(Http.COOKIE, val); + } +} diff --git a/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/client/DoNotTrack.java b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/client/DoNotTrack.java new file mode 100644 index 000000000..e7909f94b --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/client/DoNotTrack.java @@ -0,0 +1,27 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package betty16.lec1.httplong.message.client; + +import betty16.lec1.httplong.HttpLong.Http.Http; +import betty16.lec1.httplong.message.HeaderField; + +public class DoNotTrack extends HeaderField +{ + private static final long serialVersionUID = 1L; + + public DoNotTrack(int val) + { + super(Http.DNT, Integer.toString(val)); + } +} diff --git a/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/client/Host.java b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/client/Host.java new file mode 100644 index 000000000..01510acdf --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/client/Host.java @@ -0,0 +1,27 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package betty16.lec1.httplong.message.client; + +import betty16.lec1.httplong.HttpLong.Http.Http; +import betty16.lec1.httplong.message.HeaderField; + +public class Host extends HeaderField +{ + private static final long serialVersionUID = 1L; + + public Host(String host) + { + super(Http.HOST, host); + } +} diff --git a/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/client/Pragma.java b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/client/Pragma.java new file mode 100644 index 000000000..703a0ed6a --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/client/Pragma.java @@ -0,0 +1,27 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package betty16.lec1.httplong.message.client; + +import betty16.lec1.httplong.HttpLong.Http.Http; +import betty16.lec1.httplong.message.HeaderField; + +public class Pragma extends HeaderField +{ + private static final long serialVersionUID = 1L; + + public Pragma(String text) + { + super(Http.PRAGMA, text); + } +} diff --git a/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/client/RequestLine.java b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/client/RequestLine.java new file mode 100644 index 000000000..e2d4b9a82 --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/client/RequestLine.java @@ -0,0 +1,29 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package betty16.lec1.httplong.message.client; + +import betty16.lec1.httplong.HttpLong.Http.Http; +import betty16.lec1.httplong.message.StartLine; + + +// FIXME: not just GET +public class RequestLine extends StartLine +{ + private static final long serialVersionUID = 1L; + + public RequestLine(String reqtarget, String vers) + { + super(Http.REQUESTL, " " + reqtarget + " HTTP" + "/" + vers); + } +} diff --git a/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/client/UpgradeInsecureRequests.java b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/client/UpgradeInsecureRequests.java new file mode 100644 index 000000000..a85a62538 --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/client/UpgradeInsecureRequests.java @@ -0,0 +1,27 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package betty16.lec1.httplong.message.client; + +import betty16.lec1.httplong.HttpLong.Http.Http; +import betty16.lec1.httplong.message.HeaderField; + +public class UpgradeInsecureRequests extends HeaderField +{ + private static final long serialVersionUID = 1L; + + public UpgradeInsecureRequests(int val) + { + super(Http.UPGRADEIR, Integer.toString(val)); + } +} diff --git a/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/client/UserAgent.java b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/client/UserAgent.java new file mode 100644 index 000000000..cf59f8b73 --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/client/UserAgent.java @@ -0,0 +1,27 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package betty16.lec1.httplong.message.client; + +import betty16.lec1.httplong.HttpLong.Http.Http; +import betty16.lec1.httplong.message.HeaderField; + +public class UserAgent extends HeaderField +{ + private static final long serialVersionUID = 1L; + + public UserAgent(String text) + { + super(Http.USERA, text); + } +} diff --git a/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/server/AcceptRanges.java b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/server/AcceptRanges.java new file mode 100644 index 000000000..a664c5deb --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/server/AcceptRanges.java @@ -0,0 +1,27 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package betty16.lec1.httplong.message.server; + +import betty16.lec1.httplong.HttpLong.Http.Http; +import betty16.lec1.httplong.message.HeaderField; + +public class AcceptRanges extends HeaderField +{ + private static final long serialVersionUID = 1L; + + public AcceptRanges(String text) + { + super(Http.ACCEPTR, text); + } +} diff --git a/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/server/CRLF.java b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/server/CRLF.java new file mode 100644 index 000000000..b5ca83662 --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/server/CRLF.java @@ -0,0 +1,29 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package betty16.lec1.httplong.message.server; + +import betty16.lec1.httplong.message.HttpLongMessage; + +@Deprecated +public class CRLF extends HttpLongMessage +{ + private static final long serialVersionUID = 1L; + + public CRLF() + { + //super(Http.CRLF, HttpMessage.CRLF); // No: HttpMessage already appends the CRLF + //super(Http.CRLF, ""); + super(null, ""); + } +} diff --git a/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/server/ContentLength.java b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/server/ContentLength.java new file mode 100644 index 000000000..e9eeacb95 --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/server/ContentLength.java @@ -0,0 +1,27 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package betty16.lec1.httplong.message.server; + +import betty16.lec1.httplong.HttpLong.Http.Http; +import betty16.lec1.httplong.message.HeaderField; + +public class ContentLength extends HeaderField +{ + private static final long serialVersionUID = 1L; + + public ContentLength(Integer len) + { + super(Http.CONTENTL, len.toString()); + } +} diff --git a/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/server/ContentType.java b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/server/ContentType.java new file mode 100644 index 000000000..e7d3ad4a3 --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/server/ContentType.java @@ -0,0 +1,27 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package betty16.lec1.httplong.message.server; + +import betty16.lec1.httplong.HttpLong.Http.Http; +import betty16.lec1.httplong.message.HeaderField; + +public class ContentType extends HeaderField +{ + private static final long serialVersionUID = 1L; + + public ContentType(String type) + { + super(Http.CONTENTT, type); + } +} diff --git a/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/server/Date.java b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/server/Date.java new file mode 100644 index 000000000..0136c71d8 --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/server/Date.java @@ -0,0 +1,27 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package betty16.lec1.httplong.message.server; + +import betty16.lec1.httplong.HttpLong.Http.Http; +import betty16.lec1.httplong.message.HeaderField; + +public class Date extends HeaderField +{ + private static final long serialVersionUID = 1L; + + public Date(String date) + { + super(Http.DATE, date); + } +} diff --git a/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/server/ETag.java b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/server/ETag.java new file mode 100644 index 000000000..2621dbb8c --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/server/ETag.java @@ -0,0 +1,27 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package betty16.lec1.httplong.message.server; + +import betty16.lec1.httplong.HttpLong.Http.Http; +import betty16.lec1.httplong.message.HeaderField; + +public class ETag extends HeaderField +{ + private static final long serialVersionUID = 1L; + + public ETag(String tag) + { + super(Http.ETAG, tag); + } +} diff --git a/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/server/HttpVersion.java b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/server/HttpVersion.java new file mode 100644 index 000000000..103334a94 --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/server/HttpVersion.java @@ -0,0 +1,34 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package betty16.lec1.httplong.message.server; + +import betty16.lec1.httplong.HttpLong.Http.Http; +import betty16.lec1.httplong.message.HttpLongMessage; +import betty16.lec1.httplong.message.HttpLongMessageFormatter; + +public class HttpVersion extends HttpLongMessage +{ + private static final long serialVersionUID = 1L; + + public HttpVersion(String version) + { + super(Http.HTTPV, "/" + version); + } + + @Override + public byte[] toBytes() + { + return (getOpString(op) + getBody() + " ").getBytes(HttpLongMessageFormatter.cs); + } +} diff --git a/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/server/LastModified.java b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/server/LastModified.java new file mode 100644 index 000000000..97442bd9d --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/server/LastModified.java @@ -0,0 +1,27 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package betty16.lec1.httplong.message.server; + +import betty16.lec1.httplong.HttpLong.Http.Http; +import betty16.lec1.httplong.message.HeaderField; + +public class LastModified extends HeaderField +{ + private static final long serialVersionUID = 1L; + + public LastModified(String date) + { + super(Http.LASTM, date); + } +} diff --git a/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/server/Server.java b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/server/Server.java new file mode 100644 index 000000000..2730e261e --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/server/Server.java @@ -0,0 +1,27 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package betty16.lec1.httplong.message.server; + +import betty16.lec1.httplong.HttpLong.Http.Http; +import betty16.lec1.httplong.message.HeaderField; + +public class Server extends HeaderField +{ + private static final long serialVersionUID = 1L; + + public Server(String server) + { + super(Http.SERVER, server); + } +} diff --git a/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/server/StatusCode.java b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/server/StatusCode.java new file mode 100644 index 000000000..376d0bf23 --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/server/StatusCode.java @@ -0,0 +1,28 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package betty16.lec1.httplong.message.server; + +import org.scribble.core.type.name.Op; + +import betty16.lec1.httplong.message.HttpLongMessage; + +public abstract class StatusCode extends HttpLongMessage +{ + private static final long serialVersionUID = 1L; + + public StatusCode(Op code, String reason) + { + super(code, " " + reason); + } +} diff --git a/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/server/StrictTransportSecurity.java b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/server/StrictTransportSecurity.java new file mode 100644 index 000000000..0ef9ebbfe --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/server/StrictTransportSecurity.java @@ -0,0 +1,27 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package betty16.lec1.httplong.message.server; + +import betty16.lec1.httplong.HttpLong.Http.Http; +import betty16.lec1.httplong.message.HeaderField; + +public class StrictTransportSecurity extends HeaderField +{ + private static final long serialVersionUID = 1L; + + public StrictTransportSecurity(String server) + { + super(Http.STRICTTS, server); + } +} diff --git a/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/server/Vary.java b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/server/Vary.java new file mode 100644 index 000000000..25b078749 --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/server/Vary.java @@ -0,0 +1,27 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package betty16.lec1.httplong.message.server; + +import betty16.lec1.httplong.HttpLong.Http.Http; +import betty16.lec1.httplong.message.HeaderField; + +public class Vary extends HeaderField +{ + private static final long serialVersionUID = 1L; + + public Vary(String text) + { + super(Http.VARY, text); + } +} diff --git a/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/server/Via.java b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/server/Via.java new file mode 100644 index 000000000..fc0f933cd --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/server/Via.java @@ -0,0 +1,27 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package betty16.lec1.httplong.message.server; + +import betty16.lec1.httplong.HttpLong.Http.Http; +import betty16.lec1.httplong.message.HeaderField; + +public class Via extends HeaderField +{ + private static final long serialVersionUID = 1L; + + public Via(String text) + { + super(Http.VIA, text); + } +} diff --git a/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/server/_200.java b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/server/_200.java new file mode 100644 index 000000000..a5dcfe84c --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/server/_200.java @@ -0,0 +1,26 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package betty16.lec1.httplong.message.server; + +import betty16.lec1.httplong.HttpLong.Http.Http; + +public class _200 extends StatusCode +{ + private static final long serialVersionUID = 1L; + + public _200(String reason) + { + super(Http._200, reason); + } +} diff --git a/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/server/_404.java b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/server/_404.java new file mode 100644 index 000000000..4a3b3f2e8 --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec1/httplong/message/server/_404.java @@ -0,0 +1,26 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package betty16.lec1.httplong.message.server; + +import betty16.lec1.httplong.HttpLong.Http.Http; + +public class _404 extends StatusCode +{ + private static final long serialVersionUID = 1L; + + public _404(String reason) + { + super(Http._404, reason); + } +} diff --git a/scribble-demos/scrib/betty16/src/betty16/lec1/httpshort/HttpShort.scr b/scribble-demos/scrib/betty16/src/betty16/lec1/httpshort/HttpShort.scr new file mode 100644 index 000000000..fbda13229 --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec1/httpshort/HttpShort.scr @@ -0,0 +1,38 @@ +/** + * Assuming scribblec.sh in scribble-java root directory: + * + * ./scribblec.sh -d scribble-demos/scrib/betty16/src scribble-demos/scrib/betty16/src/betty16/lec1/httpshort/HttpShort.scr -api Http C + * + * $ javadoc -cp scribble-core/target/classes:scribble-runtime/target/classes:scribble-demos/scrib/betty16/src -subpackages betty16.lec1.httpshort.HttpShort.Http -d scribble-demos/scrib/betty16/javadoc/httpshort + * + */ + + +module betty16.lec1.httpshort.HttpShort; + + +sig "betty16.lec1.httpshort.message.client.Request" + from "betty16/httpshort/message/Request.java" + as Request; + +sig "betty16.lec1.httpshort.message.server.Response" + from "betty16/shortvers/message/Response.java" + as Response; + + +global protocol Http(role C, role S) { + Request from C to S; + Response from S to C; +} + + + + + + + + + + + + diff --git a/scribble-demos/scrib/betty16/src/betty16/lec1/httpshort/HttpShortC.java b/scribble-demos/scrib/betty16/src/betty16/lec1/httpshort/HttpShortC.java new file mode 100644 index 000000000..789a31ac0 --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec1/httpshort/HttpShortC.java @@ -0,0 +1,57 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package betty16.lec1.httpshort; + +import static betty16.lec1.httpshort.HttpShort.Http.Http.C; +import static betty16.lec1.httpshort.HttpShort.Http.Http.Response; +import static betty16.lec1.httpshort.HttpShort.Http.Http.S; + +import org.scribble.runtime.net.SocketChannelEndpoint; +import org.scribble.runtime.session.MPSTEndpoint; +import org.scribble.runtime.util.Buf; + +import betty16.lec1.httpshort.HttpShort.Http.Http; +import betty16.lec1.httpshort.HttpShort.Http.roles.C; +import betty16.lec1.httpshort.HttpShort.Http.statechans.C.EndSocket; +import betty16.lec1.httpshort.HttpShort.Http.statechans.C.Http_C_1; +import betty16.lec1.httpshort.message.HttpShortMessageFormatter; +import betty16.lec1.httpshort.message.client.Request; +import betty16.lec1.httpshort.message.server.Response; + +public class HttpShortC { + + public static void main(String[] args) throws Exception { + Http http = new Http(); + try (MPSTEndpoint client = new MPSTEndpoint<>(http, C, + new HttpShortMessageFormatter())) { + String host = "example.com"; int port = 80; String file = "/"; + //String host = "localhost"; int port = 8080; String file = "/"; + + client.request(S, SocketChannelEndpoint::new, host, port); + new HttpShortC().run(new Http_C_1(client), host, file); + } + } + + private EndSocket run(Http_C_1 c1, String host, String file) throws Exception { + Buf buf = new Buf<>(); + + EndSocket end = + c1.send(S, new Request(file, "1.1", host)) + .receive(S, Response, buf); + + System.out.println("Response:\n" + buf.val); + + return end; + } +} diff --git a/scribble-demos/scrib/betty16/src/betty16/lec1/httpshort/HttpShortS.java b/scribble-demos/scrib/betty16/src/betty16/lec1/httpshort/HttpShortS.java new file mode 100644 index 000000000..bbb62f6de --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec1/httpshort/HttpShortS.java @@ -0,0 +1,64 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package betty16.lec1.httpshort; + +import static betty16.lec1.httpshort.HttpShort.Http.Http.C; +import static betty16.lec1.httpshort.HttpShort.Http.Http.Request; +import static betty16.lec1.httpshort.HttpShort.Http.Http.S; + +import java.io.IOException; + +import org.scribble.main.ScribRuntimeException; +import org.scribble.runtime.net.ScribServerSocket; +import org.scribble.runtime.net.SocketChannelServer; +import org.scribble.runtime.session.MPSTEndpoint; +import org.scribble.runtime.util.Buf; + +import betty16.lec1.httpshort.HttpShort.Http.Http; +import betty16.lec1.httpshort.HttpShort.Http.roles.S; +import betty16.lec1.httpshort.HttpShort.Http.statechans.S.Http_S_1; +import betty16.lec1.httpshort.HttpShort.Http.statechans.S.Http_S_2; +import betty16.lec1.httpshort.message.HttpShortMessageFormatter; +import betty16.lec1.httpshort.message.client.Request; +import betty16.lec1.httpshort.message.server.Response; + +public class HttpShortS { + + public static void main(String[] args) throws IOException { + try (ScribServerSocket ss = new SocketChannelServer(8080)) { + while (true) { + Http http = new Http(); + try (MPSTEndpoint server = new MPSTEndpoint<>(http, S, + new HttpShortMessageFormatter())) { + server.accept(ss, C); + + run(new Http_S_1(server)); + } + catch (IOException | ClassNotFoundException | ScribRuntimeException e) + { + e.printStackTrace(); + } + } + } + } + + private static void run(Http_S_1 s1) + throws ClassNotFoundException, ScribRuntimeException, IOException { + Buf buf = new Buf<>(); + + Http_S_2 s2 = s1.receive(C, Request, buf); + System.out.println("Request:\n" + buf.val); + s2.send(C, new Response("1.1", "Hello, World!")); + } +} diff --git a/scribble-demos/scrib/betty16/src/betty16/lec1/httpshort/message/HttpShortMessage.java b/scribble-demos/scrib/betty16/src/betty16/lec1/httpshort/message/HttpShortMessage.java new file mode 100644 index 000000000..424e90e63 --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec1/httpshort/message/HttpShortMessage.java @@ -0,0 +1,67 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package betty16.lec1.httpshort.message; + +import org.scribble.runtime.message.ScribMessage; +import org.scribble.core.type.name.Op; + +import betty16.lec1.httpshort.HttpShort.Http.Http; + +public abstract class HttpShortMessage extends ScribMessage +{ + private static final long serialVersionUID = 1L; + + public static final String GET = "GET"; + public static final String HTTP = "HTTP"; + + public static final String CRLF = "\r\n"; + + public HttpShortMessage(Op op, String m) + { + super(op, m); + } + + public String getHeadersAndBody() + { + return (this.payload.length == 0) ? "" : (String) this.payload[0]; + } + + public byte[] toBytes() + { + // FIXME: factor better with Request/Response (e.g. " " after op, terminal CRLF, etc) + return (getOpString(this.op) + getHeadersAndBody()).getBytes(HttpShortMessageFormatter.cs); // Can give "utf-8" as arg directly + } + + @Override + public String toString() + { + return new String(toBytes()); + } + + protected static String getOpString(Op op) + { + if (op.equals(Http.Request)) + { + return HttpShortMessage.GET; + } + else if (op.equals(Http.Response)) + { + return HttpShortMessage.HTTP; + } + else + { + throw new RuntimeException("TODO: " + op); + } + } +} diff --git a/scribble-demos/scrib/betty16/src/betty16/lec1/httpshort/message/HttpShortMessageFormatter.java b/scribble-demos/scrib/betty16/src/betty16/lec1/httpshort/message/HttpShortMessageFormatter.java new file mode 100644 index 000000000..6e3f45924 --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec1/httpshort/message/HttpShortMessageFormatter.java @@ -0,0 +1,274 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package betty16.lec1.httpshort.message; + +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.Charset; +import java.util.Arrays; + +import org.scribble.runtime.message.ScribMessage; +import org.scribble.runtime.message.ScribMessageFormatter; + +import betty16.lec1.httpshort.message.client.Request; +import betty16.lec1.httpshort.message.server.Response; + +public class HttpShortMessageFormatter implements ScribMessageFormatter +{ + public static final Charset cs = Charset.forName("UTF8"); + //private static CharsetDecoder cd = cs.newDecoder(); + + public HttpShortMessageFormatter() + { + + } + + @Override + public byte[] toBytes(ScribMessage m) throws IOException + { + return ((HttpShortMessage) m).toBytes(); + } + + @Override + public ScribMessage fromBytes(ByteBuffer bb) + throws IOException, ClassNotFoundException + { + bb.flip(); + int rem = bb.remaining(); + if (rem < 2) + { + bb.compact(); + return null; + } + + String curr = new String(Arrays.copyOf(bb.array(), bb.remaining()), + HttpShortMessageFormatter.cs); + String endOfHeaders = HttpShortMessage.CRLF + HttpShortMessage.CRLF; + if (!curr.contains(endOfHeaders)) + { + bb.compact(); + return null; + } + + if (curr.contains(Response.CONTENT_LENGTH)) + { + int eoh = curr.indexOf(endOfHeaders); + if (eoh == -1) + { + bb.compact(); + return null; + } + String contentLenSplit = curr + .substring(curr.indexOf(Response.CONTENT_LENGTH)); + int len = Integer.parseInt( + contentLenSplit.substring(Response.CONTENT_LENGTH.length() + 2, + contentLenSplit.indexOf('\r')).trim()); + if (curr.length() < eoh+4) + { + bb.compact(); + return null; + } + String body = curr.substring(eoh+4); + if (body.getBytes(HttpShortMessageFormatter.cs).length < len) + { + bb.compact(); + return null; + } + byte[] bs = new byte[bb.remaining()]; // FIXME: hardcoded Response parsing based on presence of Content-Length + bb.get(bs); + bb.compact(); + return parseResponse(new String(bs, HttpShortMessageFormatter.cs)); + } + else + { + byte[] bs = new byte[bb.remaining()]; + bb.get(bs); + bb.compact(); + return parseRequest(new String(bs, HttpShortMessageFormatter.cs)); // FIXME: assuming empty-body Request if no Content-Length + } + } + + // Assumes no body + private static HttpShortMessage parseRequest(String msg) + { + String get = null; + String http = null; + String host = null; + String userA = null; + String accept = null; + String acceptL = null; + String acceptE = null; + String dnt = null; + String connection = null; + String upgradeIR = null; + String cookie = null; + + for (boolean eoh = false; !eoh; ) + { + //if (msg.startsWith(HttpMessage.CRLF + HttpMessage.CRLF)) + if (msg.startsWith(HttpShortMessage.CRLF)) // First CRLF already trimmed after last header + { + eoh = true; + //msg = msg.substring(4); + msg = msg.substring(2); + break; + } + + msg = msg.replace("\\A\\s+", ""); + int i = msg.indexOf(":"); + if (i == -1) + { + throw new RuntimeException("Shouldn't get in here: " + msg); + } + if (msg.startsWith(HttpShortMessage.GET)) // FIXME + { + int j = msg.indexOf(' '); + get = msg.substring(j+1, msg.indexOf(' ', j+1)).trim(); + j = msg.indexOf('\r'); + http = msg.substring(msg.indexOf('/')+1, j).trim(); + msg = msg.substring(j+2); + } + else + { + String header = msg.substring(0, i); + int j = msg.indexOf("\r"); + switch (header) // FIXME: duplicates not checked + { + case Request.HOST: host = msg.substring(i+1, j).trim(); break; + case Request.USER_AGENT: userA = msg.substring(i+1, j).trim(); break; + case Request.ACCEPT: accept = msg.substring(i+1, j).trim(); break; + case Request.ACCEPT_LANGUAGE: acceptL = msg.substring(i+1, j).trim(); break; + case Request.ACCEPT_ENCODING: acceptE = msg.substring(i+1, j).trim(); break; + case Request.DO_NOT_TRACK: dnt = msg.substring(i+1, j).trim(); break; + case Request.CONNECTION: connection = msg.substring(i+1, j).trim(); break; + case Request.UPGRADE_INSECURE_REQUESTS: upgradeIR = msg.substring(i+1, j).trim(); break; + case Request.COOKIE: cookie = msg.substring(i+1, j).trim(); break; + //case Request.REFERER: referer = msg.substring(i+1, j).trim(); break; + //case Request.CACHECONTROL: cacheC = msg.substring(i+1, j).trim(); break; + default: { + //throw new RuntimeException("Cannot parse header field: " + msg.substring(0, j)); + System.err.println("Cannot parse header field, attempting to skip: " + msg.substring(0, j)); + } + } + msg = msg.substring(j+2); + } + } + if (!msg.isEmpty()) + { + throw new RuntimeException("Shouldn't get in here: " + msg); + } + return new Request(get, http, host, userA, accept, acceptL, acceptE, dnt, + connection, upgradeIR, cookie); + } + + private static HttpShortMessage parseResponse(String msg) + { + String httpv = null; + String ack = null; + String date = null; + String server = null; + String strictTS = null; + String lastMod = null; + String eTag = null; + String acceptR = null; + String contentL = null; + String vary = null; + String contentT = null; + String via = null; + String body = null; + + for (boolean eoh = false; !eoh; ) + { + //if (msg.startsWith(HttpMessage.CRLF + HttpMessage.CRLF)) + if (msg.startsWith(HttpShortMessage.CRLF)) // First CRLF already trimmed after last header + { + eoh = true; + //msg = msg.substring(4); + msg = msg.substring(2); + break; + } + + msg = msg.trim(); + int i = msg.indexOf(":"); + if (i == -1) + { + throw new RuntimeException("Shouldn't get in here: " + msg); + } + if (msg.startsWith(HttpShortMessage.HTTP)) // FIXME + { + int j = msg.indexOf(' '); + httpv = msg.substring(msg.indexOf('/')+1, j); + + int k = msg.indexOf('\r'); + ack = msg.substring(j+1, k); + /*if (!ack.equals("200 OK")) + { + if (!ack.startsWith("404")) + { + throw new RuntimeException("[TODO]: " + msg); + } + } + ack = "OK"; // Hardcoded*/ + msg = msg.substring(k+2); + } + else + { + String header = msg.substring(0, i); + int j = msg.indexOf("\r"); + switch (header) + { + case Response.DATE: date = msg.substring(i+1, j).trim(); break; + case Response.SERVER: server = msg.substring(i+1, j).trim(); break; + case Response.STRICT_TRANSPORT_SECURITY: strictTS = msg.substring(i+1, j).trim(); break; + case Response.LAST_MODIFIED: lastMod = msg.substring(i+1, j).trim(); break; + case Response.ETAG: eTag = msg.substring(i+1, j).trim(); break; + case Response.ACCEPT_RANGES: acceptR = msg.substring(i+1, j).trim(); break; + case Response.CONTENT_LENGTH: contentL = msg.substring(i+1, j).trim(); break; + case Response.VARY: vary = msg.substring(i+1, j).trim(); break; + case Response.CONTENT_TYPE: contentT = msg.substring(i+1, j).trim(); break; + case Response.VIA: via = msg.substring(i+1, j).trim(); break; + default: + //throw new RuntimeException("Cannot parse header field: " + msg.substring(0, msg.indexOf('\r'))); + System.err + .println("[Warning] Attempting to skip over response field: " + + header + "\n" + msg.substring(i + 1, j).trim()); + } + msg = msg.substring(j+2); + } + } + body = msg; + return new Response(httpv, ack, date, server, strictTS, lastMod, eTag, + acceptR, contentL, vary, contentT, via, body); + } + + + + + + + // TODO: delete + @Deprecated @Override + public void writeMessage(DataOutputStream dos, ScribMessage m) throws IOException + { + throw new RuntimeException("Shouldn't get in here: " + m); + } + + @Deprecated @Override + public ScribMessage readMessage(DataInputStream dis) throws IOException + { + throw new RuntimeException("Shouldn't get in here: "); + } +} diff --git a/scribble-demos/scrib/betty16/src/betty16/lec1/httpshort/message/client/Request.java b/scribble-demos/scrib/betty16/src/betty16/lec1/httpshort/message/client/Request.java new file mode 100644 index 000000000..b8fef7cdb --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec1/httpshort/message/client/Request.java @@ -0,0 +1,58 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package betty16.lec1.httpshort.message.client; + +import betty16.lec1.httpshort.HttpShort.Http.Http; +import betty16.lec1.httpshort.message.HttpShortMessage; + +public class Request extends HttpShortMessage { + + private static final long serialVersionUID = 1L; + + // TODO: make case-insensitive + public static final String HOST = "Host"; + public static final String USER_AGENT = "User-Agent"; + public static final String ACCEPT = "Accept"; + public static final String ACCEPT_LANGUAGE = "Accept-Language"; + public static final String ACCEPT_ENCODING = "Accept-Encoding"; + public static final String DO_NOT_TRACK = "DNT"; + public static final String CONNECTION = "Connection"; + public static final String UPGRADE_INSECURE_REQUESTS = "Upgrade-Insecure-Requests"; + public static final String COOKIE = "Cookie"; + public static final String REFERER = "Referer"; + public static final String CACHECONTROL = "Cache-Control"; + + public Request(String get, String http, String host, String userA, String accept, String acceptL, String acceptE, String dnt, String connection, String upgradeIR, String cookie) { + super(Http.Request, getHeadersAndBody(get, http, host, userA, accept, acceptL, acceptE, dnt, connection, upgradeIR, cookie)); + } + + public Request(String get, String http, String host) { + this(get, http, host, null, null, null, null, null, null, null, null); + } + + protected static String getHeadersAndBody(String get, String http, String host, String userA, String accept, String acceptL, String acceptE, String dnt, String connection, String upgradeIR, String cookie) { + return " " + + get + " " + HttpShortMessage.HTTP + "/" + http + HttpShortMessage.CRLF + + Request.HOST + ": " + host + HttpShortMessage.CRLF + + ((userA == null) ? "" : Request.USER_AGENT + ": " + userA + HttpShortMessage.CRLF) + + ((accept == null) ? "" : Request.ACCEPT + ": " + accept + HttpShortMessage.CRLF) + + ((acceptL == null) ? "" : Request.ACCEPT_LANGUAGE + ": " + acceptL + HttpShortMessage.CRLF) + + ((acceptE == null) ? "" : Request.ACCEPT_ENCODING + ": " + acceptE + HttpShortMessage.CRLF) + + ((dnt == null) ? "" : Request.DO_NOT_TRACK + ": " + dnt + HttpShortMessage.CRLF) + + ((connection == null) ? "" : Request.CONNECTION + ": " + connection + HttpShortMessage.CRLF) + + ((upgradeIR == null) ? "" : Request.UPGRADE_INSECURE_REQUESTS + ": " + upgradeIR + HttpShortMessage.CRLF) + + ((cookie == null) ? "" : Request.COOKIE + ": " + cookie + HttpShortMessage.CRLF) + + "" + HttpShortMessage.CRLF; // Empty body + } +} diff --git a/scribble-demos/scrib/betty16/src/betty16/lec1/httpshort/message/server/Response.java b/scribble-demos/scrib/betty16/src/betty16/lec1/httpshort/message/server/Response.java new file mode 100644 index 000000000..aa1cd2468 --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec1/httpshort/message/server/Response.java @@ -0,0 +1,99 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package betty16.lec1.httpshort.message.server; + +import betty16.lec1.httpshort.HttpShort.Http.Http; +import betty16.lec1.httpshort.message.HttpShortMessage; + +public class Response extends HttpShortMessage +{ + private static final long serialVersionUID = 1L; + + // TODO: make case-insensitive + public static final String DATE = "Date"; + public static final String CONTENT_TYPE = "Content-Type"; + public static final String _404 = "404"; + public static final String _200 = "200"; + public static final String ACCEPT_RANGES = "Accept-Ranges"; + public static final String LAST_MODIFIED = "Last-Modified"; + public static final String VARY = "Vary"; + public static final String SERVER = "Server"; + public static final String STRICT_TRANSPORT_SECURITY = "Strict-Transport-Security"; + public static final String VIA = "Via"; + public static final String ETAG = "ETag"; + public static final String CONTENT_LENGTH = "Content-Length"; + + /*HTTP/1.1 200 OK + Date: Mon, 13 Jun 2016 19:42:34 GMT + Server: Apache + Strict-Transport-Security: max-age=31536000; preload; includeSubDomains + Strict-Transport-Security: max-age=31536000; preload; includeSubDomains // BUG? (Apache configuration) + Last-Modified: Thu, 14 Apr 2016 12:46:24 GMT + ETag: "74a-53071482f6e0f" + Accept-Ranges: bytes + Content-Length: 1866 + Vary: Accept-Encoding + Content-Type: text/html + Via: 1.1 www.doc.ic.ac.uk*/ + public Response(String httpv, String ack, String date, String server, String strictTS, String lastMod, + String eTag, String acceptR, String contentL, String vary, String contentT, String via, String body) + { + super(Http.Response, getHeadersAndBody( + httpv, ack, date, server, strictTS, lastMod, eTag, acceptR, contentL, vary, contentT, via, body)); + } + + /*public Response(String httpv, String ack, String contentL, String body) + { + super(Http.RESPONSE, getHeadersAndBody(httpv, ack, contentL, body)); + }*/ + + public Response(String httpv, String body) + { + this(httpv, Response._200 + " OK", null, null, null, null, null, null, Integer.toString(body.length()), null, null, null, body); + } + + // ack includes "op", e.g. 200, 404, ... + protected static String getHeadersAndBody(String httpv, String ack, String date, String server, String strictTS, String lastMod, + String eTag, String acceptR, String contentL, String vary, String contentT, String via, String body) + { + if (!ack.startsWith(Response._200) && !ack.startsWith(Response._404)) + { + throw new RuntimeException("[TODO]: " + ack); + } + return "/" + httpv + " " + + ack + HttpShortMessage.CRLF // Hardcoded + + ((date == null) ? "" : Response.DATE + ": " + date + HttpShortMessage.CRLF) + + ((server == null) ? "" : Response.SERVER + ": " + server + HttpShortMessage.CRLF) + + ((strictTS == null) ? "" : Response.STRICT_TRANSPORT_SECURITY + ": " + strictTS + HttpShortMessage.CRLF) + + ((lastMod == null) ? "" : Response.LAST_MODIFIED + ": " + lastMod + HttpShortMessage.CRLF) + + ((eTag == null) ? "" : Response.ETAG + ": " + eTag + HttpShortMessage.CRLF) + + ((acceptR == null) ? "" : Response.ACCEPT_RANGES + ": " + acceptR + HttpShortMessage.CRLF) + + Response.CONTENT_LENGTH + ": " + contentL + HttpShortMessage.CRLF + + ((vary == null) ? "" : Response.VARY + ": " + vary + HttpShortMessage.CRLF) + + ((contentT == null) ? "" : Response.CONTENT_TYPE + ": " + contentT + HttpShortMessage.CRLF) + + ((via == null) ? "" : Response.VIA + ": " + via + HttpShortMessage.CRLF) + + HttpShortMessage.CRLF // Empty line for end of headers + + body + HttpShortMessage.CRLF; + } + + /*// 404 + protected static String getHeadersAndBody(String httpv, String ack, String contentL, String body) + { + return "/" + httpv + " " + + _404 + ack + HttpMessage.CRLF // Hardcoded + + Response.CONTENT_LENGTH + ": " + contentL + HttpMessage.CRLF + + HttpMessage.CRLF // Empty line for end of headers + + body + HttpMessage.CRLF; + }*/ +} diff --git a/scribble-demos/scrib/betty16/src/betty16/lec1/misc/Choice1.scr b/scribble-demos/scrib/betty16/src/betty16/lec1/misc/Choice1.scr new file mode 100644 index 000000000..1b967f952 --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec1/misc/Choice1.scr @@ -0,0 +1,14 @@ +module betty16.lec1.misc.Choice1; + + +global protocol Proto1(role A, role B, role C) { + choice at A { + 1() from A to B; + 3() from B to C; + 4() from C to A; + } or { + 2() from A to B; + 3() from B to C; + 5() from C to A; + } +} diff --git a/scribble-demos/scrib/betty16/src/betty16/lec1/misc/Choice2.scr b/scribble-demos/scrib/betty16/src/betty16/lec1/misc/Choice2.scr new file mode 100644 index 000000000..de85481c1 --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec1/misc/Choice2.scr @@ -0,0 +1,69 @@ +module betty16.lec1.misc.Choice2; + + +global protocol Proto1(role A, role B, role C) { + choice at A { + 1() from A to B; + 3() from B to C; + 4() from C to A; + } or { + 2() from A to B; + 3() from B to C; + 4() from C to A; + } +} + + +global protocol Proto2(role A, role B, role C) { + choice at A { + 1() from A to B; + 3() from B to C; + do Merge2(A, C); + } or { + 2() from A to B; + 3() from B to C; + do Merge2(A, C); + } +} + +aux global protocol Merge2(role A, role C) { + 4() from C to A; +} + + +global protocol Proto3(role A, role B, role C) { + choice at A { + 1() from A to B; + 3() from B to C; + do Merge3(A, C); + } or { + 2() from A to B; + 3() from B to C; + do Merge3(A, C); + } +} + +aux global protocol Merge3(role A, role C) { + 4() from A to C; +} + + +global protocol Proto4(role A, role B, role C) { + choice at A { + 1() from A to B; + 3() from B to C; + do Merge4(A, C); + } or { + 2() from A to B; + 3() from B to C; + do Merge4(A, C); + } +} + +aux global protocol Merge4(role A, role C) { + choice at A { + 4() from A to C; + } or { + 5() from A to C; + } +} diff --git a/scribble-demos/scrib/betty16/src/betty16/lec1/misc/Choice3.scr b/scribble-demos/scrib/betty16/src/betty16/lec1/misc/Choice3.scr new file mode 100644 index 000000000..9e0ffd1b7 --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec1/misc/Choice3.scr @@ -0,0 +1,15 @@ +module betty16.lec1.misc.Choice3; + + +global protocol Proto1(role A, role B, role C) { + choice at A { + 1() from A to B; + 2() from A to C; + 3() from B to C; + 4() from C to A; + } or { + 1b() from A to B; + 3() from B to C; + 4() from C to A; + } +} diff --git a/scribble-demos/scrib/betty16/src/betty16/lec1/misc/Choice4.scr b/scribble-demos/scrib/betty16/src/betty16/lec1/misc/Choice4.scr new file mode 100644 index 000000000..9ff9de823 --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec1/misc/Choice4.scr @@ -0,0 +1,11 @@ +module betty16.lec1.misc.Choice4; + + +global protocol Proto1(role A, role B, role C) { + choice at A { + 1() from A to B; + 2() from A to C; + } or { + 3() from A to B; + } +} diff --git a/scribble-demos/scrib/betty16/src/betty16/lec1/misc/LocatedChoice.scr b/scribble-demos/scrib/betty16/src/betty16/lec1/misc/LocatedChoice.scr new file mode 100644 index 000000000..406f9cd31 --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec1/misc/LocatedChoice.scr @@ -0,0 +1,23 @@ +module betty16.lec1.misc.LocatedChoice; + + +global protocol Proto1(role A, role B, role C) { + choice at A { + 1() from A to B; + 2() from A to C; + } or { + 3() from A to B; + 4() from A to C; + } +} + + +global protocol Proto2(role A, role B, role C) { + choice at A { + 1() from A to B; + 2() from A to C; + } or { + 4() from A to C; + 3() from A to B; + } +} diff --git a/scribble-demos/scrib/betty16/src/betty16/lec1/misc/LocatedChoice2.scr b/scribble-demos/scrib/betty16/src/betty16/lec1/misc/LocatedChoice2.scr new file mode 100644 index 000000000..3978d0892 --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec1/misc/LocatedChoice2.scr @@ -0,0 +1,15 @@ +module betty16.lec1.misc.LocatedChoice2; + +data "java.lang.Integer" from "rt.jar" as Int; + +global protocol Proto1(role A, role B, role C) { + choice at A { + buyer1(Int) from A to B; // Total + (Int) from B to A; // B will pay this much + buyer2(Int) from A to C; // C will pay remainder + } or { + buyer1(Int) from A to C; // Total + (Int) from C to A; // C will pay this much + buyer2(Int) from A to B; // B will pay remainder + } +} diff --git a/scribble-demos/scrib/betty16/src/betty16/lec1/misc/Messaging.scr b/scribble-demos/scrib/betty16/src/betty16/lec1/misc/Messaging.scr new file mode 100644 index 000000000..0c30b83fb --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec1/misc/Messaging.scr @@ -0,0 +1,15 @@ +module betty16.lec1.misc.Messaging; + + +data "java.lang.Integer" from "rt.jar" as Int; +data "java.lang.String" from "rt.jar" as String; + + +global protocol Proto1(role A, role B) { + 123(Int, String) from A to B; +} + + +global protocol Proto2(role A, role B) { + () from A to B; +} diff --git a/scribble-demos/scrib/betty16/src/betty16/lec1/misc/Protocol1a.scr b/scribble-demos/scrib/betty16/src/betty16/lec1/misc/Protocol1a.scr new file mode 100644 index 000000000..3f3bf5dfd --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec1/misc/Protocol1a.scr @@ -0,0 +1,15 @@ +module betty16.lec1.misc.Protocol1a; + + +global protocol Proto1(role A, role B, role C) { + choice at A { + rec X { + 1() from A to B; + 1() from B to C; + continue X; + } + } or { + 2() from A to B; + 2() from B to C; + } +} diff --git a/scribble-demos/scrib/betty16/src/betty16/lec1/misc/Protocol1b.scr b/scribble-demos/scrib/betty16/src/betty16/lec1/misc/Protocol1b.scr new file mode 100644 index 000000000..6e7420adb --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec1/misc/Protocol1b.scr @@ -0,0 +1,15 @@ +module betty16.lec1.misc.Protocol1b; + + +global protocol Proto1(role A, role B, role C) { + choice at A { + rec X { + 1() from A to B; + //1() from B to C; + continue X; + } + } or { + 2() from A to B; + 2() from B to C; + } +} diff --git a/scribble-demos/scrib/betty16/src/betty16/lec1/misc/Protocol1c.scr b/scribble-demos/scrib/betty16/src/betty16/lec1/misc/Protocol1c.scr new file mode 100644 index 000000000..b35890270 --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec1/misc/Protocol1c.scr @@ -0,0 +1,14 @@ +module betty16.lec1.misc.Protocol1c; + + +global protocol Proto1(role A, role B, role C) { + choice at A { + rec X { + 1() from A to B; + continue X; + } + } or { + 2() from A to B; + } + 2() from C to B; +} diff --git a/scribble-demos/scrib/betty16/src/betty16/lec1/misc/Protocol2.scr b/scribble-demos/scrib/betty16/src/betty16/lec1/misc/Protocol2.scr new file mode 100644 index 000000000..354563a8b --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec1/misc/Protocol2.scr @@ -0,0 +1,14 @@ +module betty16.lec1.misc.Protocol2; + + +global protocol Proto1(role A, role B, role C) { + rec X { + choice at A { + 1() from A to B; + continue X; + } or { + 2() from A to B; + 2() from B to C; + } + } +} diff --git a/scribble-demos/scrib/betty16/src/betty16/lec1/misc/Recursion1.scr b/scribble-demos/scrib/betty16/src/betty16/lec1/misc/Recursion1.scr new file mode 100644 index 000000000..cdca4bc74 --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec1/misc/Recursion1.scr @@ -0,0 +1,16 @@ +module betty16.lec1.misc.Recursion1; + + +global protocol Proto1(role A, role B) { + rec X { + choice at A { + 1() from A to B; + continue X; + 2() from A to B; + } or { + 3() from A to B; + } + 4() from A to B; + } + 5() from A to B; +} diff --git a/scribble-demos/scrib/betty16/src/betty16/lec1/misc/Recursion2.scr b/scribble-demos/scrib/betty16/src/betty16/lec1/misc/Recursion2.scr new file mode 100644 index 000000000..21b89abfa --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec1/misc/Recursion2.scr @@ -0,0 +1,10 @@ +module betty16.lec1.misc.Recursion2; + + +global protocol Proto1(role A, role B) { + rec X { + 1() from A to B; + continue X; + } + 2() from A to B; +} diff --git a/scribble-demos/scrib/betty16/src/betty16/lec1/misc/Recursion3.scr b/scribble-demos/scrib/betty16/src/betty16/lec1/misc/Recursion3.scr new file mode 100644 index 000000000..2bb13ab5c --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec1/misc/Recursion3.scr @@ -0,0 +1,10 @@ +module betty16.lec1.misc.Recursion3; + + +global protocol Proto1(role A, role B, role C, role D) { + rec X { + 1() from A to B; + continue X; + } + 2() from C to D; +} diff --git a/scribble-demos/scrib/betty16/src/betty16/lec1/misc/RoleEnabling.scr b/scribble-demos/scrib/betty16/src/betty16/lec1/misc/RoleEnabling.scr new file mode 100644 index 000000000..a6b4b9147 --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec1/misc/RoleEnabling.scr @@ -0,0 +1,17 @@ +module betty16.lec1.misc.RoleEnabling; + + +global protocol Proto1(role A, role B, role C) { + choice at A { + 1() from A to B; + 1() from B to C; + } or { + //2() from A to B; + 2() from B to A; + choice at B { + 3() from B to C; + } or { + 4() from B to C; + } + } +} diff --git a/scribble-demos/scrib/betty16/src/betty16/lec1/nego/Negotiate.scr b/scribble-demos/scrib/betty16/src/betty16/lec1/nego/Negotiate.scr new file mode 100644 index 000000000..adbf5e88a --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec1/nego/Negotiate.scr @@ -0,0 +1,70 @@ +/** + * Assuming scribblec.sh in scribble-java root directory: + * + * E.g., ./scribblec.sh scribble-demos/scrib/betty16/src/betty16/lec1/nego/Negotiate.scr -fsm Nego1 C + */ + + +module betty16.lec1.nego.Negotiate; + + +data "test.nego.SAP" from "test/nego/SAP.java" as SAP; + + +// C = Consumer, P = Producer +global protocol Nego1(role C, role P) { + propose(SAP) from C to P; + rec X { + choice at P { + accpt() from P to C; + confirm() from C to P; + } or { + reject() from P to C; + } or { + propose(SAP) from P to C; + choice at C { + accpt() from C to P; + confirm() from P to C; + } or { + reject() from C to P; + } or { + propose(SAP) from C to P; + continue X; + } + } + } +} + + +global protocol Nego2(role C, role P) +{ + propose(SAP) from C to P; + do Nego2Aux(P, C); +} + +aux global protocol Nego2Aux(role A, role B) +{ + choice at A { + accpt() from A to B; + confirm() from B to A; + } or { + reject() from A to B; + } or { + propose(SAP) from A to B; + do Nego2Aux(B, A); + } +} + + +global protocol Nego3(role C, role P) +{ + propose(SAP) from C to P; + choice at P { + accpt() from P to C; + confirm() from C to P; + } or { + reject() from P to C; + } or { + do Nego3(P, C); + } +} diff --git a/scribble-demos/scrib/betty16/src/betty16/lec2/adder/Adder.scr b/scribble-demos/scrib/betty16/src/betty16/lec2/adder/Adder.scr new file mode 100644 index 000000000..9216608b8 --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec2/adder/Adder.scr @@ -0,0 +1,34 @@ +/** + * Assuming scribblec.sh in scribble-java root directory: + * + * (1) Check Adder protocol: + * $ ./scribblec.sh scribble-demos/scrib/betty16/src/betty16/lec2/adder/Adder.scr + * + * (2) Build Endpoint FSM for C: + * $ ./scribblec.sh scribble-demos/scrib/betty16/src/betty16/lec2/adder/Adder.scr -fsm Adder C + * + * (3) Generate Endpoint API ("Session API" and "State Channel API") for C: + * $ ./scribblec.sh -d scribble-demos/scrib/betty16/src/ scribble-demos/scrib/betty16/src/betty16/lec2/adder/Adder.scr -api Adder C + * + * (4) [Java] Generate javadoc from Endpoint API(s): modules/demos/scrib/betty16/src/betty16/lec2/adder/Adder.scr + * $ javadoc -cp scribble-core/target/classes:scribble-runtime/target/classes:scribble-demos/scrib/betty16/src -subpackages betty16.lec2.adder.Adder.Adder -d scribble-demos/scrib/betty16/javadoc/adder + * + */ + + +module betty16.lec2.adder.Adder; + + +data "java.lang.Integer" from "rt.jar" as Integer; + + +global protocol Adder(role C, role S) { + choice at C { + Add(Integer, Integer) from C to S; + Res(Integer) from S to C; + do Adder(C, S); + } or { + Bye() from C to S; + Bye() from S to C; + } +} diff --git a/scribble-demos/scrib/betty16/src/betty16/lec2/adder/AdderC1.java b/scribble-demos/scrib/betty16/src/betty16/lec2/adder/AdderC1.java new file mode 100644 index 000000000..57a379759 --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec2/adder/AdderC1.java @@ -0,0 +1,54 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package betty16.lec2.adder; + +import static betty16.lec2.adder.Adder.Adder.Adder.Add; +import static betty16.lec2.adder.Adder.Adder.Adder.Bye; +import static betty16.lec2.adder.Adder.Adder.Adder.C; +import static betty16.lec2.adder.Adder.Adder.Adder.Res; +import static betty16.lec2.adder.Adder.Adder.Adder.S; + +import org.scribble.runtime.message.ObjectStreamFormatter; +import org.scribble.runtime.net.SocketChannelEndpoint; +import org.scribble.runtime.session.MPSTEndpoint; +import org.scribble.runtime.util.Buf; + +import betty16.lec2.adder.Adder.Adder.Adder; +import betty16.lec2.adder.Adder.Adder.roles.C; +import betty16.lec2.adder.Adder.Adder.statechans.C.Adder_C_1; + +public class AdderC1 { + + public static void main(String[] args) throws Exception { + Adder adder = new Adder(); + try (MPSTEndpoint client = new MPSTEndpoint<>(adder, C, + new ObjectStreamFormatter())) { + client.request(S, SocketChannelEndpoint::new, "localhost", 8888); + System.out.println("C: " + new AdderC1().run(client)); + } + } + + private int run(MPSTEndpoint client) throws Exception { + Buf i = new Buf<>(1); + + new Adder_C_1(client) + .send(S, Add, i.val, i.val) + .receive(S, Res, i) + .send(S, Add, i.val, i.val) + .receive(S, Res, i) + .send(S, Bye).receive(S, Bye); + + return i.val; + } +} diff --git a/scribble-demos/scrib/betty16/src/betty16/lec2/adder/AdderC2.java b/scribble-demos/scrib/betty16/src/betty16/lec2/adder/AdderC2.java new file mode 100644 index 000000000..e9d9968e2 --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec2/adder/AdderC2.java @@ -0,0 +1,53 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package betty16.lec2.adder; + +import static betty16.lec2.adder.Adder.Adder.Adder.Add; +import static betty16.lec2.adder.Adder.Adder.Adder.Bye; +import static betty16.lec2.adder.Adder.Adder.Adder.C; +import static betty16.lec2.adder.Adder.Adder.Adder.Res; +import static betty16.lec2.adder.Adder.Adder.Adder.S; + +import org.scribble.runtime.message.ObjectStreamFormatter; +import org.scribble.runtime.net.SocketChannelEndpoint; +import org.scribble.runtime.session.MPSTEndpoint; +import org.scribble.runtime.util.Buf; + +import betty16.lec2.adder.Adder.Adder.Adder; +import betty16.lec2.adder.Adder.Adder.roles.C; +import betty16.lec2.adder.Adder.Adder.statechans.C.Adder_C_1; + +public class AdderC2 { + + public static void main(String[] args) throws Exception { + Adder adder = new Adder(); + try (MPSTEndpoint client = new MPSTEndpoint<>(adder, C, + new ObjectStreamFormatter())) { + client.request(S, SocketChannelEndpoint::new, "localhost", 8888); + System.out.println("C: " + new AdderC2().run(client)); + } + } + + private int run(MPSTEndpoint client) throws Exception { + Buf i = new Buf<>(1); + + Adder_C_1 s1 = new Adder_C_1(client); + for (int j = 0; j < 10; j++) { + s1 = s1.send(S, Add, i.val, i.val).receive(S, Res, i); + } + s1.send(S, Bye).receive(S, Bye); + + return i.val; + } +} diff --git a/scribble-demos/scrib/betty16/src/betty16/lec2/adder/AdderS1.java b/scribble-demos/scrib/betty16/src/betty16/lec2/adder/AdderS1.java new file mode 100644 index 000000000..e7c7e8f86 --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec2/adder/AdderS1.java @@ -0,0 +1,77 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package betty16.lec2.adder; + +import static betty16.lec2.adder.Adder.Adder.Adder.Add; +import static betty16.lec2.adder.Adder.Adder.Adder.Bye; +import static betty16.lec2.adder.Adder.Adder.Adder.C; +import static betty16.lec2.adder.Adder.Adder.Adder.Res; +import static betty16.lec2.adder.Adder.Adder.Adder.S; + +import java.io.IOException; + +import org.scribble.main.ScribRuntimeException; +import org.scribble.runtime.message.ObjectStreamFormatter; +import org.scribble.runtime.net.ScribServerSocket; +import org.scribble.runtime.net.SocketChannelServer; +import org.scribble.runtime.session.MPSTEndpoint; +import org.scribble.runtime.util.Buf; + +import betty16.lec2.adder.Adder.Adder.Adder; +import betty16.lec2.adder.Adder.Adder.roles.S; +import betty16.lec2.adder.Adder.Adder.statechans.S.Adder_S_1; +import betty16.lec2.adder.Adder.Adder.statechans.S.Adder_S_1_Cases; + +public class AdderS1 { + + public static void main(String[] args) throws Exception { + try (ScribServerSocket ss = new SocketChannelServer(8888)) { + while (true) { + Adder adder = new Adder(); + try (MPSTEndpoint server = new MPSTEndpoint<>(adder, S, + new ObjectStreamFormatter())) { + server.accept(ss, C); + new AdderS1().run(new Adder_S_1(server)); + } catch (ScribRuntimeException | IOException | ClassNotFoundException e) { + e.printStackTrace(); + } + } + } + } + + private void run(Adder_S_1 s1) throws Exception { + Buf i1 = new Buf<>(); + Buf i2 = new Buf<>(); + while (true) { + Adder_S_1_Cases cases = s1.branch(C); + switch (cases.op) { + case Add: s1 = cases.receive(Add, i1, i2).send(C, Res, i1.val+i2.val); break; + case Bye: cases.receive(Bye).send(C, Bye); return; + } + } + } + + /* + private EndSocket run(Adder_S_1 s1, Buf i1, Buf i2) throws Exception { + Adder_S_1_Cases cases = s1.branch(C); + switch (cases.op) { + case Add: return run( + cases.receive(Add, i1, i2).send(C, Res, i1.val+i2.val), + i1, i2); + case Bye: return cases.receive(Bye).send(C, Bye); + default: throw new RuntimeException("Dummy."); // Java + } + } + //*/ +} diff --git a/scribble-demos/scrib/betty16/src/betty16/lec2/adder/AdderS2.java b/scribble-demos/scrib/betty16/src/betty16/lec2/adder/AdderS2.java new file mode 100644 index 000000000..bd64eaade --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec2/adder/AdderS2.java @@ -0,0 +1,69 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package betty16.lec2.adder; + +import static betty16.lec2.adder.Adder.Adder.Adder.Bye; +import static betty16.lec2.adder.Adder.Adder.Adder.C; +import static betty16.lec2.adder.Adder.Adder.Adder.Res; +import static betty16.lec2.adder.Adder.Adder.Adder.S; + +import java.io.IOException; + +import org.scribble.main.ScribRuntimeException; +import org.scribble.runtime.message.ObjectStreamFormatter; +import org.scribble.runtime.net.ScribServerSocket; +import org.scribble.runtime.net.SocketChannelServer; +import org.scribble.runtime.session.MPSTEndpoint; +import org.scribble.runtime.util.Buf; + +import betty16.lec2.adder.Adder.Adder.Adder; +import betty16.lec2.adder.Adder.Adder.ops.Add; +import betty16.lec2.adder.Adder.Adder.ops.Bye; +import betty16.lec2.adder.Adder.Adder.roles.S; +import betty16.lec2.adder.Adder.Adder.statechans.S.Adder_S_1; +import betty16.lec2.adder.Adder.Adder.statechans.S.Adder_S_1_Handler; +import betty16.lec2.adder.Adder.Adder.statechans.S.Adder_S_2; +import betty16.lec2.adder.Adder.Adder.statechans.S.Adder_S_3; + +public class AdderS2 implements Adder_S_1_Handler { + + public static void main(String[] args) throws Exception { + try (ScribServerSocket ss = new SocketChannelServer(8888)) { + while (true) { + Adder adder = new Adder(); + try (MPSTEndpoint server = new MPSTEndpoint<>(adder, S, + new ObjectStreamFormatter())) { + server.accept(ss, C); + + new Adder_S_1(server).branch(C, new AdderS2()); + } catch (ScribRuntimeException | IOException | ClassNotFoundException e) { + e.printStackTrace(); + } + } + } + } + + @Override + public void receive(Adder_S_2 s2, Add op, Buf arg1, + Buf arg2) + throws ScribRuntimeException, IOException, ClassNotFoundException + { + s2.send(C, Res, arg1.val + arg2.val).branch(C, this); + } + + @Override + public void receive(Adder_S_3 s3, Bye op) throws ScribRuntimeException, IOException { + s3.send(C, Bye); + } +} diff --git a/scribble-demos/scrib/betty16/src/betty16/lec2/adder/FibC1.java b/scribble-demos/scrib/betty16/src/betty16/lec2/adder/FibC1.java new file mode 100644 index 000000000..32dec9fc4 --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec2/adder/FibC1.java @@ -0,0 +1,55 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package betty16.lec2.adder; + +import static betty16.lec2.adder.Adder.Adder.Adder.Add; +import static betty16.lec2.adder.Adder.Adder.Adder.Bye; +import static betty16.lec2.adder.Adder.Adder.Adder.C; +import static betty16.lec2.adder.Adder.Adder.Adder.Res; +import static betty16.lec2.adder.Adder.Adder.Adder.S; + +import org.scribble.runtime.message.ObjectStreamFormatter; +import org.scribble.runtime.net.SocketChannelEndpoint; +import org.scribble.runtime.session.MPSTEndpoint; +import org.scribble.runtime.util.Buf; + +import betty16.lec2.adder.Adder.Adder.Adder; +import betty16.lec2.adder.Adder.Adder.roles.C; +import betty16.lec2.adder.Adder.Adder.statechans.C.Adder_C_1; +import betty16.lec2.adder.Adder.Adder.statechans.C.EndSocket; + +public class FibC1 { + + public static void main(String[] args) throws Exception { + Adder adder = new Adder(); + try (MPSTEndpoint client = new MPSTEndpoint<>(adder, C, + new ObjectStreamFormatter())) { + client.request(S, SocketChannelEndpoint::new, "localhost", 8888); + + Buf i1 = new Buf<>(0); + Buf i2 = new Buf<>(1); + int N = 10; + new FibC1().fibo(new Adder_C_1(client), i1, i2, N); + System.out.println(N + ": " + i1.val); + } + } + + // Post: i1.val is the i-th Fibonacci number + private EndSocket fibo(Adder_C_1 c1, Buf i1, Buf i2, int i) + throws Exception { + return (i > 0) + ? fibo(c1.send(S, Add, i1.val, i1.val=i2.val).receive(S, Res, i2), i1, i2, i-1) + : c1.send(S, Bye).receive(S, Bye); + } +} diff --git a/scribble-demos/scrib/betty16/src/betty16/lec2/adder/MyAdderC.java b/scribble-demos/scrib/betty16/src/betty16/lec2/adder/MyAdderC.java new file mode 100644 index 000000000..05371bf54 --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec2/adder/MyAdderC.java @@ -0,0 +1,55 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package betty16.lec2.adder; + +import static betty16.lec2.adder.Adder.Adder.Adder.C; +import static betty16.lec2.adder.Adder.Adder.Adder.S; + +import org.scribble.runtime.message.ObjectStreamFormatter; +import org.scribble.runtime.net.SocketChannelEndpoint; +import org.scribble.runtime.session.MPSTEndpoint; +import org.scribble.runtime.util.Buf; + +import betty16.lec2.adder.Adder.Adder.Adder; +import betty16.lec2.adder.Adder.Adder.roles.C; +import betty16.lec2.adder.Adder.Adder.statechans.C.Adder_C_1; + +public class MyAdderC { + + public static void main(String[] args) throws Exception { + Adder adder = new Adder(); + try (MPSTEndpoint client = new MPSTEndpoint<>(adder, C, + new ObjectStreamFormatter())) { + client.request(S, SocketChannelEndpoint::new, "localhost", 8888); + System.out.println("C: " + new MyAdderC().run(client)); + } + } + + private int run(MPSTEndpoint client) throws Exception { + Buf i = new Buf<>(1); + + Adder_C_1 c1 = new Adder_C_1(client); + + // TODO + + return i.val; + } +} + + + + + + + diff --git a/scribble-demos/scrib/betty16/src/betty16/lec2/adder/MyAdderS.java b/scribble-demos/scrib/betty16/src/betty16/lec2/adder/MyAdderS.java new file mode 100644 index 000000000..2abeacb50 --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec2/adder/MyAdderS.java @@ -0,0 +1,77 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package betty16.lec2.adder; + +import static betty16.lec2.adder.Adder.Adder.Adder.Add; +import static betty16.lec2.adder.Adder.Adder.Adder.Bye; +import static betty16.lec2.adder.Adder.Adder.Adder.C; +import static betty16.lec2.adder.Adder.Adder.Adder.Res; +import static betty16.lec2.adder.Adder.Adder.Adder.S; + +import java.io.IOException; + +import org.scribble.main.ScribRuntimeException; +import org.scribble.runtime.message.ObjectStreamFormatter; +import org.scribble.runtime.net.ScribServerSocket; +import org.scribble.runtime.net.SocketChannelServer; +import org.scribble.runtime.session.MPSTEndpoint; +import org.scribble.runtime.util.Buf; + +import betty16.lec2.adder.Adder.Adder.Adder; +import betty16.lec2.adder.Adder.Adder.roles.S; +import betty16.lec2.adder.Adder.Adder.statechans.S.Adder_S_1; +import betty16.lec2.adder.Adder.Adder.statechans.S.Adder_S_1_Cases; + +public class MyAdderS { + + public static void main(String[] args) throws Exception { + try (ScribServerSocket ss = new SocketChannelServer(8888)) { + while (true) { + Adder adder = new Adder(); + try (MPSTEndpoint server = new MPSTEndpoint<>(adder, S, + new ObjectStreamFormatter())) { + server.accept(ss, C); + new MyAdderS().run(new Adder_S_1(server)); + } catch (ScribRuntimeException | IOException | ClassNotFoundException e) { + e.printStackTrace(); + } + } + } + } + + private void run(Adder_S_1 s1) throws Exception { + Buf i1 = new Buf<>(); + Buf i2 = new Buf<>(); + while (true) { + Adder_S_1_Cases cases = s1.branch(C); + switch (cases.op) { + case Add: s1 = cases.receive(Add, i1, i2).send(C, Res, i1.val+i2.val); break; + case Bye: cases.receive(Bye).send(C, Bye); return; + } + } + } + + /* + private EndSocket run(Adder_S_1 s1, Buf i1, Buf i2) throws Exception { + Adder_S_1_Cases cases = s1.branch(C); + switch (cases.op) { + case Add: return run( + cases.receive(Add, i1, i2).send(C, Res, i1.val+i2.val), + i1, i2); + case Bye: return cases.receive(Bye).send(C, Bye); + default: throw new RuntimeException("Dummy."); // Java + } + } + //*/ +} diff --git a/scribble-demos/scrib/betty16/src/betty16/lec2/adder/MyFibC.java b/scribble-demos/scrib/betty16/src/betty16/lec2/adder/MyFibC.java new file mode 100644 index 000000000..6129bc53c --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec2/adder/MyFibC.java @@ -0,0 +1,51 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package betty16.lec2.adder; + +import static betty16.lec2.adder.Adder.Adder.Adder.C; +import static betty16.lec2.adder.Adder.Adder.Adder.S; + +import org.scribble.runtime.message.ObjectStreamFormatter; +import org.scribble.runtime.net.SocketChannelEndpoint; +import org.scribble.runtime.session.MPSTEndpoint; +import org.scribble.runtime.util.Buf; + +import betty16.lec2.adder.Adder.Adder.Adder; +import betty16.lec2.adder.Adder.Adder.roles.C; +import betty16.lec2.adder.Adder.Adder.statechans.C.Adder_C_1; +import betty16.lec2.adder.Adder.Adder.statechans.C.EndSocket; + +public class MyFibC { + + public static void main(String[] args) throws Exception { + Adder adder = new Adder(); + try (MPSTEndpoint client = new MPSTEndpoint<>(adder, C, new ObjectStreamFormatter())) { + client.request(S, SocketChannelEndpoint::new, "localhost", 8888); + + Buf i1 = new Buf<>(0); + Buf i2 = new Buf<>(1); + int N = 10; + new MyFibC().fibo(new Adder_C_1(client), i1, i2, N); + System.out.println("C: " + i1.val); + } + } + + // Result: i1.val contains the N-th Fibonacci number + private EndSocket fibo(Adder_C_1 c1, Buf i1, Buf i2, int i) throws Exception { + + //... c1.send(S, Add, i1.val, i1.val=i2.val) ... + + throw new RuntimeException("[TODO]"); + } +} diff --git a/scribble-demos/scrib/betty16/src/betty16/lec2/smtp/MySmtpC.java b/scribble-demos/scrib/betty16/src/betty16/lec2/smtp/MySmtpC.java new file mode 100644 index 000000000..3f2f3bb51 --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec2/smtp/MySmtpC.java @@ -0,0 +1,80 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package betty16.lec2.smtp; + +import static betty16.lec2.smtp.Smtp.Smtp.Smtp.C; +import static betty16.lec2.smtp.Smtp.Smtp.Smtp.S; +import static betty16.lec2.smtp.Smtp.Smtp.Smtp._220; + +import org.scribble.runtime.net.SSLSocketChannelWrapper; +import org.scribble.runtime.net.SocketChannelEndpoint; +import org.scribble.runtime.session.MPSTEndpoint; +import org.scribble.runtime.statechans.LinearSocket; + +import betty16.lec2.smtp.Smtp.Smtp.Smtp; +import betty16.lec2.smtp.Smtp.Smtp.roles.C; +import betty16.lec2.smtp.Smtp.Smtp.statechans.C.EndSocket; +import betty16.lec2.smtp.Smtp.Smtp.statechans.C.Smtp_C_1; +import betty16.lec2.smtp.Smtp.Smtp.statechans.C.Smtp_C_4; +import betty16.lec2.smtp.Smtp.Smtp.statechans.C.Smtp_C_6; +import betty16.lec2.smtp.Smtp.Smtp.statechans.C.ioifaces.Select_C_S_Ehlo; +import betty16.lec2.smtp.Smtp.Smtp.statechans.C.ioifaces.Succ_In_S_250; +import betty16.lec2.smtp.message.SmtpMessageFormatter; +import betty16.lec2.smtp.message.client.StartTls; + +public class MySmtpC { + + public static void main(String[] args) throws Exception { + String host = "smtp.cc.ic.ac.uk"; + int port = 25; + + Smtp smtp = new Smtp(); + try (MPSTEndpoint client = new MPSTEndpoint<>(smtp, C, + new SmtpMessageFormatter())) { + client.request(S, SocketChannelEndpoint::new, host, port); + new MySmtpC().run(new Smtp_C_1(client)); + } + } + + private EndSocket run(Smtp_C_1 c1) throws Exception { + /* + + return + doInit( + doStartTls( + doInit(c1.async(S, _220))) + ) + .send(S, new Quit()); + + /*/ + throw new RuntimeException("[TODO]: "); + //*/ + } + + private + // succ(S?250) <- S!{ Ehlo: ?? } + Succ_In_S_250 doInit(Select_C_S_Ehlo c) throws Exception { + + throw new RuntimeException("[TODO]: "); + + } + + private Smtp_C_6 doStartTls(Smtp_C_4 c4) throws Exception { + return + LinearSocket.wrapClient( + c4.send(S, new StartTls()) + .async(S, _220) + , S, SSLSocketChannelWrapper::new); + } +} diff --git a/scribble-demos/scrib/betty16/src/betty16/lec2/smtp/Smtp.scr b/scribble-demos/scrib/betty16/src/betty16/lec2/smtp/Smtp.scr new file mode 100644 index 000000000..243dd6bb2 --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec2/smtp/Smtp.scr @@ -0,0 +1,62 @@ +/** + * Note: this simplified example does not include the actual mail exchanges. + * See, e.g., scribble-demos/scrib/smtp/src/Smtp.scr for a more complete version. + * + * Assuming scribblec.sh in scribble-java root directory: + * + * (1) Generate Endpoint API for C + * $ ./scribblec.sh -d scribble-demos/scrib/betty16/src scribble-demos/scrib/betty16/src/betty16/lec2/smtp/Smtp.scr -api Smtp C + * + * (2) Generate Endpoint API for C with session subtyping interfaces + * $ ./scribblec.sh -d scribble-demos/scrib/betty16/src scribble-demos/scrib/betty16/src/betty16/lec2/smtp/Smtp.scr -subtypes -api Smtp C + * + */ + + +module betty16.lec2.smtp.Smtp; + + +sig "betty16.lec2.smtp.message.server._220" + from "betty16/smtp/message/server/_220.java" as 220; +sig "betty16.lec2.smtp.message.server._250" + from "betty16/smtp/message/server/_250.java" as 250; +sig "betty16.lec2.smtp.message.server._250d" + from "betty16/smtp/message/server/_250d.java" as 250d; + + +sig "betty16.lec2.smtp.message.client.Ehlo" + from "betty16/smtp/message/client/Ehlo.java" as Ehlo; +sig "betty16.lec2.smtp.message.client.StartTls" + from "betty16/smtp/message/client/StartTls.java" as StartTls; +sig "betty16.lec2.smtp.message.client.Quit" + from "betty16/smtp/message/client/Quit.java" as Quit; + + +global protocol Smtp(role C, role S) { + 220 from S to C; + //choice at C { + do Init(C, S); + do StartTls(C, S); + do Init(C, S); + Quit from C to S; + /*} or { + Quit from C to S; + }*/ +} + +aux global protocol Init(role C, role S) { + Ehlo from C to S; + rec X { + choice at S { + 250d from S to C; + continue X; + } or { + 250 from S to C; + } + } +} + +aux global protocol StartTls(role C, role S) { + StartTls from C to S; + 220 from S to C; +} diff --git a/scribble-demos/scrib/betty16/src/betty16/lec2/smtp/SmtpC1.java b/scribble-demos/scrib/betty16/src/betty16/lec2/smtp/SmtpC1.java new file mode 100644 index 000000000..95b941dbb --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec2/smtp/SmtpC1.java @@ -0,0 +1,105 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package betty16.lec2.smtp; + +import static betty16.lec2.smtp.Smtp.Smtp.Smtp.C; +import static betty16.lec2.smtp.Smtp.Smtp.Smtp.S; +import static betty16.lec2.smtp.Smtp.Smtp.Smtp._220; +import static betty16.lec2.smtp.Smtp.Smtp.Smtp._250; +import static betty16.lec2.smtp.Smtp.Smtp.Smtp._250d; + +import org.scribble.runtime.net.SSLSocketChannelWrapper; +import org.scribble.runtime.net.SocketChannelEndpoint; +import org.scribble.runtime.session.MPSTEndpoint; +import org.scribble.runtime.statechans.LinearSocket; +import org.scribble.runtime.util.Buf; + +import betty16.lec2.smtp.Smtp.Smtp.Smtp; +import betty16.lec2.smtp.Smtp.Smtp.roles.C; +import betty16.lec2.smtp.Smtp.Smtp.statechans.C.EndSocket; +import betty16.lec2.smtp.Smtp.Smtp.statechans.C.Smtp_C_1; +import betty16.lec2.smtp.Smtp.Smtp.statechans.C.Smtp_C_2; +import betty16.lec2.smtp.Smtp.Smtp.statechans.C.Smtp_C_3; +import betty16.lec2.smtp.Smtp.Smtp.statechans.C.Smtp_C_3_Cases; +import betty16.lec2.smtp.Smtp.Smtp.statechans.C.Smtp_C_4; +import betty16.lec2.smtp.Smtp.Smtp.statechans.C.Smtp_C_6; +import betty16.lec2.smtp.Smtp.Smtp.statechans.C.Smtp_C_7; +import betty16.lec2.smtp.Smtp.Smtp.statechans.C.Smtp_C_7_Cases; +import betty16.lec2.smtp.Smtp.Smtp.statechans.C.Smtp_C_8; +import betty16.lec2.smtp.message.SmtpMessageFormatter; +import betty16.lec2.smtp.message.client.Ehlo; +import betty16.lec2.smtp.message.client.Quit; +import betty16.lec2.smtp.message.client.StartTls; + +public class SmtpC1 +{ + public static void main(String[] args) throws Exception { + String host = "...smtp server..."; + int port = 25; + + Smtp smtp = new Smtp(); + try (MPSTEndpoint client = new MPSTEndpoint<>(smtp, C, + new SmtpMessageFormatter())) { + client.request(S, SocketChannelEndpoint::new, host, port); + new SmtpC1().run(new Smtp_C_1(client)); + } + } + + private EndSocket run(Smtp_C_1 c1) throws Exception { + return + doInit( + doStartTls( + doInit(c1.async(S, _220))) + ) + .send(S, new Quit()); + } + + private Smtp_C_4 doInit(Smtp_C_2 c2) throws Exception { + Smtp_C_3 c3 = c2.send(S, new Ehlo("test")); + Buf buf = new Buf<>(); + while (true) { + Smtp_C_3_Cases cases = c3.branch(S); + switch (cases.getOp()) { + case _250d: c3 = cases.receive(S, _250d, buf); System.out.print(buf.val); break; + case _250: return printlnBuf(cases.receive(S, _250, buf), buf); + } + } + } + + private Smtp_C_6 doStartTls(Smtp_C_4 c4) throws Exception { + return + LinearSocket.wrapClient( + c4.send(S, new StartTls()) + .async(S, _220) + , S, SSLSocketChannelWrapper::new); + } + + private Smtp_C_8 doInit(Smtp_C_6 c6) throws Exception { + Smtp_C_7 c7 = c6.send(S, new Ehlo("test")); + Buf buf = new Buf<>(); + while (true) { + Smtp_C_7_Cases cases = c7.branch(S); + switch (cases.getOp()) { + case _250d: c7 = cases.receive(S, _250d, buf); System.out.print(buf.val); break; + case _250: return printlnBuf(cases.receive(S, _250, buf), buf); + } + } + } + + private static > S printlnBuf(S s, B b) { + System.out.println(b.val); + return s; + } +} + diff --git a/scribble-demos/scrib/betty16/src/betty16/lec2/smtp/SmtpC2.java b/scribble-demos/scrib/betty16/src/betty16/lec2/smtp/SmtpC2.java new file mode 100644 index 000000000..349a4c652 --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec2/smtp/SmtpC2.java @@ -0,0 +1,100 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package betty16.lec2.smtp; + +import static betty16.lec2.smtp.Smtp.Smtp.Smtp.C; +import static betty16.lec2.smtp.Smtp.Smtp.Smtp.S; +import static betty16.lec2.smtp.Smtp.Smtp.Smtp._220; +import static betty16.lec2.smtp.Smtp.Smtp.Smtp._250; +import static betty16.lec2.smtp.Smtp.Smtp.Smtp._250d; + +import org.scribble.runtime.net.SSLSocketChannelWrapper; +import org.scribble.runtime.net.SocketChannelEndpoint; +import org.scribble.runtime.session.MPSTEndpoint; +import org.scribble.runtime.statechans.LinearSocket; +import org.scribble.runtime.util.Buf; + +import betty16.lec2.smtp.Smtp.Smtp.Smtp; +import betty16.lec2.smtp.Smtp.Smtp.roles.C; +import betty16.lec2.smtp.Smtp.Smtp.statechans.C.EndSocket; +import betty16.lec2.smtp.Smtp.Smtp.statechans.C.Smtp_C_1; +import betty16.lec2.smtp.Smtp.Smtp.statechans.C.ioifaces.Branch_C_S_250__S_250d; +import betty16.lec2.smtp.Smtp.Smtp.statechans.C.ioifaces.Case_C_S_250__S_250d; +import betty16.lec2.smtp.Smtp.Smtp.statechans.C.ioifaces.Receive_C_S_220; +import betty16.lec2.smtp.Smtp.Smtp.statechans.C.ioifaces.Select_C_S_Ehlo; +import betty16.lec2.smtp.Smtp.Smtp.statechans.C.ioifaces.Select_C_S_Quit; +import betty16.lec2.smtp.Smtp.Smtp.statechans.C.ioifaces.Select_C_S_StartTls; +import betty16.lec2.smtp.Smtp.Smtp.statechans.C.ioifaces.Succ_In_S_220; +import betty16.lec2.smtp.Smtp.Smtp.statechans.C.ioifaces.Succ_In_S_250; +import betty16.lec2.smtp.message.SmtpMessageFormatter; +import betty16.lec2.smtp.message.client.Ehlo; +import betty16.lec2.smtp.message.client.Quit; +import betty16.lec2.smtp.message.client.StartTls; + +public class SmtpC2 { + + public static void main(String[] args) throws Exception { + String host = "...smtp server..."; + int port = 25; + + Smtp smtp = new Smtp(); + try (MPSTEndpoint client = new MPSTEndpoint<>(smtp, C, + new SmtpMessageFormatter())) { + client.request(S, SocketChannelEndpoint::new, host, port); + new SmtpC2().run(new Smtp_C_1(client)); + } + } + + private EndSocket run(Smtp_C_1 c1) throws Exception { + return + doInit( + doStartTls( + doInit(c1.async(S, _220)).to(Select_C_S_StartTls.cast) + ).to(Select_C_S_Ehlo.cast) + ) + .to(Select_C_S_Quit.cast) + .send(S, new Quit()) + .to(EndSocket.cast); + } + + private Succ_In_S_250 doInit(Select_C_S_Ehlo c) throws Exception { + Branch_C_S_250__S_250d b = + c.send(S, new Ehlo("test")).to(Branch_C_S_250__S_250d.cast); + Buf buf = new Buf<>(); + for (Case_C_S_250__S_250d cases = b.branch(S); true; cases = b.branch(S)) { + switch (cases.getOp()) { + case _250: return printlnBuf(cases.receive(S, _250, buf), buf); + case _250d: b = cases.receive(S, _250d, buf).to(Branch_C_S_250__S_250d.cast); System.out.print(buf.val); break; + } + } + } + + private Succ_In_S_220 doStartTls(Select_C_S_StartTls c) throws Exception { + return + LinearSocket.wrapClient( + c.send(S, new StartTls()).to(Receive_C_S_220.cast) + .async(S, _220) + , S, SSLSocketChannelWrapper::new); + } + + private static > S printlnBuf(S s, B b) { + System.out.println(b.val); + return s; + } + + /*private static > S printBuf(S s, B b) { + System.out.print(b.val); + return s; + }*/ +} diff --git a/scribble-demos/scrib/betty16/src/betty16/lec2/smtp/SmtpC3.java b/scribble-demos/scrib/betty16/src/betty16/lec2/smtp/SmtpC3.java new file mode 100644 index 000000000..2d2e31285 --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec2/smtp/SmtpC3.java @@ -0,0 +1,121 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package betty16.lec2.smtp; + +import static betty16.lec2.smtp.Smtp.Smtp.Smtp.C; +import static betty16.lec2.smtp.Smtp.Smtp.Smtp.S; +import static betty16.lec2.smtp.Smtp.Smtp.Smtp._220; +import static betty16.lec2.smtp.Smtp.Smtp.Smtp._250; +import static betty16.lec2.smtp.Smtp.Smtp.Smtp._250d; + +import org.scribble.runtime.net.SSLSocketChannelWrapper; +import org.scribble.runtime.net.SocketChannelEndpoint; +import org.scribble.runtime.session.MPSTEndpoint; +import org.scribble.runtime.statechans.LinearSocket; +import org.scribble.runtime.util.Buf; + +import betty16.lec2.smtp.Smtp.Smtp.Smtp; +import betty16.lec2.smtp.Smtp.Smtp.roles.C; +import betty16.lec2.smtp.Smtp.Smtp.statechans.C.EndSocket; +import betty16.lec2.smtp.Smtp.Smtp.statechans.C.Smtp_C_1; +import betty16.lec2.smtp.Smtp.Smtp.statechans.C.Smtp_C_4; +import betty16.lec2.smtp.Smtp.Smtp.statechans.C.Smtp_C_6; +import betty16.lec2.smtp.Smtp.Smtp.statechans.C.ioifaces.Branch_C_S_250__S_250d; +import betty16.lec2.smtp.Smtp.Smtp.statechans.C.ioifaces.Case_C_S_250__S_250d; +import betty16.lec2.smtp.Smtp.Smtp.statechans.C.ioifaces.Select_C_S_Ehlo; +import betty16.lec2.smtp.Smtp.Smtp.statechans.C.ioifaces.Succ_In_S_250; +import betty16.lec2.smtp.message.SmtpMessageFormatter; +import betty16.lec2.smtp.message.client.Ehlo; +import betty16.lec2.smtp.message.client.Quit; +import betty16.lec2.smtp.message.client.StartTls; + +public class SmtpC3 { + + public static void main(String[] args) throws Exception { + String host = "...smtp server..."; + int port = 25; + + Smtp smtp = new Smtp(); + try (MPSTEndpoint client = new MPSTEndpoint<>(smtp, C, + new SmtpMessageFormatter())) { + client.request(S, SocketChannelEndpoint::new, host, port); + new SmtpC3().run(new Smtp_C_1(client)); + } + } + + private EndSocket run(Smtp_C_1 c1) throws Exception { + return + doInit( + doStartTls( + doInit(c1.async(S, _220))) + ) + .send(S, new Quit()); + } + + /* + private + < + S1 extends Branch_C_S_250__S_250d // S1 = S?{ 250: Succ(S?250), 250d: S1 } + > + // S!Ehlo.S1 -> S2 + Succ_In_S_250 doInit(Select_C_S_Ehlo c) throws Exception { + S1 b = c.send(S, new Ehlo("test")); + Buf buf = new Buf<>(); + for (Case_C_S_250__S_250d cases = b.branch(S); true; cases = b.branch(S)) { + switch (cases.getOp()) { + case _250: return printlnBuf(cases.receive(S, _250, buf), buf); + case _250d: b = cases.receive(S, _250d, buf); System.out.print(buf.val); break; + } + } + } + //*/ + + //* + private + < + S1 extends Branch_C_S_250__S_250d, // S1 = S?{ 250: S2, 250d: S1 } + S2 extends Succ_In_S_250 // S2 = Succ(S?250) + > + // S!Ehlo.S1 -> S2 + S2 doInit(Select_C_S_Ehlo c) throws Exception { + S1 b = c.send(S, new Ehlo("test")); + Buf buf = new Buf<>(); + while (true) { + Case_C_S_250__S_250d cases = b.branch(S); + switch (cases.getOp()) { + case _250d: b = cases.receive(S, _250d, buf); System.out.print(buf.val); break; + case _250: return printlnBuf(cases.receive(S, _250, buf), buf); + } + } + } + //*/ + + private Smtp_C_6 doStartTls(Smtp_C_4 c4) throws Exception { + return + LinearSocket.wrapClient( + c4.send(S, new StartTls()) + .async(S, _220) + , S, SSLSocketChannelWrapper::new); + } + + private static > S printlnBuf(S s, B b) { + System.out.println(b.val); + return s; + } + + /*private static > S printBuf(S s, B b) { + System.out.print(b.val); + return s; + }*/ +} diff --git a/scribble-demos/scrib/betty16/src/betty16/lec2/smtp/SmtpC4.java b/scribble-demos/scrib/betty16/src/betty16/lec2/smtp/SmtpC4.java new file mode 100644 index 000000000..617cfa93d --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec2/smtp/SmtpC4.java @@ -0,0 +1,107 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package betty16.lec2.smtp; + +import static betty16.lec2.smtp.Smtp.Smtp.Smtp.S; +import static betty16.lec2.smtp.Smtp.Smtp.Smtp._220; + +import java.io.IOException; + +import org.scribble.main.ScribRuntimeException; +import org.scribble.runtime.net.SSLSocketChannelWrapper; +import org.scribble.runtime.net.SocketChannelEndpoint; +import org.scribble.runtime.session.MPSTEndpoint; +import org.scribble.runtime.statechans.LinearSocket; +import org.scribble.runtime.util.Buf; + +import betty16.lec2.smtp.Smtp.Smtp.Smtp; +import betty16.lec2.smtp.Smtp.Smtp.roles.C; +import betty16.lec2.smtp.Smtp.Smtp.statechans.C.Smtp_C_1; +import betty16.lec2.smtp.Smtp.Smtp.statechans.C.Smtp_C_3; +import betty16.lec2.smtp.Smtp.Smtp.statechans.C.Smtp_C_3_Handler; +import betty16.lec2.smtp.Smtp.Smtp.statechans.C.Smtp_C_4; +import betty16.lec2.smtp.Smtp.Smtp.statechans.C.Smtp_C_7; +import betty16.lec2.smtp.Smtp.Smtp.statechans.C.Smtp_C_7_Handler; +import betty16.lec2.smtp.Smtp.Smtp.statechans.C.Smtp_C_8; +import betty16.lec2.smtp.message.SmtpMessageFormatter; +import betty16.lec2.smtp.message.client.Ehlo; +import betty16.lec2.smtp.message.client.Quit; +import betty16.lec2.smtp.message.client.StartTls; +import betty16.lec2.smtp.message.server._250; +import betty16.lec2.smtp.message.server._250d; + +public class SmtpC4 { + + public static void main(String[] args) throws Exception + { + String host = "...smtp server..."; + int port = 25; + + Smtp smtp = new Smtp(); + try (MPSTEndpoint client = new MPSTEndpoint<>(smtp, Smtp.C, + new SmtpMessageFormatter())) + { + client.request(S, SocketChannelEndpoint::new, host, port); + new SmtpC4().run(new Smtp_C_1(client)); + } + } + + private void run(Smtp_C_1 c1) throws Exception { + + System.out.println("Init: "); + + c1.async(S, _220).send(S, new Ehlo("test")).branch(S, new MySmtp_C_3Handler()); + } +} + +class MySmtp_C_3Handler implements Smtp_C_3_Handler { + + @Override + public void receive(Smtp_C_3 s3, betty16.lec2.smtp.Smtp.Smtp.ops._250d op, Buf<_250d> arg) throws ScribRuntimeException, IOException, ClassNotFoundException + { + System.out.println("250-: " + arg.val.getBody()); + + s3.branch(S, this); + } + + @Override + public void receive(Smtp_C_4 s4, betty16.lec2.smtp.Smtp.Smtp.ops._250 op, Buf<_250> arg) throws ScribRuntimeException, IOException, ClassNotFoundException + { + System.out.println("250: " + arg.val.getBody()); + + LinearSocket.wrapClient( + s4.send(S, new StartTls()).async(S, _220) + , S, SSLSocketChannelWrapper::new) + .send(S, new Ehlo("test")).branch(S, new MySmtp_C_8Handler()); + } +} + +class MySmtp_C_8Handler implements Smtp_C_7_Handler { + + @Override + public void receive(Smtp_C_7 s7, betty16.lec2.smtp.Smtp.Smtp.ops._250d op, Buf<_250d> arg) throws ScribRuntimeException, IOException, ClassNotFoundException + { + System.out.println("(TLS) 250-: " + arg.val.getBody()); + + s7.branch(S, this); + } + + @Override + public void receive(Smtp_C_8 s8, betty16.lec2.smtp.Smtp.Smtp.ops._250 op, Buf<_250> arg) throws ScribRuntimeException, IOException, ClassNotFoundException + { + System.out.println("(TLS) 250: " + arg.val.getBody()); + + s8.send(S, new Quit()); + } +} diff --git a/scribble-demos/scrib/betty16/src/betty16/lec2/smtp/message/SmtpMessage.java b/scribble-demos/scrib/betty16/src/betty16/lec2/smtp/message/SmtpMessage.java new file mode 100644 index 000000000..b2c5f5b81 --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec2/smtp/message/SmtpMessage.java @@ -0,0 +1,86 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package betty16.lec2.smtp.message; + +import org.scribble.runtime.message.ScribMessage; +import org.scribble.core.type.name.Op; +import org.scribble.util.Caller; + +import betty16.lec2.smtp.Smtp.Smtp.Smtp; + +public abstract class SmtpMessage extends ScribMessage +{ + public static final String _220 = "220"; + public static final String _250 = "250"; + public static final String _250_ = "250-"; + public static final String _235 = "235"; + public static final String _535 = "535"; + public static final String _501 = "501"; + public static final String _354 = "354"; + + public static final String EHLO = "ehlo"; + public static final String STARTTLS = "starttls"; + public static final String AUTH = "auth plain"; + public static final String MAIL = "mail from:"; + public static final String RCPT = "rcpt to:"; + public static final String SUBJECT = "subject:"; + public static final String DATA = "data"; + public static final String QUIT = "quit"; + + public static final String DATA_LINE = ""; + public static final String END_OF_DATA = ""; + + private static final long serialVersionUID = 1L; + + protected static final String CRLF = "\r\n"; + + public SmtpMessage(Op op) + { + super(op); + } + + public SmtpMessage(Op op, String body) + { + super(op, body); + } + + public String getBody() + { + return (this.payload.length == 0) ? "" : (String) this.payload[0]; + } + + public byte[] toBytes() + { + byte[] bs = (getOpString(this.op) + " " + getBody() + SmtpMessage.CRLF).getBytes(SmtpMessageFormatter.cs); // Can give "utf-8" as arg directly + return bs; + } + + @Override + public String toString() + { + return new String(toBytes()); + } + + protected static String getOpString(Op op) + { + return + (op.equals(Smtp._220)) ? SmtpMessage._220 + : (op.equals(Smtp._250)) ? SmtpMessage._250 + : (op.equals(Smtp._250d)) ? SmtpMessage._250_ + : (op.equals(Smtp.Ehlo)) ? SmtpMessage.EHLO + : (op.equals(Smtp.StartTls)) ? SmtpMessage.STARTTLS + : (op.equals(Smtp.Quit)) ? SmtpMessage.QUIT + : new Caller().call(() -> { throw new RuntimeException("TODO: " + op); }); + } +} diff --git a/scribble-demos/scrib/betty16/src/betty16/lec2/smtp/message/SmtpMessageFormatter.java b/scribble-demos/scrib/betty16/src/betty16/lec2/smtp/message/SmtpMessageFormatter.java new file mode 100644 index 000000000..9540ae25e --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec2/smtp/message/SmtpMessageFormatter.java @@ -0,0 +1,446 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package betty16.lec2.smtp.message; + +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.Charset; + +import org.scribble.runtime.message.ScribMessage; +import org.scribble.runtime.message.ScribMessageFormatter; + +import betty16.lec2.smtp.message.server._220; +import betty16.lec2.smtp.message.server._250; +import betty16.lec2.smtp.message.server._250d; + +// Currently supports only client-side reading, not server-side +public class SmtpMessageFormatter implements ScribMessageFormatter +{ + //.. fix formatting + //.. try ssl wrapper + //.. add connection (transport) actions + + public static Charset cs = Charset.forName("UTF8"); + //private static CharsetDecoder cd = cs.newDecoder(); + + public SmtpMessageFormatter() + { + + } + + @Override + public byte[] toBytes(ScribMessage m) throws IOException + { + return ((SmtpMessage) m).toBytes(); + } + + @Override + public ScribMessage fromBytes(ByteBuffer bb) throws IOException, ClassNotFoundException + { + bb.flip(); + //byte[] bs = new byte[2]; + int rem = bb.remaining(); + if (rem < 2) + { + bb.compact(); + return null; + } + + int pos = bb.position(); + String front = new String(new byte[] { bb.get(pos), bb.get(pos + 1) }, SmtpMessageFormatter.cs); + if (front.equals(SmtpMessage.CRLF)) + { + throw new RuntimeException("TODO: "); + } + + if (rem < pos + 4) + { + bb.compact(); + return null; + } + front += new String(new byte[] { bb.get(pos + 2), bb.get(pos + 3) }, SmtpMessageFormatter.cs); + int code = isStatusCode(front); + if (code > -1) + { + String body = readLine(bb, pos + 4).trim(); // Whitespace already built into the message classes + bb.compact(); + if (body == null) + { + return null; + } + switch (code) + { + case 220: return new _220(body); + case 250: + { + if (front.charAt(3) == '-') + { + return new _250d(body); + } + return new _250(body); + } + /*case 235: return new _235(body); + case 535: return new _535(body); + case 501: return new _501(body); + case 354: return new _354(body);*/ + default: throw new RuntimeException("Unknown status code " + code + ": " + body); + } + } + /*else if (front.startsWith(HttpMessage.GET)) // TODO: server-side (EHLO, STARTTLS, etc) + { + }*/ + else + { + // TODO: server-side (MAIL FROM:, RCPT TO:, etc) + String line = front + readLine(bb, pos + 4); + bb.compact(); + /*if (line == null) // deadcode + { + return null; + }*/ + throw new RuntimeException("Cannot parse message: " + line); + } + } + + private static String readLine(ByteBuffer bb, int i) throws IOException + { + StringBuilder sb = new StringBuilder(); + for (int limit = bb.limit(); i <= limit; ) + { + char c = (char) bb.get(i++); + sb.append(c); + if (c == '\r') + { + c = (char) bb.get(i++); + sb.append(c); + if (c == '\n') + { + bb.position(i); + return sb.substring(0, sb.length() - 2).toString(); + } + } + } + return null; + } + + // Duplicated from HttpMessageFormatter // FIXME: factor out + private int isStatusCode(String front) + { + String code = ""; + for (int i = 0; i < 4; i++) + { + //char c = (char) bs[i]; + char c = front.charAt(i); + if (i < 3) + { + if (c < '0' || c > '9') + { + return -1; + } + code += c; + } + else + { + if (c != ' ' && c != '-') // HACK: hypen + { + return -1; + } + } + } + return Integer.parseInt(code); + } + + /*private static String readWord(ByteBuffer bb, int i) throws IOException + { + StringBuilder sb = new StringBuilder(); + for (int limit = bb.limit(); i <= limit; ) + { + char c = (char) bb.get(i); + if (c == ' ') + { + bb.position(i); + return sb.toString(); + } + sb.append(c); + } + return null; + }*/ + + /* // Pre: flipped ready for reading + @Override + public SmtpMessage readMessage(DataInputStream dis) throws IOException + { + String header = getHeader(dis); + switch (header) + { + // FIXME: factor out text constants with Session constants? + case "220 ": + { + return new _220(getBody(dis)); + } + case "235 ": + { + return new _235(getBody(dis)); + } + case "250-": + { + return new _250_(getBody(dis)); + } + case "250 ": + { + return new _250(getBody(dis)); + } + case "354 ": + { + return new _354(getBody(dis)); + } + case "501 ": + { + return new _501(getBody(dis)); + } + case "535 ": + { + return new _535(getBody(dis)); + } + default: + { + throw new RuntimeException("Unknown header: " + header); + } + } + } + + // *4* char headers (3 digits, dash or space) + private String getHeader(DataInputStream dis) throws IOException + { + readMinimumBytes(dis, 4); + + int limit = bb.limit(); + bb.limit(4); + String header = cd.decode(bb).toString(); // updates bb position + bb.limit(limit); + bb.compact(); + bb.flip(); + return header; + } + + // Reads up to \r\n inclusive; doesn't return the \r\n + private String getBody(DataInputStream dis) throws IOException + { + int min = 2; + readMinimumBytes(dis, min); // Min should be more? + while (true) + { + String all = cd.decode(bb).toString(); // updates bb position + if (all.contains("\n")) // FIXME: didn't check exactly \r\n + { + int i = all.indexOf("\n"); + String body = all.substring(0, i - 1); + bb.position(i + 1); // \r\n -- ASCII 1-to-1 byte-char index + bb.compact(); + bb.flip(); + return body; + } + bb.rewind(); + readMinimumBytes(dis, ++min); // FIXME: buffered readLine would be more efficient + } + } + + // FIXME: min should mean min fresh (i.e. not including bb cached -- there currently is no cache: is.available doesn't work for SSLSocket, always returns 0) + private void readMinimumBytes(DataInputStream dis, int min) throws IOException + { + for (int remaining = bb.remaining(); remaining < min; remaining = bb.remaining()) + { + bb.compact(); + bb.put((byte) dis.read()); // FIXME: check for buffer overflow + bb.flip(); + } + }*/ + + @Override + public void writeMessage(DataOutputStream dos, ScribMessage m) throws IOException + { + dos.write(((SmtpMessage) m).toBytes()); + dos.flush(); + } + + @Override + public SmtpMessage readMessage(DataInputStream dis) throws IOException + { + byte[] bs = new byte[2]; + dis.readFully(bs); + String front = new String(bs, SmtpMessageFormatter.cs); + if (front.equals(SmtpMessage.CRLF)) + { + throw new RuntimeException("TODO: "); + } + bs = new byte[2]; + dis.readFully(bs); + front += new String(bs, SmtpMessageFormatter.cs); + int code = isStatusCode(front); + if (code > -1) + { + String body = readLine(dis).trim(); // Whitespace already built into the message classes + switch (code) + { + case 220: return new _220(body); + case 250: + { + if (front.charAt(3) == '-') + { + return new _250d(body); + } + return new _250(body); + } + /*case 235: return new _235(body); + case 535: return new _535(body); + case 501: return new _501(body); + case 354: return new _354(body);*/ + default: throw new RuntimeException("Unknown status code: " + code); + } + } + /*else if (front.startsWith(HttpMessage.GET)) + { + }*/ + else + { + String line = front + readLine(dis); + throw new RuntimeException("Cannot parse message: " + line); + } + } + + private static String readLine(DataInputStream dis) throws IOException + { + StringBuilder sb = new StringBuilder(); + for (; true; ) + { + char c = (char) dis.read(); // readChar is not the same + sb.append(c); + if (c == '\r') + { + c = (char) dis.read(); + sb.append(c); + if (c == '\n') + { + return sb.substring(0, sb.length() - 2).toString(); + } + } + } + } + + /*private static String readWord(DataInputStream dis) throws IOException + { + StringBuilder sb = new StringBuilder(); + for (; true; ) + { + char c = (char) dis.read(); + if (c == ' ') + { + return sb.toString(); + } + sb.append(c); + } + }*/ + + /* // Pre: flipped ready for reading + @Override + public SmtpMessage readMessage(DataInputStream dis) throws IOException + { + String header = getHeader(dis); + switch (header) + { + // FIXME: factor out text constants with Session constants? + case "220 ": + { + return new _220(getBody(dis)); + } + case "235 ": + { + return new _235(getBody(dis)); + } + case "250-": + { + return new _250_(getBody(dis)); + } + case "250 ": + { + return new _250(getBody(dis)); + } + case "354 ": + { + return new _354(getBody(dis)); + } + case "501 ": + { + return new _501(getBody(dis)); + } + case "535 ": + { + return new _535(getBody(dis)); + } + default: + { + throw new RuntimeException("Unknown header: " + header); + } + } + } + + // *4* char headers (3 digits, dash or space) + private String getHeader(DataInputStream dis) throws IOException + { + readMinimumBytes(dis, 4); + + int limit = bb.limit(); + bb.limit(4); + String header = cd.decode(bb).toString(); // updates bb position + bb.limit(limit); + bb.compact(); + bb.flip(); + return header; + } + + // Reads up to \r\n inclusive; doesn't return the \r\n + private String getBody(DataInputStream dis) throws IOException + { + int min = 2; + readMinimumBytes(dis, min); // Min should be more? + while (true) + { + String all = cd.decode(bb).toString(); // updates bb position + if (all.contains("\n")) // FIXME: didn't check exactly \r\n + { + int i = all.indexOf("\n"); + String body = all.substring(0, i - 1); + bb.position(i + 1); // \r\n -- ASCII 1-to-1 byte-char index + bb.compact(); + bb.flip(); + return body; + } + bb.rewind(); + readMinimumBytes(dis, ++min); // FIXME: buffered readLine would be more efficient + } + } + + // FIXME: min should mean min fresh (i.e. not including bb cached -- there currently is no cache: is.available doesn't work for SSLSocket, always returns 0) + private void readMinimumBytes(DataInputStream dis, int min) throws IOException + { + for (int remaining = bb.remaining(); remaining < min; remaining = bb.remaining()) + { + bb.compact(); + bb.put((byte) dis.read()); // FIXME: check for buffer overflow + bb.flip(); + } + }*/ +} diff --git a/scribble-demos/scrib/betty16/src/betty16/lec2/smtp/message/client/Ehlo.java b/scribble-demos/scrib/betty16/src/betty16/lec2/smtp/message/client/Ehlo.java new file mode 100644 index 000000000..9a5789550 --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec2/smtp/message/client/Ehlo.java @@ -0,0 +1,32 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package betty16.lec2.smtp.message.client; + +import betty16.lec2.smtp.Smtp.Smtp.Smtp; +import betty16.lec2.smtp.message.SmtpMessage; + +public class Ehlo extends SmtpMessage +{ + private static final long serialVersionUID = 1L; + + public Ehlo() + { + super(Smtp.Ehlo); + } + + public Ehlo(String body) + { + super(Smtp.Ehlo, body); + } +} diff --git a/scribble-demos/scrib/betty16/src/betty16/lec2/smtp/message/client/Quit.java b/scribble-demos/scrib/betty16/src/betty16/lec2/smtp/message/client/Quit.java new file mode 100644 index 000000000..06a0cbc15 --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec2/smtp/message/client/Quit.java @@ -0,0 +1,27 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package betty16.lec2.smtp.message.client; + +import betty16.lec2.smtp.Smtp.Smtp.Smtp; +import betty16.lec2.smtp.message.SmtpMessage; + +public class Quit extends SmtpMessage +{ + private static final long serialVersionUID = 1L; + + public Quit() + { + super(Smtp.Quit); + } +} diff --git a/scribble-demos/scrib/betty16/src/betty16/lec2/smtp/message/client/StartTls.java b/scribble-demos/scrib/betty16/src/betty16/lec2/smtp/message/client/StartTls.java new file mode 100644 index 000000000..91a81ae70 --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec2/smtp/message/client/StartTls.java @@ -0,0 +1,27 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package betty16.lec2.smtp.message.client; + +import betty16.lec2.smtp.Smtp.Smtp.Smtp; +import betty16.lec2.smtp.message.SmtpMessage; + +public class StartTls extends SmtpMessage +{ + private static final long serialVersionUID = 1L; + + public StartTls() + { + super(Smtp.StartTls); + } +} diff --git a/scribble-demos/scrib/betty16/src/betty16/lec2/smtp/message/server/_220.java b/scribble-demos/scrib/betty16/src/betty16/lec2/smtp/message/server/_220.java new file mode 100644 index 000000000..2187da431 --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec2/smtp/message/server/_220.java @@ -0,0 +1,38 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package betty16.lec2.smtp.message.server; + +import betty16.lec2.smtp.Smtp.Smtp.Smtp; +import betty16.lec2.smtp.message.SmtpMessage; + +public class _220 extends SmtpMessage +{ + private static final long serialVersionUID = 1L; + + public _220() + { + super(Smtp._220); + } + + public _220(String body) + { + super(Smtp._220, body); + } + + /*@Override + public Operator getOperator() + { + return Smtp._220; + }*/ +} diff --git a/scribble-demos/scrib/betty16/src/betty16/lec2/smtp/message/server/_250.java b/scribble-demos/scrib/betty16/src/betty16/lec2/smtp/message/server/_250.java new file mode 100644 index 000000000..dec23a6d7 --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec2/smtp/message/server/_250.java @@ -0,0 +1,32 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package betty16.lec2.smtp.message.server; + +import betty16.lec2.smtp.Smtp.Smtp.Smtp; +import betty16.lec2.smtp.message.SmtpMessage; + +public class _250 extends SmtpMessage +{ + private static final long serialVersionUID = 1L; + + public _250() + { + super(Smtp._250); + } + + public _250(String body) + { + super(Smtp._250, body); + } +} diff --git a/scribble-demos/scrib/betty16/src/betty16/lec2/smtp/message/server/_250d.java b/scribble-demos/scrib/betty16/src/betty16/lec2/smtp/message/server/_250d.java new file mode 100644 index 000000000..2bdd9c35f --- /dev/null +++ b/scribble-demos/scrib/betty16/src/betty16/lec2/smtp/message/server/_250d.java @@ -0,0 +1,40 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package betty16.lec2.smtp.message.server; + +import betty16.lec2.smtp.Smtp.Smtp.Smtp; +import betty16.lec2.smtp.message.SmtpMessage; +import betty16.lec2.smtp.message.SmtpMessageFormatter; + +public class _250d extends SmtpMessage +{ + private static final long serialVersionUID = 1L; + + public _250d() + { + super(Smtp._250d); + } + + public _250d(String body) + { + super(Smtp._250d, body); + } + + @Override + public byte[] toBytes() + { + // No space after op + return (getOpString(this.op) + getBody() + SmtpMessage.CRLF).getBytes(SmtpMessageFormatter.cs); + } +} diff --git a/scribble-demos/scrib/bettybook/src/bettybook/http/longv/HttpLong.scr b/scribble-demos/scrib/bettybook/src/bettybook/http/longv/HttpLong.scr new file mode 100644 index 000000000..2ea18410c --- /dev/null +++ b/scribble-demos/scrib/bettybook/src/bettybook/http/longv/HttpLong.scr @@ -0,0 +1,188 @@ +/** + * Assuming scribblec.sh in scribble-java root directory: + * + * ./scribblec.sh -d scribble-demos/scrib/bettybook/src scribble-demos/scrib/bettybook/src/bettybook/http/longv/HttpLong.scr -api Http C + */ + + +module bettybook.http.longv.HttpLong; + + +sig "bettybook.http.longv.message.client.RequestLine" + from "bettybook/http/longv/message/RequestLine.java" + as RequestL; // GET /~rhu/ HTTP/1.1 + +sig "bettybook.http.longv.message.client.Host" + from "bettybook/http/longv/message/Host.java" + as Host; // host: www.doc.ic.ac.uk + +sig "bettybook.http.longv.message.Body" + from "bettybook/http/longv/message/Body.java" + as Body; // ... + +sig "bettybook.http.longv.message.client.UserAgent" + from "bettybook/http/longv/message/UserAgent.java" + as UserA; // User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; rv:38.0) Gecko/20100101 Firefox/38.0 + +sig "bettybook.http.longv.message.client.Accept" + from "bettybook/http/longv/message/Accept.java" + as Accept; // Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 + +sig "bettybook.http.longv.message.client.AcceptLanguage" + from "bettybook/http/longv/message/AcceptLanguage.java" + as AcceptL; // Accept-Language: en-GB,en;q=0.5 + +sig "bettybook.http.longv.message.client.AcceptEncoding" + from "bettybook/http/longv/message/AcceptEncoding.java" + as AcceptE; // Accept-Encoding: gzip, deflate + +sig "bettybook.http.longv.message.client.DoNotTrack" + from "bettybook/http/longv/message/DoNotTrack.java" + as DNT; // DNT: 1 + +sig "bettybook.http.longv.message.client.Connection" + from "bettybook/http/longv/message/Connection.java" + as Connection; // Connection: keep-alive + +sig "bettybook.http.longv.message.client.UpgradeInsecureRequests" + from "bettybook/http/longv/message/UpgradeInsecureRequests.java" + as UpgradeIR; // Upgrade-Insecure-Requests: 1 + + +sig "bettybook.http.longv.message.server.HttpVersion" + from "bettybook/http/longv/message/HttpVersion.java" + as HttpV; // HTTP/1.1 + +sig "bettybook.http.longv.message.server._200" // "Status" line (with HttpV) + from "bettybook/http/longv/message/_200.java" + as 200; // 200 OK + +sig "bettybook.http.longv.message.server._404" + from "bettybook/http/longv/message/_404.java" + as 404; + +sig "bettybook.http.longv.message.server.Date" + from "bettybook/http/longv/message/Date.java" + as Date; // Date: Sun, 24 May 2015 21:04:36 GMT + +sig "bettybook.http.longv.message.server.Server" + from "bettybook/http/longv/message/Server.java" + as Server; // Server: Apache + +sig "bettybook.http.longv.message.server.StrictTransportSecurity" + from "bettybook/http/longv/message/StrictTransportSecurity.java" + as StrictTS; // Strict-Transport-Security: max-age=31536000; preload; includeSubDomains + +sig "bettybook.http.longv.message.server.LastModified" + from "bettybook/http/longv/message/LastModified.java" + as LastM; // Last-Modified: Sat, 23 Jul 2011 09:38:43 GMT + +sig "bettybook.http.longv.message.server.ETag" + from "bettybook/http/longv/message/ETag.java" + as ETag; // ETag: "ac6fa008-559-4a8b95908aec0" + +sig "bettybook.http.longv.message.server.AcceptRanges" + from "bettybook/http/longv/message/AcceptRanges.java" + as AcceptR; // Accept-Ranges: bytes + +sig "bettybook.http.longv.message.server.ContentLength" + from "bettybook/http/longv/message/ContentLength.java" + as ContentL; // Content-Length: 1369 + +sig "bettybook.http.longv.message.server.Vary" + from "bettybook/http/longv/message/Vary.java" + as Vary; // Vary: Accept-Encoding + +sig "bettybook.http.longv.message.server.ContentType" + from "bettybook/http/longv/message/ContentType.java" + as ContentT; // Content-Type: text/html + +sig "bettybook.http.longv.message.server.Via" + from "bettybook/http/longv/message/Via.java" + as Via; // Via: 1.1 www.doc.ic.ac.uk + + +global protocol Http(role C, role S) { + do Request(C, S); + do Response(C, S); +} + +aux global protocol Request(role C, role S) { + choice at C { + RequestL from C to S; // GET /~rhu/ HTTP/1.1 + rec X { + choice at C { + Host from C to S; // Host: www.doc.ic.ac.uk + continue X; + } or { + UserA from C to S; // User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; rv:38.0) Gecko/20100101 Firefox/38.0 + continue X; + } or { + Accept from C to S; // Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 + continue X; + } or { + AcceptL from C to S; // Accept-Language: en-GB,en;q=0.5 + continue X; + } or { + AcceptE from C to S; // Accept-Encoding: gzip, deflate + continue X; + } or { + DNT from C to S; // DNT: 1 + continue X; + } or { + Connection from C to S; // Connection: keep-alive + continue X; + } or { + UpgradeIR from C to S; // Upgrade-Insecure-Requests: 1 + continue X; + } or { + Body from C to S; + } + } + } +} + +aux global protocol Response(role C, role S) { + HttpV from S to C; // HTTP/1.1 + choice at S { + 200 from S to C; // 200 OK + } or { + 404 from S to C; + } + + rec Y { + choice at S { + Date from S to C; // Date: Sun, 24 May 2015 21:04:36 GMT + continue Y; + } or { + Server from S to C; // Server: Apache + continue Y; + } or { + StrictTS from S to C; // Strict-Transport-Security: max-age=31536000; preload; includeSubDomains + continue Y; + } or { + LastM from S to C; // Last-Modified: Sat, 23 Jul 2011 09:38:43 GMT + continue Y; + } or { + ETag from S to C; // ETag: "ac6fa008-559-4a8b95908aec0" + continue Y; + } or { + AcceptR from S to C; // Accept-Ranges: bytes + continue Y; + } or { + ContentL from S to C; // Content-Length: 1369 + continue Y; + } or { + Vary from S to C; // Vary: Accept-Encoding + continue Y; + } or { + ContentT from S to C; // Content-Type: text/html + continue Y; + } or { + Via from S to C; // Via: 1.1 www.doc.ic.ac.uk + continue Y; + } or { + Body from S to C; // Message length indicated by Content-Length + } + } +} diff --git a/scribble-demos/scrib/bettybook/src/bettybook/http/longv/HttpLongC.java b/scribble-demos/scrib/bettybook/src/bettybook/http/longv/HttpLongC.java new file mode 100644 index 000000000..33b06b8e5 --- /dev/null +++ b/scribble-demos/scrib/bettybook/src/bettybook/http/longv/HttpLongC.java @@ -0,0 +1,105 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package bettybook.http.longv; + +import static bettybook.http.longv.HttpLong.Http.Http.AcceptR; +import static bettybook.http.longv.HttpLong.Http.Http.Body; +import static bettybook.http.longv.HttpLong.Http.Http.C; +import static bettybook.http.longv.HttpLong.Http.Http.ContentL; +import static bettybook.http.longv.HttpLong.Http.Http.ContentT; +import static bettybook.http.longv.HttpLong.Http.Http.Date; +import static bettybook.http.longv.HttpLong.Http.Http.ETag; +import static bettybook.http.longv.HttpLong.Http.Http.HttpV; +import static bettybook.http.longv.HttpLong.Http.Http.LastM; +import static bettybook.http.longv.HttpLong.Http.Http.S; +import static bettybook.http.longv.HttpLong.Http.Http.Server; +import static bettybook.http.longv.HttpLong.Http.Http.StrictTS; +import static bettybook.http.longv.HttpLong.Http.Http.Vary; +import static bettybook.http.longv.HttpLong.Http.Http.Via; +import static bettybook.http.longv.HttpLong.Http.Http._200; +import static bettybook.http.longv.HttpLong.Http.Http._404; + +import org.scribble.runtime.net.SocketChannelEndpoint; +import org.scribble.runtime.session.MPSTEndpoint; +import org.scribble.runtime.util.Buf; + +import bettybook.http.longv.HttpLong.Http.Http; +import bettybook.http.longv.HttpLong.Http.roles.C; +import bettybook.http.longv.HttpLong.Http.statechans.C.EndSocket; +import bettybook.http.longv.HttpLong.Http.statechans.C.Http_C_1; +import bettybook.http.longv.HttpLong.Http.statechans.C.Http_C_3; +import bettybook.http.longv.HttpLong.Http.statechans.C.Http_C_4_Cases; +import bettybook.http.longv.HttpLong.Http.statechans.C.Http_C_5; +import bettybook.http.longv.HttpLong.Http.statechans.C.Http_C_5_Cases; +import bettybook.http.longv.message.Body; +import bettybook.http.longv.message.HttpLongMessageFormatter; +import bettybook.http.longv.message.client.Host; +import bettybook.http.longv.message.client.RequestLine; + +public class HttpLongC { + + public static void main(String[] args) throws Exception { + Http http = new Http(); + try (MPSTEndpoint client = new MPSTEndpoint<>(http, C, + new HttpLongMessageFormatter())) { + String host = "example.com"; int port = 80; String file = "/"; + //String host = "localhost"; int port = 8080; String file = "/"; + + client.request(S, SocketChannelEndpoint::new, host, port); + new HttpLongC().run(new Http_C_1(client), host, file); + } + } + + public void run(Http_C_1 s1, String host, String file) throws Exception { + doResponse(doRequest(s1, host, file)); + } + + private Http_C_3 doRequest(Http_C_1 s1, String host, String file) throws Exception { + return s1.send(S, new RequestLine(file, "1.1")) + .send(S, new Host(host)) + .send(S, new Body("")); + } + + private void doResponse(Http_C_3 s3) throws Exception { + Http_C_4_Cases cases = s3.async(S, HttpV).branch(S); + switch (cases.op) { + case _200: doResponseAux(cases.receive(_200)); break; + case _404: doResponseAux(cases.receive(_404)); break; + default: throw new RuntimeException("[TODO]: " + cases.op); + } + } + + private EndSocket doResponseAux(Http_C_5 c5) throws Exception { + Http_C_5_Cases cases = c5.branch(S); + switch (cases.op) { + case AcceptR: return doResponseAux(cases.receive(AcceptR)); + case ContentL: return doResponseAux(cases.receive(ContentL)); + case ContentT: return doResponseAux(cases.receive(ContentT)); + case Date: return doResponseAux(cases.receive(Date)); + case ETag: return doResponseAux(cases.receive(ETag)); + case LastM: return doResponseAux(cases.receive(LastM)); + case Server: return doResponseAux(cases.receive(Server)); + case StrictTS: return doResponseAux(cases.receive(StrictTS)); + case Vary: return doResponseAux(cases.receive(Vary)); + case Via: return doResponseAux(cases.receive(Via)); + case Body: { + Buf buf_body = new Buf<>(); + EndSocket end = cases.receive(Body, buf_body); + System.out.println(buf_body.val.getBody()); + return end; + } + default: throw new RuntimeException("[TODO]: " + cases.op); + } + } +} diff --git a/scribble-demos/scrib/bettybook/src/bettybook/http/longv/HttpLongS.java b/scribble-demos/scrib/bettybook/src/bettybook/http/longv/HttpLongS.java new file mode 100644 index 000000000..5fd4ceefa --- /dev/null +++ b/scribble-demos/scrib/bettybook/src/bettybook/http/longv/HttpLongS.java @@ -0,0 +1,100 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package bettybook.http.longv; + +import static bettybook.http.longv.HttpLong.Http.Http.Accept; +import static bettybook.http.longv.HttpLong.Http.Http.AcceptE; +import static bettybook.http.longv.HttpLong.Http.Http.AcceptL; +import static bettybook.http.longv.HttpLong.Http.Http.Body; +import static bettybook.http.longv.HttpLong.Http.Http.C; +import static bettybook.http.longv.HttpLong.Http.Http.Connection; +import static bettybook.http.longv.HttpLong.Http.Http.DNT; +import static bettybook.http.longv.HttpLong.Http.Http.Host; +import static bettybook.http.longv.HttpLong.Http.Http.RequestL; +import static bettybook.http.longv.HttpLong.Http.Http.S; +import static bettybook.http.longv.HttpLong.Http.Http.UpgradeIR; +import static bettybook.http.longv.HttpLong.Http.Http.UserA; + +import java.io.IOException; + +import org.scribble.main.ScribRuntimeException; +import org.scribble.runtime.net.ScribServerSocket; +import org.scribble.runtime.net.SocketChannelServer; +import org.scribble.runtime.session.MPSTEndpoint; +import org.scribble.runtime.util.Buf; + +import bettybook.http.longv.HttpLong.Http.Http; +import bettybook.http.longv.HttpLong.Http.roles.S; +import bettybook.http.longv.HttpLong.Http.statechans.S.Http_S_1; +import bettybook.http.longv.HttpLong.Http.statechans.S.Http_S_2; +import bettybook.http.longv.HttpLong.Http.statechans.S.Http_S_2_Cases; +import bettybook.http.longv.message.Body; +import bettybook.http.longv.message.HttpLongMessageFormatter; +import bettybook.http.longv.message.server.ContentLength; +import bettybook.http.longv.message.server.HttpVersion; +import bettybook.http.longv.message.server._200; + +public class HttpLongS +{ + public static void main(String[] args) throws Exception + { + try (ScribServerSocket ss = new SocketChannelServer(8080)) { + while (true) { + Http http = new Http(); + try (MPSTEndpoint server = new MPSTEndpoint<>(http, S, + new HttpLongMessageFormatter())) { + server.accept(ss, C); + + run(new Http_S_1(server)); + } + catch (IOException | ClassNotFoundException | ScribRuntimeException e) + { + e.printStackTrace(); + } + } + } + } + + private static void run(Http_S_1 s1) + throws ClassNotFoundException, ScribRuntimeException, IOException { + Buf buf = new Buf<>(); + + Http_S_2 s2 = s1.receive(C, RequestL, buf); + System.out.println("Requested: " + buf.val); + + Y: while (true) { + Http_S_2_Cases cases = s2.branch(C); + switch (cases.op) { + case Accept: s2 = cases.receive(Accept, buf); break; + case AcceptE: s2 = cases.receive(AcceptE, buf); break; + case AcceptL: s2 = cases.receive(AcceptL, buf); break; + case Body: + { + String body = "Hello, World!"; + cases.receive(Body, buf) + .send(C, new HttpVersion("1.1")) + .send(C, new _200("OK")) + .send(C, new ContentLength(body.length())) + .send(C, new Body(body)); + break Y; + } + case Connection: s2 = cases.receive(Connection, buf); break; + case DNT: s2 = cases.receive(DNT, buf); break; + case UpgradeIR: s2 = cases.receive(UpgradeIR, buf); break; + case Host: s2 = cases.receive(Host, buf); break; + case UserA: s2 = cases.receive(UserA, buf); break; + } + } + } +} diff --git a/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/Body.java b/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/Body.java new file mode 100644 index 000000000..a013fda47 --- /dev/null +++ b/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/Body.java @@ -0,0 +1,32 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package bettybook.http.longv.message; + +import bettybook.http.longv.HttpLong.Http.Http; + +public class Body extends HttpLongMessage +{ + private static final long serialVersionUID = 1L; + + public Body(String body) + { + super(Http.Body, body); + } + + @Override + public byte[] toBytes() + { + return (getOpString(this.op) + getBody()).getBytes(HttpLongMessageFormatter.cs); // opString should be empty + } +} diff --git a/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/HeaderField.java b/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/HeaderField.java new file mode 100644 index 000000000..9ea724145 --- /dev/null +++ b/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/HeaderField.java @@ -0,0 +1,26 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package bettybook.http.longv.message; + +import org.scribble.core.type.name.Op; + +public abstract class HeaderField extends HttpLongMessage +{ + private static final long serialVersionUID = 1L; + + public HeaderField(Op name, String value) + { + super(name, ": " + value + " "); + } +} diff --git a/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/HttpLongMessage.java b/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/HttpLongMessage.java new file mode 100644 index 000000000..7b4cce573 --- /dev/null +++ b/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/HttpLongMessage.java @@ -0,0 +1,152 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package bettybook.http.longv.message; + +import org.scribble.core.type.name.Op; +import org.scribble.runtime.message.ScribMessage; + +import bettybook.http.longv.HttpLong.Http.Http; + +// Unlike ScribMessage, HttpMessage is not actually "sent", but we use it as the base class since the socket API takes ScribMessages +public abstract class HttpLongMessage extends ScribMessage +{ + private static final long serialVersionUID = 1L; + + // " " after ops done by HeaderField + public static final String GET = "GET"; + public static final String HTTP = "HTTP"; + public static final String HOST = "Host"; + + public static final String USER_AGENT = "User-Agent"; + public static final String ACCEPT = "Accept"; + public static final String ACCEPT_LANGUAGE = "Accept-Language"; + public static final String ACCEPT_ENCODING = "Accept-Encoding"; + public static final String DO_NOT_TRACK = "DNT"; + public static final String CONNECTION = "Connection"; + public static final String UPGRADE_INSECURE_REQUESTS = "Upgrade-Insecure-Requests"; + + public static final String DATE = "Date"; + public static final String CONTENT_TYPE = "Content-Type"; + public static final String _404 = "404"; + public static final String _200 = "200"; + public static final String ACCEPT_RANGES = "Accept-Ranges"; + public static final String LAST_MODIFIED = "Last-Modified"; + public static final String VARY = "Vary"; + public static final String SERVER = "Server"; + public static final String STRICT_TRANSPORT_SECURITY = "Strict-Transport-Security"; + public static final String VIA = "Via"; + public static final String ETAG = "ETag"; + public static final String CONTENT_LENGTH = "Content-Length"; + + protected static final String CRLF = "\r\n"; + + public HttpLongMessage(Op op) + { + super(op); + } + + public HttpLongMessage(Op op, String body) + { + super(op, body); + } + + public String getBody() + { + return (this.payload.length == 0) ? "" : (String) this.payload[0]; + } + + public byte[] toBytes() + { + return (getOpString(this.op) + getBody() + HttpLongMessage.CRLF).getBytes(HttpLongMessageFormatter.cs); // Can give "utf-8" as arg directly + } + + @Override + public String toString() + { + return new String(toBytes()); + } + + // " " after ops done by HeaderField + protected static String getOpString(Op op) + { + if (op.equals(Http.ContentL)) + { + return HttpLongMessage.CONTENT_LENGTH; + } + else if (op.equals(Http.ETag)) + { + return HttpLongMessage.ETAG; + } + else if (op.equals(Http.Body)) + { + return HttpLongMessage.CRLF; // This CRLF "op" actually enacts the empty line for end-of-headers + } + else if (op.equals(Http.Via)) + { + return HttpLongMessage.VIA; + } + else if (op.equals(Http.Server)) + { + return HttpLongMessage.SERVER; + } + else if (op.equals(Http.Vary)) + { + return HttpLongMessage.VARY; + } + else if (op.equals(HttpLongMessage.CRLF)) + { + return ""; + } + else if (op.equals(Http.RequestL)) // FIXME: not just GET (POST..) + { + return HttpLongMessage.GET; + } + else if (op.equals(Http.LastM)) + { + return HttpLongMessage.LAST_MODIFIED; + } + else if (op.equals(Http.AcceptR)) + { + return HttpLongMessage.ACCEPT_RANGES; + } + else if (op.equals(Http.Host)) + { + return HttpLongMessage.HOST; + } + else if (op.equals(Http.HttpV)) + { + return HttpLongMessage.HTTP; + } + else if (op.equals(Http._200)) + { + return HttpLongMessage._200; + } + else if (op.equals(Http._404)) + { + return HttpLongMessage._404; + } + else if (op.equals(Http.ContentT)) + { + return HttpLongMessage.CONTENT_TYPE; + } + else if (op.equals(Http.Date)) + { + return HttpLongMessage.DATE; + } + else + { + throw new RuntimeException("TODO: " + op); + } + } +} diff --git a/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/HttpLongMessageFormatter.java b/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/HttpLongMessageFormatter.java new file mode 100644 index 000000000..2ff68850c --- /dev/null +++ b/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/HttpLongMessageFormatter.java @@ -0,0 +1,413 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package bettybook.http.longv.message; + +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.Charset; + +import org.scribble.runtime.message.ScribMessage; +import org.scribble.runtime.message.ScribMessageFormatter; + +import bettybook.http.longv.message.client.Accept; +import bettybook.http.longv.message.client.AcceptEncoding; +import bettybook.http.longv.message.client.AcceptLanguage; +import bettybook.http.longv.message.client.Connection; +import bettybook.http.longv.message.client.DoNotTrack; +import bettybook.http.longv.message.client.Host; +import bettybook.http.longv.message.client.RequestLine; +import bettybook.http.longv.message.client.UpgradeInsecureRequests; +import bettybook.http.longv.message.client.UserAgent; +import bettybook.http.longv.message.server.AcceptRanges; +import bettybook.http.longv.message.server.ContentLength; +import bettybook.http.longv.message.server.ContentType; +import bettybook.http.longv.message.server.Date; +import bettybook.http.longv.message.server.ETag; +import bettybook.http.longv.message.server.HttpVersion; +import bettybook.http.longv.message.server.LastModified; +import bettybook.http.longv.message.server.Server; +import bettybook.http.longv.message.server.StrictTransportSecurity; +import bettybook.http.longv.message.server.Vary; +import bettybook.http.longv.message.server.Via; +import bettybook.http.longv.message.server._200; +import bettybook.http.longv.message.server._404; + +public class HttpLongMessageFormatter implements ScribMessageFormatter +{ + public static final Charset cs = Charset.forName("UTF8"); + //private static CharsetDecoder cd = cs.newDecoder(); + + private int len = -1; + + public HttpLongMessageFormatter() + { + + } + + @Override + public byte[] toBytes(ScribMessage m) throws IOException + { + return ((HttpLongMessage) m).toBytes(); + } + + @Override + public ScribMessage fromBytes(ByteBuffer bb) throws IOException, ClassNotFoundException + { + bb.flip(); + int rem = bb.remaining(); + if (rem < 2) + { + bb.compact(); + return null; + } + + int pos = bb.position(); + String front = new String(new byte[] { bb.get(pos), bb.get(pos + 1) }, HttpLongMessageFormatter.cs); + if (front.equals(HttpLongMessage.CRLF)) // not sound? -- actually, due to sess types it is safe (same reason why interpreting any of these messages without context is sound) -- parsing doesn't have to follow the *full protocol* BNF any more to be sound + { + if (this.len == -1) + { + return new Body(""); + } + if (rem < this.len + 2) + { + bb.compact(); + return null; + } + //String body = readLine(dis) + HttpMessage.CRLF; // HACK: assumes at least 1 CRLF + StringBuffer sb = new StringBuffer(); + //for (int i = body.length(); i < this.len; i++) + for (int i = 0; i < this.len; i++) + { + sb.append((char) bb.get()); + } + this.len = -1; + //return new Body(body + sb.toString()); + return new Body(sb.toString()); + } + + if (rem < pos + 4) + { + bb.compact(); + return null; + } + //byte[] bs = new byte[2]; + //dis.readFully(bs); + front += new String(new byte[] { bb.get(pos + 2), bb.get(pos + 3) }, HttpLongMessageFormatter.cs); + // FIXME: factor out with HttpMessage op strings + int code = isStatusCode(front); + if (code > -1) + { + String reason = readLine(bb, pos + 4).trim(); // Whitespace already built into the message classes + bb.compact(); + if (reason == null) + { + return null; + } + switch (code) + { + case 200: return new _200(reason); + case 404: return new _404(reason); + default: throw new RuntimeException("Unknown status code: " + code); + } + } + else if (front.startsWith(HttpLongMessage.GET)) + { + String reql = readLine(bb, pos + 4).trim(); + bb.compact(); + if (reql == null) + { + return null; + } + String target = reql.substring(0, reql.indexOf(' ')); + String vers = reql.substring(reql.indexOf(' ') + 1).trim(); + vers = vers.substring(vers.indexOf('/') + 1); + return new RequestLine(target, vers); + } + else if (front.equals(HttpLongMessage.HTTP)) + { + //dis.read(); // '/' + if (rem < pos + 5) + { + bb.compact(); + return null; + } + String word = readWord(bb, pos + 5); + bb.compact(); + if (word == null) + { + return null; + } + return new HttpVersion(word); + } + else + { + String line = readLine(bb, pos + 4); + bb.compact(); + if (line == null) + { + return null; + } + line = front + line; + int colon = line.indexOf(':'); + if (colon > -1) + { + String name = line.substring(0, colon); + String value = line.substring(colon + 1).trim(); // Whitespace already built into the message classes + switch (name) + { + case HttpLongMessage.HOST: return new Host("value"); + case HttpLongMessage.USER_AGENT: return new UserAgent(value); + case HttpLongMessage.ACCEPT: return new Accept(value); + case HttpLongMessage.ACCEPT_LANGUAGE: return new AcceptLanguage(value); + case HttpLongMessage.ACCEPT_ENCODING: return new AcceptEncoding(value); + case HttpLongMessage.DO_NOT_TRACK: return new DoNotTrack(Integer.parseInt(value)); + case HttpLongMessage.CONNECTION: return new Connection(value); + case HttpLongMessage.UPGRADE_INSECURE_REQUESTS: return new UpgradeInsecureRequests(Integer.parseInt(value)); + + case HttpLongMessage.DATE: return new Date(value); + case HttpLongMessage.SERVER: return new Server(value); + case HttpLongMessage.STRICT_TRANSPORT_SECURITY: return new StrictTransportSecurity(value); + case HttpLongMessage.LAST_MODIFIED: return new LastModified(value); + case HttpLongMessage.ETAG: return new ETag(value); + case HttpLongMessage.ACCEPT_RANGES: return new AcceptRanges(value); + case HttpLongMessage.CONTENT_LENGTH: + { + len = Integer.parseInt(value.trim()); + return new ContentLength(len); + } + case HttpLongMessage.VARY: return new Vary(value); + case HttpLongMessage.CONTENT_TYPE: return new ContentType(value); + case HttpLongMessage.VIA: return new Via(value); + default: { + //throw new RuntimeException("Cannot parse header field: " + line); + System.err.println("Cannot parse header field, attempting to skip: " + line); + return fromBytes(bb); + } + } + } + else + { + throw new RuntimeException("Cannot parse message: " + line); + } + } + } + + private static String readLine(ByteBuffer bb, int i) throws IOException + { + StringBuilder sb = new StringBuilder(); + for (int limit = bb.limit(); i <= limit; ) + { + char c = (char) bb.get(i++); // readChar is not the same + sb.append(c); + if (c == '\r') + { + if (i > limit) + { + return null; + } + c = (char) bb.get(i++); + sb.append(c); + if (c == '\n') + { + bb.position(i); + return sb.substring(0, sb.length() - 2).toString(); + } + } + } + return null; + } + + private static String readWord(ByteBuffer bb, int i) throws IOException + { + StringBuilder sb = new StringBuilder(); + for (int limit = bb.limit(); i <= limit; ) + { + char c = (char) bb.get(i++); + if (c == ' ') + { + bb.position(i); + return sb.toString(); + } + sb.append(c); + } + return null; + } + + //private int isStatusCode(byte[] bs) + private int isStatusCode(String front) + { + String code = ""; + for (int i = 0; i < 4; i++) + { + //char c = (char) bs[i]; + char c = front.charAt(i); + if (i < 3) + { + if (c < '0' || c > '9') + { + return -1; + } + code += c; + } + else + { + if (c != ' ') + { + return -1; + } + } + } + return Integer.parseInt(code); + } + + + + // FIXME: delete + @Deprecated @Override + public void writeMessage(DataOutputStream dos, ScribMessage m) throws IOException + { + dos.write(((HttpLongMessage) m).toBytes()); + dos.flush(); + } + + @Deprecated @Override + public ScribMessage readMessage(DataInputStream dis) throws IOException + { + byte[] bs = new byte[2]; + dis.readFully(bs); + String front = new String(bs, HttpLongMessageFormatter.cs); + if (front.equals(HttpLongMessage.CRLF)) // not sound? -- actually, due to sess types it is safe (same reason why interpreting any of these messages without context is sound) -- parsing doesn't have to follow the *full protocol* BNF any more to be sound + { + if (this.len == -1) + { + return new Body(""); + } + //String body = readLine(dis) + HttpMessage.CRLF; // HACK: assumes at least 1 CRLF + StringBuffer sb = new StringBuffer(); + //for (int i = body.length(); i < this.len; i++) + for (int i = 0; i < this.len; i++) + { + sb.append((char) dis.read()); + } + this.len = -1; + //return new Body(body + sb.toString()); + return new Body(sb.toString()); + } + + bs = new byte[2]; + dis.readFully(bs); + front += new String(bs, HttpLongMessageFormatter.cs); + // FIXME: factor out with HttpMessage op strings + int code = isStatusCode(front); + if (code > -1) + { + String reason = readLine(dis).trim(); // Whitespace already built into the message classes + switch (code) + { + case 200: return new _200(reason); + case 404: return new _404(reason); + default: throw new RuntimeException("Unknown status code: " + code); + } + } + else if (front.startsWith(HttpLongMessage.GET)) + { + String reql = readLine(dis).trim(); + String target = reql.substring(0, reql.indexOf(' ')); + String vers = reql.substring(reql.indexOf(' ') + 1).trim(); + vers = vers.substring(vers.indexOf('/') + 1); + return new RequestLine(target, vers); + } + else if (front.equals(HttpLongMessage.HTTP)) + { + dis.read(); // '/' + String word = readWord(dis); + return new HttpVersion(word); + } + else + { + String line = front + readLine(dis); + int colon = line.indexOf(':'); + if (colon > -1) + { + String name = line.substring(0, colon); + String value = line.substring(colon + 1).trim(); // Whitespace already built into the message classes + switch (name) + { + case HttpLongMessage.HOST: return new Host("value"); + case HttpLongMessage.USER_AGENT: return new UserAgent(value); + case HttpLongMessage.ACCEPT: return new Accept(value); + case HttpLongMessage.ACCEPT_LANGUAGE: return new AcceptLanguage(value); + case HttpLongMessage.ACCEPT_ENCODING: return new AcceptEncoding(value); + case HttpLongMessage.DO_NOT_TRACK: return new DoNotTrack(Integer.parseInt(value)); + case HttpLongMessage.CONNECTION: return new Connection(value); + + case HttpLongMessage.DATE: return new Date(value); + case HttpLongMessage.SERVER: return new Server(value); + case HttpLongMessage.LAST_MODIFIED: return new LastModified(value); + case HttpLongMessage.ETAG: return new ETag(value); + case HttpLongMessage.ACCEPT_RANGES: return new AcceptRanges(value); + case HttpLongMessage.CONTENT_LENGTH: + { + len = Integer.parseInt(value.trim()); + return new ContentLength(len); + } + case HttpLongMessage.VARY: return new Vary(value); + case HttpLongMessage.CONTENT_TYPE: return new ContentType(value); + case HttpLongMessage.VIA: return new Via(value); + default: throw new RuntimeException("Cannot parse header field: " + line); + } + } + else + { + throw new RuntimeException("Cannot parse message: " + line); + } + } + } + + private static String readLine(DataInputStream dis) throws IOException + { + StringBuilder sb = new StringBuilder(); + for (; true; ) + { + char c = (char) dis.read(); // readChar is not the same + sb.append(c); + if (c == '\r') + { + c = (char) dis.read(); + sb.append(c); + if (c == '\n') + { + return sb.substring(0, sb.length() - 2).toString(); + } + } + } + } + + private static String readWord(DataInputStream dis) throws IOException + { + StringBuilder sb = new StringBuilder(); + for (; true; ) + { + char c = (char) dis.read(); + if (c == ' ') + { + return sb.toString(); + } + sb.append(c); + } + } +} diff --git a/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/StartLine.java b/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/StartLine.java new file mode 100644 index 000000000..ac7122583 --- /dev/null +++ b/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/StartLine.java @@ -0,0 +1,26 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package bettybook.http.longv.message; + +import org.scribble.core.type.name.Op; + +public abstract class StartLine extends HttpLongMessage +{ + private static final long serialVersionUID = 1L; + + public StartLine(Op op, String body) + { + super(op, body); + } +} diff --git a/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/client/Accept.java b/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/client/Accept.java new file mode 100644 index 000000000..9ba0138c8 --- /dev/null +++ b/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/client/Accept.java @@ -0,0 +1,27 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package bettybook.http.longv.message.client; + +import bettybook.http.longv.HttpLong.Http.Http; +import bettybook.http.longv.message.HeaderField; + +public class Accept extends HeaderField +{ + private static final long serialVersionUID = 1L; + + public Accept(String text) + { + super(Http.Accept, text); + } +} diff --git a/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/client/AcceptEncoding.java b/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/client/AcceptEncoding.java new file mode 100644 index 000000000..93ae038eb --- /dev/null +++ b/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/client/AcceptEncoding.java @@ -0,0 +1,27 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package bettybook.http.longv.message.client; + +import bettybook.http.longv.HttpLong.Http.Http; +import bettybook.http.longv.message.HeaderField; + +public class AcceptEncoding extends HeaderField +{ + private static final long serialVersionUID = 1L; + + public AcceptEncoding(String text) + { + super(Http.AcceptE, text); + } +} diff --git a/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/client/AcceptLanguage.java b/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/client/AcceptLanguage.java new file mode 100644 index 000000000..b09b325c3 --- /dev/null +++ b/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/client/AcceptLanguage.java @@ -0,0 +1,27 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package bettybook.http.longv.message.client; + +import bettybook.http.longv.HttpLong.Http.Http; +import bettybook.http.longv.message.HeaderField; + +public class AcceptLanguage extends HeaderField +{ + private static final long serialVersionUID = 1L; + + public AcceptLanguage(String text) + { + super(Http.AcceptL, text); + } +} diff --git a/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/client/Connection.java b/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/client/Connection.java new file mode 100644 index 000000000..58ad475f1 --- /dev/null +++ b/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/client/Connection.java @@ -0,0 +1,27 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package bettybook.http.longv.message.client; + +import bettybook.http.longv.HttpLong.Http.Http; +import bettybook.http.longv.message.HeaderField; + +public class Connection extends HeaderField +{ + private static final long serialVersionUID = 1L; + + public Connection(String text) + { + super(Http.Connection, text); + } +} diff --git a/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/client/DoNotTrack.java b/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/client/DoNotTrack.java new file mode 100644 index 000000000..43df8a147 --- /dev/null +++ b/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/client/DoNotTrack.java @@ -0,0 +1,27 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package bettybook.http.longv.message.client; + +import bettybook.http.longv.HttpLong.Http.Http; +import bettybook.http.longv.message.HeaderField; + +public class DoNotTrack extends HeaderField +{ + private static final long serialVersionUID = 1L; + + public DoNotTrack(int val) + { + super(Http.DNT, Integer.toString(val)); + } +} diff --git a/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/client/Host.java b/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/client/Host.java new file mode 100644 index 000000000..355ef0904 --- /dev/null +++ b/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/client/Host.java @@ -0,0 +1,27 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package bettybook.http.longv.message.client; + +import bettybook.http.longv.HttpLong.Http.Http; +import bettybook.http.longv.message.HeaderField; + +public class Host extends HeaderField +{ + private static final long serialVersionUID = 1L; + + public Host(String host) + { + super(Http.Host, host); + } +} diff --git a/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/client/RequestLine.java b/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/client/RequestLine.java new file mode 100644 index 000000000..90cbdd8d7 --- /dev/null +++ b/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/client/RequestLine.java @@ -0,0 +1,29 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package bettybook.http.longv.message.client; + +import bettybook.http.longv.HttpLong.Http.Http; +import bettybook.http.longv.message.StartLine; + + +// FIXME: not just GET +public class RequestLine extends StartLine +{ + private static final long serialVersionUID = 1L; + + public RequestLine(String reqtarget, String vers) + { + super(Http.RequestL, " " + reqtarget + " HTTP" + "/" + vers); + } +} diff --git a/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/client/UpgradeInsecureRequests.java b/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/client/UpgradeInsecureRequests.java new file mode 100644 index 000000000..844fc8447 --- /dev/null +++ b/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/client/UpgradeInsecureRequests.java @@ -0,0 +1,27 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package bettybook.http.longv.message.client; + +import bettybook.http.longv.HttpLong.Http.Http; +import bettybook.http.longv.message.HeaderField; + +public class UpgradeInsecureRequests extends HeaderField +{ + private static final long serialVersionUID = 1L; + + public UpgradeInsecureRequests(int val) + { + super(Http.UpgradeIR, Integer.toString(val)); + } +} diff --git a/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/client/UserAgent.java b/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/client/UserAgent.java new file mode 100644 index 000000000..81b402550 --- /dev/null +++ b/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/client/UserAgent.java @@ -0,0 +1,27 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package bettybook.http.longv.message.client; + +import bettybook.http.longv.HttpLong.Http.Http; +import bettybook.http.longv.message.HeaderField; + +public class UserAgent extends HeaderField +{ + private static final long serialVersionUID = 1L; + + public UserAgent(String text) + { + super(Http.UserA, text); + } +} diff --git a/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/server/AcceptRanges.java b/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/server/AcceptRanges.java new file mode 100644 index 000000000..3323cd20c --- /dev/null +++ b/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/server/AcceptRanges.java @@ -0,0 +1,27 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package bettybook.http.longv.message.server; + +import bettybook.http.longv.HttpLong.Http.Http; +import bettybook.http.longv.message.HeaderField; + +public class AcceptRanges extends HeaderField +{ + private static final long serialVersionUID = 1L; + + public AcceptRanges(String text) + { + super(Http.AcceptR, text); + } +} diff --git a/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/server/CRLF.java b/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/server/CRLF.java new file mode 100644 index 000000000..6b6c85dc8 --- /dev/null +++ b/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/server/CRLF.java @@ -0,0 +1,29 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package bettybook.http.longv.message.server; + +import bettybook.http.longv.message.HttpLongMessage; + +@Deprecated +public class CRLF extends HttpLongMessage +{ + private static final long serialVersionUID = 1L; + + public CRLF() + { + //super(Http.CRLF, HttpMessage.CRLF); // No: HttpMessage already appends the CRLF + //super(Http.CRLF, ""); + super(null, ""); + } +} diff --git a/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/server/ContentLength.java b/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/server/ContentLength.java new file mode 100644 index 000000000..f92f59e26 --- /dev/null +++ b/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/server/ContentLength.java @@ -0,0 +1,27 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package bettybook.http.longv.message.server; + +import bettybook.http.longv.HttpLong.Http.Http; +import bettybook.http.longv.message.HeaderField; + +public class ContentLength extends HeaderField +{ + private static final long serialVersionUID = 1L; + + public ContentLength(Integer len) + { + super(Http.ContentL, len.toString()); + } +} diff --git a/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/server/ContentType.java b/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/server/ContentType.java new file mode 100644 index 000000000..c22d6d7d5 --- /dev/null +++ b/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/server/ContentType.java @@ -0,0 +1,27 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package bettybook.http.longv.message.server; + +import bettybook.http.longv.HttpLong.Http.Http; +import bettybook.http.longv.message.HeaderField; + +public class ContentType extends HeaderField +{ + private static final long serialVersionUID = 1L; + + public ContentType(String type) + { + super(Http.ContentT, type); + } +} diff --git a/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/server/Date.java b/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/server/Date.java new file mode 100644 index 000000000..a7a68d9d1 --- /dev/null +++ b/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/server/Date.java @@ -0,0 +1,27 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package bettybook.http.longv.message.server; + +import bettybook.http.longv.HttpLong.Http.Http; +import bettybook.http.longv.message.HeaderField; + +public class Date extends HeaderField +{ + private static final long serialVersionUID = 1L; + + public Date(String date) + { + super(Http.Date, date); + } +} diff --git a/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/server/ETag.java b/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/server/ETag.java new file mode 100644 index 000000000..c76d42fb7 --- /dev/null +++ b/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/server/ETag.java @@ -0,0 +1,27 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package bettybook.http.longv.message.server; + +import bettybook.http.longv.HttpLong.Http.Http; +import bettybook.http.longv.message.HeaderField; + +public class ETag extends HeaderField +{ + private static final long serialVersionUID = 1L; + + public ETag(String tag) + { + super(Http.ETag, tag); + } +} diff --git a/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/server/HttpVersion.java b/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/server/HttpVersion.java new file mode 100644 index 000000000..7234c179b --- /dev/null +++ b/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/server/HttpVersion.java @@ -0,0 +1,34 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package bettybook.http.longv.message.server; + +import bettybook.http.longv.HttpLong.Http.Http; +import bettybook.http.longv.message.HttpLongMessage; +import bettybook.http.longv.message.HttpLongMessageFormatter; + +public class HttpVersion extends HttpLongMessage +{ + private static final long serialVersionUID = 1L; + + public HttpVersion(String version) + { + super(Http.HttpV, "/" + version); + } + + @Override + public byte[] toBytes() + { + return (getOpString(op) + getBody() + " ").getBytes(HttpLongMessageFormatter.cs); + } +} diff --git a/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/server/LastModified.java b/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/server/LastModified.java new file mode 100644 index 000000000..8e8e39374 --- /dev/null +++ b/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/server/LastModified.java @@ -0,0 +1,27 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package bettybook.http.longv.message.server; + +import bettybook.http.longv.HttpLong.Http.Http; +import bettybook.http.longv.message.HeaderField; + +public class LastModified extends HeaderField +{ + private static final long serialVersionUID = 1L; + + public LastModified(String date) + { + super(Http.LastM, date); + } +} diff --git a/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/server/Server.java b/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/server/Server.java new file mode 100644 index 000000000..0404f42d4 --- /dev/null +++ b/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/server/Server.java @@ -0,0 +1,27 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package bettybook.http.longv.message.server; + +import bettybook.http.longv.HttpLong.Http.Http; +import bettybook.http.longv.message.HeaderField; + +public class Server extends HeaderField +{ + private static final long serialVersionUID = 1L; + + public Server(String server) + { + super(Http.Server, server); + } +} diff --git a/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/server/StatusCode.java b/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/server/StatusCode.java new file mode 100644 index 000000000..f2216df9e --- /dev/null +++ b/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/server/StatusCode.java @@ -0,0 +1,28 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package bettybook.http.longv.message.server; + +import org.scribble.core.type.name.Op; + +import bettybook.http.longv.message.HttpLongMessage; + +public abstract class StatusCode extends HttpLongMessage +{ + private static final long serialVersionUID = 1L; + + public StatusCode(Op code, String reason) + { + super(code, " " + reason); + } +} diff --git a/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/server/StrictTransportSecurity.java b/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/server/StrictTransportSecurity.java new file mode 100644 index 000000000..d9b970653 --- /dev/null +++ b/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/server/StrictTransportSecurity.java @@ -0,0 +1,27 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package bettybook.http.longv.message.server; + +import bettybook.http.longv.HttpLong.Http.Http; +import bettybook.http.longv.message.HeaderField; + +public class StrictTransportSecurity extends HeaderField +{ + private static final long serialVersionUID = 1L; + + public StrictTransportSecurity(String server) + { + super(Http.StrictTS, server); + } +} diff --git a/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/server/Vary.java b/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/server/Vary.java new file mode 100644 index 000000000..99d8f0811 --- /dev/null +++ b/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/server/Vary.java @@ -0,0 +1,27 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package bettybook.http.longv.message.server; + +import bettybook.http.longv.HttpLong.Http.Http; +import bettybook.http.longv.message.HeaderField; + +public class Vary extends HeaderField +{ + private static final long serialVersionUID = 1L; + + public Vary(String text) + { + super(Http.Vary, text); + } +} diff --git a/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/server/Via.java b/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/server/Via.java new file mode 100644 index 000000000..985272b9f --- /dev/null +++ b/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/server/Via.java @@ -0,0 +1,27 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package bettybook.http.longv.message.server; + +import bettybook.http.longv.HttpLong.Http.Http; +import bettybook.http.longv.message.HeaderField; + +public class Via extends HeaderField +{ + private static final long serialVersionUID = 1L; + + public Via(String text) + { + super(Http.Via, text); + } +} diff --git a/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/server/_200.java b/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/server/_200.java new file mode 100644 index 000000000..6cffdb99c --- /dev/null +++ b/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/server/_200.java @@ -0,0 +1,26 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package bettybook.http.longv.message.server; + +import bettybook.http.longv.HttpLong.Http.Http; + +public class _200 extends StatusCode +{ + private static final long serialVersionUID = 1L; + + public _200(String reason) + { + super(Http._200, reason); + } +} diff --git a/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/server/_404.java b/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/server/_404.java new file mode 100644 index 000000000..5414ef71b --- /dev/null +++ b/scribble-demos/scrib/bettybook/src/bettybook/http/longv/message/server/_404.java @@ -0,0 +1,26 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package bettybook.http.longv.message.server; + +import bettybook.http.longv.HttpLong.Http.Http; + +public class _404 extends StatusCode +{ + private static final long serialVersionUID = 1L; + + public _404(String reason) + { + super(Http._404, reason); + } +} diff --git a/scribble-demos/scrib/bettybook/src/bettybook/http/shortv/HttpShort.scr b/scribble-demos/scrib/bettybook/src/bettybook/http/shortv/HttpShort.scr new file mode 100644 index 000000000..e8baa5d33 --- /dev/null +++ b/scribble-demos/scrib/bettybook/src/bettybook/http/shortv/HttpShort.scr @@ -0,0 +1,23 @@ +/** + * Assuming scribblec.sh in scribble-java root directory: + * + * bin/scribblec.sh -d scribble-demos/scrib/bettybook/src scribble-demos/scrib/bettybook/src/bettybook/http/shortv/HttpShort.scr -api Http C + */ + + +module bettybook.http.shortv.HttpShort; + + +sig "bettybook.http.shortv.message.client.Req" + from "bettybook/httpshort/message/Req.java" + as Req; + +sig "bettybook.http.shortv.message.server.Resp" + from "bettybook/shortvers/message/Resp.java" + as Resp; + + +global protocol Http(role C, role S) { + Req from C to S; + Resp from S to C; +} diff --git a/scribble-demos/scrib/bettybook/src/bettybook/http/shortv/HttpShortC.java b/scribble-demos/scrib/bettybook/src/bettybook/http/shortv/HttpShortC.java new file mode 100644 index 000000000..c0c12b183 --- /dev/null +++ b/scribble-demos/scrib/bettybook/src/bettybook/http/shortv/HttpShortC.java @@ -0,0 +1,60 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package bettybook.http.shortv; + +import static bettybook.http.shortv.HttpShort.Http.Http.C; +import static bettybook.http.shortv.HttpShort.Http.Http.Resp; +import static bettybook.http.shortv.HttpShort.Http.Http.S; + +import org.scribble.runtime.net.SocketChannelEndpoint; +import org.scribble.runtime.session.MPSTEndpoint; +import org.scribble.runtime.util.Buf; + +import bettybook.http.shortv.HttpShort.Http.Http; +import bettybook.http.shortv.HttpShort.Http.roles.C; +import bettybook.http.shortv.HttpShort.Http.statechans.C.Http_C_1; +import bettybook.http.shortv.message.HttpShortMessageFormatter; +import bettybook.http.shortv.message.client.Req; +import bettybook.http.shortv.message.server.Resp; + +public class HttpShortC { + + public static void main(String[] args) throws Exception + { + Http http = new Http(); + try (MPSTEndpoint client = new MPSTEndpoint<>(http, C, + new HttpShortMessageFormatter())) + { + String host = "example.com"; int port = 80; String file = "/"; + //String host = "localhost"; int port = 8080; String file = "/"; + + client.request(S, SocketChannelEndpoint::new, host, port); + new HttpShortC().run(client, host, file); + } + } + + private void run(MPSTEndpoint client, String host, String file) throws Exception + { + Buf buf = new Buf<>(); + Http_C_1 c = new Http_C_1(client); + + + c.send(S, new Req(file, "1.1", host)) + .receive(S, Resp, buf); + + + System.out.println("Response:\n" + buf.val); + } +} + diff --git a/scribble-demos/scrib/bettybook/src/bettybook/http/shortv/HttpShortS.java b/scribble-demos/scrib/bettybook/src/bettybook/http/shortv/HttpShortS.java new file mode 100644 index 000000000..0ff18c669 --- /dev/null +++ b/scribble-demos/scrib/bettybook/src/bettybook/http/shortv/HttpShortS.java @@ -0,0 +1,68 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package bettybook.http.shortv; + +import static bettybook.http.shortv.HttpShort.Http.Http.C; +import static bettybook.http.shortv.HttpShort.Http.Http.Req; +import static bettybook.http.shortv.HttpShort.Http.Http.S; + +import java.io.IOException; + +import org.scribble.main.ScribRuntimeException; +import org.scribble.runtime.net.ScribServerSocket; +import org.scribble.runtime.net.SocketChannelServer; +import org.scribble.runtime.session.MPSTEndpoint; +import org.scribble.runtime.util.Buf; + +import bettybook.http.shortv.HttpShort.Http.Http; +import bettybook.http.shortv.HttpShort.Http.roles.S; +import bettybook.http.shortv.HttpShort.Http.statechans.S.Http_S_1; +import bettybook.http.shortv.HttpShort.Http.statechans.S.Http_S_2; +import bettybook.http.shortv.message.HttpShortMessageFormatter; +import bettybook.http.shortv.message.client.Req; +import bettybook.http.shortv.message.server.Resp; + +public class HttpShortS { + + public static void main(String[] args) throws IOException + { + try (ScribServerSocket ss = new SocketChannelServer(8080)) + { + while (true) + { + Http http = new Http(); + try (MPSTEndpoint server = new MPSTEndpoint<>(http, S, + new HttpShortMessageFormatter())) { + server.accept(ss, C); + + run(new Http_S_1(server)); + } + catch (IOException | ClassNotFoundException | ScribRuntimeException e) + { + e.printStackTrace(); + } + } + } + } + + private static void run(Http_S_1 s1) + throws ClassNotFoundException, ScribRuntimeException, IOException + { + Buf buf = new Buf<>(); + + Http_S_2 s2 = s1.receive(C, Req, buf); + System.out.println("Request:\n" + buf.val); + s2.send(C, new Resp("1.1", "Hello, World!")); + } +} diff --git a/scribble-demos/scrib/bettybook/src/bettybook/http/shortv/message/HttpShortMessage.java b/scribble-demos/scrib/bettybook/src/bettybook/http/shortv/message/HttpShortMessage.java new file mode 100644 index 000000000..e31d5e111 --- /dev/null +++ b/scribble-demos/scrib/bettybook/src/bettybook/http/shortv/message/HttpShortMessage.java @@ -0,0 +1,67 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package bettybook.http.shortv.message; + +import org.scribble.core.type.name.Op; +import org.scribble.runtime.message.ScribMessage; + +import bettybook.http.shortv.HttpShort.Http.Http; + +public abstract class HttpShortMessage extends ScribMessage +{ + private static final long serialVersionUID = 1L; + + public static final String GET = "GET"; + public static final String HTTP = "HTTP"; + + public static final String CRLF = "\r\n"; + + public HttpShortMessage(Op op, String m) + { + super(op, m); + } + + public String getHeadersAndBody() + { + return (this.payload.length == 0) ? "" : (String) this.payload[0]; + } + + public byte[] toBytes() + { + // FIXME: factor better with Request/Response (e.g. " " after op, terminal CRLF, etc) + return (getOpString(this.op) + getHeadersAndBody()).getBytes(HttpShortMessageFormatter.cs); // Can give "utf-8" as arg directly + } + + @Override + public String toString() + { + return new String(toBytes()); + } + + protected static String getOpString(Op op) + { + if (op.equals(Http.Req)) + { + return HttpShortMessage.GET; + } + else if (op.equals(Http.Resp)) + { + return HttpShortMessage.HTTP; + } + else + { + throw new RuntimeException("TODO: " + op); + } + } +} diff --git a/scribble-demos/scrib/bettybook/src/bettybook/http/shortv/message/HttpShortMessageFormatter.java b/scribble-demos/scrib/bettybook/src/bettybook/http/shortv/message/HttpShortMessageFormatter.java new file mode 100644 index 000000000..4964fe91f --- /dev/null +++ b/scribble-demos/scrib/bettybook/src/bettybook/http/shortv/message/HttpShortMessageFormatter.java @@ -0,0 +1,258 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package bettybook.http.shortv.message; + +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.Charset; +import java.util.Arrays; + +import org.scribble.runtime.message.ScribMessage; +import org.scribble.runtime.message.ScribMessageFormatter; + +import bettybook.http.shortv.message.client.Req; +import bettybook.http.shortv.message.server.Resp; + +public class HttpShortMessageFormatter implements ScribMessageFormatter +{ + public static final Charset cs = Charset.forName("UTF8"); + //private static CharsetDecoder cd = cs.newDecoder(); + + public HttpShortMessageFormatter() + { + + } + + @Override + public byte[] toBytes(ScribMessage m) throws IOException + { + return ((HttpShortMessage) m).toBytes(); + } + + @Override + public ScribMessage fromBytes(ByteBuffer bb) throws IOException, ClassNotFoundException + { + bb.flip(); + int rem = bb.remaining(); + if (rem < 2) + { + bb.compact(); + return null; + } + + String curr = new String(Arrays.copyOf(bb.array(), bb.remaining()), HttpShortMessageFormatter.cs); + String endOfHeaders = HttpShortMessage.CRLF + HttpShortMessage.CRLF; + if (!curr.contains(endOfHeaders)) + { + bb.compact(); + return null; + } + + if (curr.contains(Resp.CONTENT_LENGTH)) + { + int eoh = curr.indexOf(endOfHeaders); + if (eoh == -1) + { + bb.compact(); + return null; + } + String contentLenSplit = curr.substring(curr.indexOf(Resp.CONTENT_LENGTH)); + int len = Integer.parseInt(contentLenSplit.substring(Resp.CONTENT_LENGTH.length()+2, contentLenSplit.indexOf('\r')).trim()); + if (curr.length() < eoh+4) + { + bb.compact(); + return null; + } + String body = curr.substring(eoh+4); + if (body.getBytes(HttpShortMessageFormatter.cs).length < len) + { + bb.compact(); + return null; + } + byte[] bs = new byte[bb.remaining()]; // FIXME: hardcoded Response parsing based on presence of Content-Length + bb.get(bs); + bb.compact(); + return parseResponse(new String(bs, HttpShortMessageFormatter.cs)); + } + else + { + byte[] bs = new byte[bb.remaining()]; + bb.get(bs); + bb.compact(); + return parseRequest(new String(bs, HttpShortMessageFormatter.cs)); // FIXME: assuming empty-body Request if no Content-Length + } + } + + // Assumes no body + private static HttpShortMessage parseRequest(String msg) + { + String get = null; + String http = null; + String host = null; + String userA = null; + String accept = null; + String acceptL = null; + String acceptE = null; + String dnt = null; + String connection = null; + String upgradeIR = null; + + for (boolean eoh = false; !eoh; ) + { + //if (msg.startsWith(HttpMessage.CRLF + HttpMessage.CRLF)) + if (msg.startsWith(HttpShortMessage.CRLF)) // First CRLF already trimmed after last header + { + eoh = true; + //msg = msg.substring(4); + msg = msg.substring(2); + break; + } + + msg = msg.replace("\\A\\s+", ""); + int i = msg.indexOf(":"); + if (i == -1) + { + throw new RuntimeException("Shouldn't get in here: " + msg); + } + if (msg.startsWith(HttpShortMessage.GET)) // FIXME + { + int j = msg.indexOf(' '); + get = msg.substring(j+1, msg.indexOf(' ', j+1)).trim(); + j = msg.indexOf('\r'); + http = msg.substring(msg.indexOf('/')+1, j).trim(); + msg = msg.substring(j+2); + } + else + { + String header = msg.substring(0, i); + int j = msg.indexOf("\r"); + switch (header) // FIXME: duplicates not checked + { + case Req.HOST: host = msg.substring(i+1, j).trim(); break; + case Req.USER_AGENT: userA = msg.substring(i+1, j).trim(); break; + case Req.ACCEPT: accept = msg.substring(i+1, j).trim(); break; + case Req.ACCEPT_LANGUAGE: acceptL = msg.substring(i+1, j).trim(); break; + case Req.ACCEPT_ENCODING: acceptE = msg.substring(i+1, j).trim(); break; + case Req.DO_NOT_TRACK: dnt = msg.substring(i+1, j).trim(); break; + case Req.CONNECTION: connection = msg.substring(i+1, j).trim(); break; + case Req.UPGRADE_INSECURE_REQUESTS: upgradeIR = msg.substring(i+1, j).trim(); break; + default: { + //throw new RuntimeException("Cannot parse header field: " + msg.substring(0, j)); + System.err.println("Cannot parse header field, attempting to skip: " + msg.substring(0, j)); + } + } + msg = msg.substring(j+2); + } + } + if (!msg.isEmpty()) + { + throw new RuntimeException("Shouldn't get in here: " + msg); + } + return new Req(get, http, host, userA, accept, acceptL, acceptE, dnt, connection, upgradeIR); + } + + private static HttpShortMessage parseResponse(String msg) + { + String httpv = null; + String ack = null; + String date = null; + String server = null; + String strictTS = null; + String lastMod = null; + String eTag = null; + String acceptR = null; + String contentL = null; + String vary = null; + String contentT = null; + String via = null; + String body = null; + + for (boolean eoh = false; !eoh; ) + { + //if (msg.startsWith(HttpMessage.CRLF + HttpMessage.CRLF)) + if (msg.startsWith(HttpShortMessage.CRLF)) // First CRLF already trimmed after last header + { + eoh = true; + //msg = msg.substring(4); + msg = msg.substring(2); + break; + } + + msg = msg.trim(); + int i = msg.indexOf(":"); + if (i == -1) + { + throw new RuntimeException("Shouldn't get in here: " + msg); + } + if (msg.startsWith(HttpShortMessage.HTTP)) // FIXME + { + int j = msg.indexOf(' '); + httpv = msg.substring(msg.indexOf('/')+1, j); + + int k = msg.indexOf('\r'); + ack = msg.substring(j+1, k); + /*if (!ack.equals("200 OK")) + { + if (!ack.startsWith("404")) + { + throw new RuntimeException("[TODO]: " + msg); + } + } + ack = "OK"; // Hardcoded*/ + msg = msg.substring(k+2); + } + else + { + String header = msg.substring(0, i); + int j = msg.indexOf("\r"); + switch (header) + { + case Resp.DATE: date = msg.substring(i+1, j).trim(); break; + case Resp.SERVER: server = msg.substring(i+1, j).trim(); break; + case Resp.STRICT_TRANSPORT_SECURITY: strictTS = msg.substring(i+1, j).trim(); break; + case Resp.LAST_MODIFIED: lastMod = msg.substring(i+1, j).trim(); break; + case Resp.ETAG: eTag = msg.substring(i+1, j).trim(); break; + case Resp.ACCEPT_RANGES: acceptR = msg.substring(i+1, j).trim(); break; + case Resp.CONTENT_LENGTH: contentL = msg.substring(i+1, j).trim(); break; + case Resp.VARY: vary = msg.substring(i+1, j).trim(); break; + case Resp.CONTENT_TYPE: contentT = msg.substring(i+1, j).trim(); break; + case Resp.VIA: via = msg.substring(i+1, j).trim(); break; + default: + //throw new RuntimeException("Cannot parse header field: " + msg.substring(0, msg.indexOf('\r'))); + System.err.println("[Warning] Attempting to skip over response field: " + header + "\n" + msg.substring(i+1, j).trim()); + } + msg = msg.substring(j+2); + } + } + body = msg; + return new Resp(httpv, ack, date, server, strictTS, lastMod, eTag, acceptR, contentL, vary, contentT, via, body); + } + + + + // FIXME: delete + @Deprecated @Override + public void writeMessage(DataOutputStream dos, ScribMessage m) throws IOException + { + throw new RuntimeException("Shouldn't get in here: " + m); + } + + @Deprecated @Override + public ScribMessage readMessage(DataInputStream dis) throws IOException + { + throw new RuntimeException("Shouldn't get in here: "); + } +} diff --git a/scribble-demos/scrib/bettybook/src/bettybook/http/shortv/message/client/Req.java b/scribble-demos/scrib/bettybook/src/bettybook/http/shortv/message/client/Req.java new file mode 100644 index 000000000..9ec29a4b4 --- /dev/null +++ b/scribble-demos/scrib/bettybook/src/bettybook/http/shortv/message/client/Req.java @@ -0,0 +1,53 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package bettybook.http.shortv.message.client; + +import bettybook.http.shortv.HttpShort.Http.Http; +import bettybook.http.shortv.message.HttpShortMessage; + +public class Req extends HttpShortMessage { + + private static final long serialVersionUID = 1L; + + public static final String HOST = "Host"; + public static final String USER_AGENT = "User-Agent"; + public static final String ACCEPT = "Accept"; + public static final String ACCEPT_LANGUAGE = "Accept-Language"; + public static final String ACCEPT_ENCODING = "Accept-Encoding"; + public static final String DO_NOT_TRACK = "DNT"; + public static final String CONNECTION = "Connection"; + public static final String UPGRADE_INSECURE_REQUESTS = "Upgrade-Insecure-Requests"; + + public Req(String get, String http, String host, String userA, String accept, String acceptL, String acceptE, String dnt, String connection, String upgradeIR) { + super(Http.Req, getHeadersAndBody(get, http, host, userA, accept, acceptL, acceptE, dnt, connection, upgradeIR)); + } + + public Req(String get, String http, String host) { + this(get, http, host, null, null, null, null, null, null, null); + } + + protected static String getHeadersAndBody(String get, String http, String host, String userA, String accept, String acceptL, String acceptE, String dnt, String connection, String upgradeIR) { + return " " + + get + " " + HttpShortMessage.HTTP + "/" + http + HttpShortMessage.CRLF + + Req.HOST + ": " + host + HttpShortMessage.CRLF + + ((userA == null) ? "" : Req.USER_AGENT + ": " + userA + HttpShortMessage.CRLF) + + ((accept == null) ? "" : Req.ACCEPT + ": " + accept + HttpShortMessage.CRLF) + + ((acceptL == null) ? "" : Req.ACCEPT_LANGUAGE + ": " + acceptL + HttpShortMessage.CRLF) + + ((acceptE == null) ? "" : Req.ACCEPT_ENCODING + ": " + acceptE + HttpShortMessage.CRLF) + + ((dnt == null) ? "" : Req.DO_NOT_TRACK + ": " + dnt + HttpShortMessage.CRLF) + + ((connection == null) ? "" : Req.CONNECTION + ": " + connection + HttpShortMessage.CRLF) + + ((upgradeIR == null) ? "" : Req.UPGRADE_INSECURE_REQUESTS + ": " + upgradeIR + HttpShortMessage.CRLF) + + "" + HttpShortMessage.CRLF; // Empty body + } +} diff --git a/scribble-demos/scrib/bettybook/src/bettybook/http/shortv/message/server/Resp.java b/scribble-demos/scrib/bettybook/src/bettybook/http/shortv/message/server/Resp.java new file mode 100644 index 000000000..8f3778d0e --- /dev/null +++ b/scribble-demos/scrib/bettybook/src/bettybook/http/shortv/message/server/Resp.java @@ -0,0 +1,98 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package bettybook.http.shortv.message.server; + +import bettybook.http.shortv.HttpShort.Http.Http; +import bettybook.http.shortv.message.HttpShortMessage; + +public class Resp extends HttpShortMessage +{ + private static final long serialVersionUID = 1L; + + public static final String DATE = "Date"; + public static final String CONTENT_TYPE = "Content-Type"; + public static final String _404 = "404"; + public static final String _200 = "200"; + public static final String ACCEPT_RANGES = "Accept-Ranges"; + public static final String LAST_MODIFIED = "Last-Modified"; + public static final String VARY = "Vary"; + public static final String SERVER = "Server"; + public static final String STRICT_TRANSPORT_SECURITY = "Strict-Transport-Security"; + public static final String VIA = "Via"; + public static final String ETAG = "ETag"; + public static final String CONTENT_LENGTH = "Content-Length"; + + /*HTTP/1.1 200 OK + Date: Mon, 13 Jun 2016 19:42:34 GMT + Server: Apache + Strict-Transport-Security: max-age=31536000; preload; includeSubDomains + Strict-Transport-Security: max-age=31536000; preload; includeSubDomains // BUG? (Apache configuration) + Last-Modified: Thu, 14 Apr 2016 12:46:24 GMT + ETag: "74a-53071482f6e0f" + Accept-Ranges: bytes + Content-Length: 1866 + Vary: Accept-Encoding + Content-Type: text/html + Via: 1.1 www.doc.ic.ac.uk*/ + public Resp(String httpv, String ack, String date, String server, String strictTS, String lastMod, + String eTag, String acceptR, String contentL, String vary, String contentT, String via, String body) + { + super(Http.Resp, getHeadersAndBody( + httpv, ack, date, server, strictTS, lastMod, eTag, acceptR, contentL, vary, contentT, via, body)); + } + + /*public Response(String httpv, String ack, String contentL, String body) + { + super(Http.RESPONSE, getHeadersAndBody(httpv, ack, contentL, body)); + }*/ + + public Resp(String httpv, String body) + { + this(httpv, Resp._200 + " OK", null, null, null, null, null, null, Integer.toString(body.length()), null, null, null, body); + } + + // ack includes "op", e.g. 200, 404, ... + protected static String getHeadersAndBody(String httpv, String ack, String date, String server, String strictTS, String lastMod, + String eTag, String acceptR, String contentL, String vary, String contentT, String via, String body) + { + if (!ack.startsWith(Resp._200) && !ack.startsWith(Resp._404)) + { + throw new RuntimeException("[TODO]: " + ack); + } + return "/" + httpv + " " + + ack + HttpShortMessage.CRLF // Hardcoded + + ((date == null) ? "" : Resp.DATE + ": " + date + HttpShortMessage.CRLF) + + ((server == null) ? "" : Resp.SERVER + ": " + server + HttpShortMessage.CRLF) + + ((strictTS == null) ? "" : Resp.STRICT_TRANSPORT_SECURITY + ": " + strictTS + HttpShortMessage.CRLF) + + ((lastMod == null) ? "" : Resp.LAST_MODIFIED + ": " + lastMod + HttpShortMessage.CRLF) + + ((eTag == null) ? "" : Resp.ETAG + ": " + eTag + HttpShortMessage.CRLF) + + ((acceptR == null) ? "" : Resp.ACCEPT_RANGES + ": " + acceptR + HttpShortMessage.CRLF) + + Resp.CONTENT_LENGTH + ": " + contentL + HttpShortMessage.CRLF + + ((vary == null) ? "" : Resp.VARY + ": " + vary + HttpShortMessage.CRLF) + + ((contentT == null) ? "" : Resp.CONTENT_TYPE + ": " + contentT + HttpShortMessage.CRLF) + + ((via == null) ? "" : Resp.VIA + ": " + via + HttpShortMessage.CRLF) + + HttpShortMessage.CRLF // Empty line for end of headers + + body + HttpShortMessage.CRLF; + } + + /*// 404 + protected static String getHeadersAndBody(String httpv, String ack, String contentL, String body) + { + return "/" + httpv + " " + + _404 + ack + HttpMessage.CRLF // Hardcoded + + Response.CONTENT_LENGTH + ": " + contentL + HttpMessage.CRLF + + HttpMessage.CRLF // Empty line for end of headers + + body + HttpMessage.CRLF; + }*/ +} diff --git a/scribble-demos/scrib/bettybook/src/bettybook/math/rmi/RMIMath.java b/scribble-demos/scrib/bettybook/src/bettybook/math/rmi/RMIMath.java new file mode 100644 index 000000000..4a8817e82 --- /dev/null +++ b/scribble-demos/scrib/bettybook/src/bettybook/math/rmi/RMIMath.java @@ -0,0 +1,25 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package bettybook.math.rmi; + +import java.rmi.Remote; +import java.rmi.RemoteException; + +public interface RMIMath extends Remote +{ + void Val(Integer x) throws RemoteException; + void Bye() throws RemoteException; + Integer Add(Integer y) throws RemoteException; + Integer Mult(Integer y) throws RemoteException; +} diff --git a/scribble-demos/scrib/bettybook/src/bettybook/math/rmi/RMIMathC.java b/scribble-demos/scrib/bettybook/src/bettybook/math/rmi/RMIMathC.java new file mode 100644 index 000000000..bc3e50dac --- /dev/null +++ b/scribble-demos/scrib/bettybook/src/bettybook/math/rmi/RMIMathC.java @@ -0,0 +1,45 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ + +//$ java -cp scribble-demos/target/test-classes/ -Djava.security.policy=file:/C:/Users/..FIXME../github.com/scribble/scribble-java/scribble-demos/scrib/bettybook/src/bettybook/math/rmi/server.policy bettybook.math.rmi.RMIMathC + + +package bettybook.math.rmi; + +import bettybook.math.rmi.RMIMath; + +import java.rmi.registry.LocateRegistry; +import java.rmi.registry.Registry; + +public class RMIMathC +{ + public static void main(String[] args) throws Exception + { + Registry registry = LocateRegistry.getRegistry(8888); + RMIMath mathS = (RMIMath) registry.lookup("MathService"); + + int i = 5; + int res = i; + while (i > 1) + { + mathS.Val(i); + i = mathS.Add(-1); + mathS.Val(res); + res = mathS.Mult(i); + } + mathS.Bye(); + + System.out.println("Facto: " + res); + } +} diff --git a/scribble-demos/scrib/bettybook/src/bettybook/math/rmi/RMIMathS.java b/scribble-demos/scrib/bettybook/src/bettybook/math/rmi/RMIMathS.java new file mode 100644 index 000000000..0c674cd2c --- /dev/null +++ b/scribble-demos/scrib/bettybook/src/bettybook/math/rmi/RMIMathS.java @@ -0,0 +1,68 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ + +//$ java -cp scribble-demos/target/test-classes -Djava.security.policy=file:/C:/Users/..FIXME../github.com/scribble/scribble-java/scribble-demos/scrib/bettybook/src/bettybook/math/rmi/server.policy bettybook.math.rmi.RMIMathS +//$ java -cp scribble-demos/target/test-classes -Djava.rmi.server.codebase=file:/C:/cygwin/home/..FIXME../scribble-java/modules/demos/scrib/bettybook/target/classes/ -Djava.security.policy=file:/C:/cygwin/home/Raymond/code/scribble/github-rhu1/scribble-java/modules/core/src/test/scrib/demo/bettybook/math/rmi/server.policy bettybook.math.rmi.RMIMathS -- FIXME: codebase arg not working + +package bettybook.math.rmi; + +import java.rmi.RemoteException; +import java.rmi.registry.LocateRegistry; +import java.rmi.registry.Registry; +import java.rmi.server.UnicastRemoteObject; + +public class RMIMathS implements RMIMath +{ + private int x; + + public void Val(Integer x) throws RemoteException + { + this.x = x; + } + + public void Bye() throws RemoteException + { + + } + + public Integer Add(Integer y) throws RemoteException + { + return this.x + y; + } + + public Integer Mult(Integer y) throws RemoteException + { + return this.x * y; + } + + public static void main(String[] args) throws Exception + { + Registry registry = LocateRegistry.createRegistry(8888); + + RMIMath stub = (RMIMath) UnicastRemoteObject.exportObject(new RMIMathS(), 0); + registry.rebind("MathService", stub); + + System.out.println("RMI Math Server running."); + } +} + + + + + + //System.setProperty("java.security.policy","file:/C:/cygwin64/home/.../scribble-java/scribble-demos/scrib/bettybook/src/bettybook/math/rmi/server.policy"); + //if (System.getSecurityManager() == null) { System.setSecurityManager(new SecurityManager()); } + + /*-Djava.security.policy=file:/C:/Users/..../github.com/scribble/scribble-java/scribble-demos/scrib/bettybook/src/bettybook/math/rmi/server.policy + Registry registry = LocateRegistry.getRegistry(8888);*/ diff --git a/scribble-demos/scrib/bettybook/src/bettybook/math/rmi/server.policy b/scribble-demos/scrib/bettybook/src/bettybook/math/rmi/server.policy new file mode 100644 index 000000000..d12f69de5 --- /dev/null +++ b/scribble-demos/scrib/bettybook/src/bettybook/math/rmi/server.policy @@ -0,0 +1,3 @@ +grant codeBase "file:/C:/cygwin64/home/rhu/code/eclipse/scribble/github.com/rhu1/scribble-java/scribble-core/target/classes/" { + permission java.security.AllPermission; +}; diff --git a/scribble-demos/scrib/bettybook/src/bettybook/math/scrib/Math.scr b/scribble-demos/scrib/bettybook/src/bettybook/math/scrib/Math.scr new file mode 100644 index 000000000..f63c2a817 --- /dev/null +++ b/scribble-demos/scrib/bettybook/src/bettybook/math/scrib/Math.scr @@ -0,0 +1,33 @@ +//$ ./scribblec.sh -ip scribble-demos/scrib/bettybook/src -d scribble-demos/scrib/bettybook/src scribble-demos/scrib/bettybook/src/bettybook/math/scrib/Math.scr -api MathService C +//$ javadoc -cp scribble-core/target/classes:scribble-runtime/target/classes:scribble-demos/scrib/bettybook/src -subpackages bettybook.math.scrib.Math.MathService -d scribble-demos/scrib/bettybook/javadoc/math + + +module bettybook.math.scrib.Math; + +data "java.lang.Integer" from "rt.jar" as Int; + + +// N.B. calling this Math will clash with java.lang.Math +global protocol MathService(role C, role S) +{ + choice at C + { + Val(Int) from C to S; + choice at C + { + Add(Int) from C to S; + Sum(Int) from S to C; + } + or + { + Mult(Int) from C to S; + Prod(Int) from S to C; + } + do MathService(C, S); + } + or + { + //Val(Int) from C to S; + Bye() from C to S; + } +} diff --git a/scribble-demos/scrib/bettybook/src/bettybook/math/scrib/MathC.java b/scribble-demos/scrib/bettybook/src/bettybook/math/scrib/MathC.java new file mode 100644 index 000000000..872078e5e --- /dev/null +++ b/scribble-demos/scrib/bettybook/src/bettybook/math/scrib/MathC.java @@ -0,0 +1,119 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package bettybook.math.scrib; + +import static bettybook.math.scrib.Math.MathService.MathService.Add; +import static bettybook.math.scrib.Math.MathService.MathService.Bye; +import static bettybook.math.scrib.Math.MathService.MathService.C; +import static bettybook.math.scrib.Math.MathService.MathService.Mult; +import static bettybook.math.scrib.Math.MathService.MathService.Prod; +import static bettybook.math.scrib.Math.MathService.MathService.S; +import static bettybook.math.scrib.Math.MathService.MathService.Sum; +import static bettybook.math.scrib.Math.MathService.MathService.Val; + +import org.scribble.runtime.message.ObjectStreamFormatter; +import org.scribble.runtime.net.SocketChannelEndpoint; +import org.scribble.runtime.session.MPSTEndpoint; +import org.scribble.runtime.util.Buf; + +import bettybook.math.scrib.Math.MathService.MathService; +import bettybook.math.scrib.Math.MathService.roles.C; +import bettybook.math.scrib.Math.MathService.statechans.C.EndSocket; +import bettybook.math.scrib.Math.MathService.statechans.C.MathService_C_1; + +public class MathC +{ + public MathC() throws Exception + { + facto(5); + fibo(10); + } + + private int facto(int n) throws Exception + { + Buf i = new Buf<>(n), res = new Buf<>(i.val); + MathService sess = new MathService(); + try (MPSTEndpoint se = new MPSTEndpoint<>(sess, C, + new ObjectStreamFormatter())) { + se.request(S, SocketChannelEndpoint::new, "localhost", 8888); + + MathService_C_1 s1 = new MathService_C_1(se); + + //facto(s1, i, res); + facto(s1, res).send(S, Bye); + + System.out.println("Facto " + n + ": " + res.val); + + return res.val; + } + } + + private static void facto(MathService_C_1 s1, Buf i, Buf res) throws Exception + { + while (i.val > 1) + { + s1 = sub1(s1, i).send(S, Val, res.val).send(S, Mult, i.val).receive(S, Prod, res); + } + s1.send(S, Bye); + } + + // Pre: b.val >= 1 + private static MathService_C_1 facto(MathService_C_1 s1, Buf b) throws Exception + { + if (b.val == 1) + { + return s1; + } + Buf tmp = new Buf<>(b.val); + return facto(sub1(s1, tmp), tmp).send(S, Val, b.val).send(S, Mult, tmp.val).receive(S, Prod, b); + } + + private int fibo(int i) throws Exception + { + Buf i1 = new Buf<>(0); + Buf i2 = new Buf<>(1); + MathService sess = new MathService(); + try (MPSTEndpoint se = new MPSTEndpoint<>(sess, C, new ObjectStreamFormatter())) + { + se.request(S, SocketChannelEndpoint::new, "localhost", 8888); + + fibo(new MathService_C_1(se), i1, i2, new Buf<>(i)); + + System.out.println("Fibo " + i + ": " + i1.val); + + return i1.val; + } + } + + // Pre: i >= 0 + // Post: i1.val is the i-th Fibonacci number + private static EndSocket fibo(MathService_C_1 s1, Buf i1, Buf i2, Buf i) throws Exception + { + return (i.val > 0) + ? fibo( + sub1(s1, i).send(S, Val, i1.val).send(S, Add, i1.val=i2.val).receive(S, Sum, i2), + i1, i2, i) + : s1.send(S, Bye); + } + + private static MathService_C_1 sub1(MathService_C_1 s1, Buf b) throws Exception + { + return s1.send(S, Val, b.val).send(S, Add, -1).receive(S, Sum, b); + } + + public static void main(String[] args) throws Exception + { + new MathC(); + } +} diff --git a/scribble-demos/scrib/bettybook/src/bettybook/math/scrib/MathS1.java b/scribble-demos/scrib/bettybook/src/bettybook/math/scrib/MathS1.java new file mode 100644 index 000000000..eabcd55b8 --- /dev/null +++ b/scribble-demos/scrib/bettybook/src/bettybook/math/scrib/MathS1.java @@ -0,0 +1,85 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package bettybook.math.scrib; + +import static bettybook.math.scrib.Math.MathService.MathService.Add; +import static bettybook.math.scrib.Math.MathService.MathService.Bye; +import static bettybook.math.scrib.Math.MathService.MathService.C; +import static bettybook.math.scrib.Math.MathService.MathService.Mult; +import static bettybook.math.scrib.Math.MathService.MathService.Prod; +import static bettybook.math.scrib.Math.MathService.MathService.S; +import static bettybook.math.scrib.Math.MathService.MathService.Sum; +import static bettybook.math.scrib.Math.MathService.MathService.Val; + +import org.scribble.runtime.message.ObjectStreamFormatter; +import org.scribble.runtime.net.ScribServerSocket; +import org.scribble.runtime.net.SocketChannelServer; +import org.scribble.runtime.session.MPSTEndpoint; +import org.scribble.runtime.util.Buf; + +import bettybook.math.scrib.Math.MathService.MathService; +import bettybook.math.scrib.Math.MathService.roles.S; +import bettybook.math.scrib.Math.MathService.statechans.S.MathService_S_1; +import bettybook.math.scrib.Math.MathService.statechans.S.MathService_S_1_Cases; +import bettybook.math.scrib.Math.MathService.statechans.S.MathService_S_2_Cases; + +public class MathS1 +{ + public MathS1() throws Exception + { + run(); + } + + private void run() throws Exception + { + try (ScribServerSocket ss = new SocketChannelServer(8888)) + { + while (true) + { + MathService sess = new MathService(); + try (MPSTEndpoint se = new MPSTEndpoint<>(sess, S, + new ObjectStreamFormatter())) { + se.accept(ss, C); + Buf b1 = new Buf<>(); + Buf b2 = new Buf<>(); + + MathService_S_1 s1 = new MathService_S_1(se); + Loop: while (true) + { + MathService_S_1_Cases c1 = s1.branch(C); + switch (c1.op) + { + case Bye: c1.receive(Bye); break Loop; + case Val: + { + MathService_S_2_Cases c2 = c1.receive(Val, b1).branch(C); + switch (c2.op) + { + case Add: s1 = c2.receive(Add, b2).send(C, Sum, b1.val + b2.val); break; + case Mult: s1 = c2.receive(Mult, b2).send(C, Prod, b1.val * b2.val); break; + } + break; + } + } + } + } + } + } + } + + public static void main(String[] args) throws Exception + { + new MathS1(); + } +} diff --git a/scribble-demos/scrib/bettybook/src/bettybook/math/scrib/MathS2.java b/scribble-demos/scrib/bettybook/src/bettybook/math/scrib/MathS2.java new file mode 100644 index 000000000..f670c01e1 --- /dev/null +++ b/scribble-demos/scrib/bettybook/src/bettybook/math/scrib/MathS2.java @@ -0,0 +1,98 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package bettybook.math.scrib; + +import static bettybook.math.scrib.Math.MathService.MathService.C; +import static bettybook.math.scrib.Math.MathService.MathService.Prod; +import static bettybook.math.scrib.Math.MathService.MathService.S; +import static bettybook.math.scrib.Math.MathService.MathService.Sum; + +import java.io.IOException; + +import org.scribble.main.ScribRuntimeException; +import org.scribble.runtime.message.ObjectStreamFormatter; +import org.scribble.runtime.net.ScribServerSocket; +import org.scribble.runtime.net.SocketChannelServer; +import org.scribble.runtime.session.MPSTEndpoint; +import org.scribble.runtime.util.Buf; + +import bettybook.math.scrib.Math.MathService.MathService; +import bettybook.math.scrib.Math.MathService.ops.Add; +import bettybook.math.scrib.Math.MathService.ops.Bye; +import bettybook.math.scrib.Math.MathService.ops.Mult; +import bettybook.math.scrib.Math.MathService.ops.Val; +import bettybook.math.scrib.Math.MathService.roles.S; +import bettybook.math.scrib.Math.MathService.statechans.S.EndSocket; +import bettybook.math.scrib.Math.MathService.statechans.S.MathService_S_1; +import bettybook.math.scrib.Math.MathService.statechans.S.MathService_S_1_Handler; +import bettybook.math.scrib.Math.MathService.statechans.S.MathService_S_2; +import bettybook.math.scrib.Math.MathService.statechans.S.MathService_S_2_Handler; +import bettybook.math.scrib.Math.MathService.statechans.S.MathService_S_3; +import bettybook.math.scrib.Math.MathService.statechans.S.MathService_S_4; + +public class MathS2 +{ + public static void main(String[] args) throws Exception + { + try (ScribServerSocket ss = new SocketChannelServer(8888)) + { + while (true) + { + MathService sess = new MathService(); + try (MPSTEndpoint se = new MPSTEndpoint<>(sess, S, + new ObjectStreamFormatter())) { + se.accept(ss, C); + + MathService_S_1 s1 = new MathService_S_1(se); + s1.branch(C, new MathSHandler()); + } + } + } + } +} + +// FIXME: add generic session-state object to handler methods +class MathSHandler implements MathService_S_1_Handler, MathService_S_2_Handler +{ + private Buf b1; + + @Override + public void receive(MathService_S_2 s2, Val op, Buf b1) + throws ScribRuntimeException, IOException, ClassNotFoundException + { + this.b1 = b1; + s2.branch(C, this); + } + + @Override + public void receive(EndSocket end, Bye op) throws ScribRuntimeException, + IOException, ClassNotFoundException + { + + } + + @Override + public void receive(MathService_S_3 s3, Add op, Buf b2) + throws ScribRuntimeException, IOException, ClassNotFoundException + { + s3.send(C, Sum, this.b1.val + b2.val).branch(C, this); + } + + @Override + public void receive(MathService_S_4 s4, Mult op, Buf b2) + throws ScribRuntimeException, IOException, ClassNotFoundException + { + s4.send(C, Prod, this.b1.val * b2.val).branch(C, this); + } +} diff --git a/scribble-demos/scrib/bettybook/src/bettybook/math/sock/SockMathC.java b/scribble-demos/scrib/bettybook/src/bettybook/math/sock/SockMathC.java new file mode 100644 index 000000000..1dcc547f4 --- /dev/null +++ b/scribble-demos/scrib/bettybook/src/bettybook/math/sock/SockMathC.java @@ -0,0 +1,113 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package bettybook.math.sock; + +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.Serializable; +import java.net.Socket; + +public class SockMathC +{ + public static void main(String[] args) throws Exception + { + try (Socket s = new Socket("localhost", 8888); + ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream()); + ObjectInputStream ois = new ObjectInputStream(s.getInputStream())) + { + int i = 5, res = i; + while (i > 1) + { + oos.writeObject(new Val(i)); + oos.writeObject(new Add(-1)); + oos.flush(); + i = ((Sum) ois.readObject()).val; + oos.writeObject(new Val(res)); + oos.writeObject(new Mult(i)); + oos.flush(); + res = ((Prod) ois.readObject()).val; + } + oos.writeObject(new Bye()); + oos.flush(); + + System.out.println("Facto: " + res); + } + } +} + +abstract class NumMsg implements Serializable +{ + private static final long serialVersionUID = 1L; + public int val; + + public NumMsg(int val) + { + this.val = val; + } +} + +class Val extends NumMsg +{ + private static final long serialVersionUID = 1L; + + public Val(int x) + { + super(x); + } +} + +class Add extends NumMsg +{ + private static final long serialVersionUID = 1L; + + public Add(int val) + { + super(val); + } +} + +class Sum extends NumMsg +{ + private static final long serialVersionUID = 1L; + + public Sum(int val) + { + super(val); + } +} + +class Mult extends NumMsg +{ + private static final long serialVersionUID = 1L; + + public Mult(int val) + { + super(val); + } +} + +class Prod extends NumMsg +{ + private static final long serialVersionUID = 1L; + + public Prod(int val) + { + super(val); + } +} + +class Bye implements Serializable +{ + private static final long serialVersionUID = 1L; +} diff --git a/scribble-demos/scrib/bettybook/src/bettybook/math/sock/SockMathS.java b/scribble-demos/scrib/bettybook/src/bettybook/math/sock/SockMathS.java new file mode 100644 index 000000000..7a756ed07 --- /dev/null +++ b/scribble-demos/scrib/bettybook/src/bettybook/math/sock/SockMathS.java @@ -0,0 +1,75 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package bettybook.math.sock; + +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.net.ServerSocket; +import java.net.Socket; + +public class SockMathS +{ + public static void main(String[] args) throws Exception + { + try (ServerSocket ss = new ServerSocket(8888)) + { + while (true) + { + try (Socket s = ss.accept()) + { + try (ObjectInputStream ois = new ObjectInputStream(s.getInputStream()); + ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream())) + { + Loop: while (true) + { + Object msg = ois.readObject(); + if (msg instanceof Val) + { + int x = ((Val) msg).val; + msg = ois.readObject(); + if (msg instanceof Add) + { + int y = ((Add) msg).val; + oos.writeObject(new Sum(x + y)); + } + else if (msg instanceof Mult) + { + int y = ((Mult) msg).val; + oos.writeObject(new Prod(x * y)); + } + else + { + throw new Exception("Bad message: " + msg.getClass()); + } + oos.flush(); + } + else if (msg instanceof Bye) + { + break Loop; + } + else + { + throw new Exception("Bad message: " + msg.getClass()); + } + } + } + } + catch (Exception x) + { + x.printStackTrace(); + } + } + } + } +} diff --git a/scribble-demos/scrib/coco/src/coco/fibo/Fibo.scr b/scribble-demos/scrib/coco/src/coco/fibo/Fibo.scr new file mode 100644 index 000000000..9786773ee --- /dev/null +++ b/scribble-demos/scrib/coco/src/coco/fibo/Fibo.scr @@ -0,0 +1,25 @@ +//$ ./scribblec.sh -ip scribble-demos/scrib/coco/src -d scribble-demos/scrib/coco/src scribble-demos/scrib/coco/src/coco/fibo/Fibo.scr -api Fibonacci A +//$ javadoc -cp scribble-core/target/classes:scribble-runtime/target/classes:scribble-demos/scrib/coco/src scribble-demos/scrib/coco/src/coco/fibo/*.java -subpackages coco.fibo.Fibo.Fibonacci -d scribble-demos/scrib/coco/javadoc/fibo + +module coco.fibo.Fibo; + + +data "java.lang.Long" from "rt.jar" as Long; + + +global protocol Fibonacci(role A, role B) +{ + rec Fib + { + choice at A + { + fibonacci(Long) from A to B; + fibonacci(Long) from B to A; + continue Fib; + } + or + { + stop() from A to B; + } + } +} diff --git a/scribble-demos/scrib/coco/src/coco/fibo/FiboA.java b/scribble-demos/scrib/coco/src/coco/fibo/FiboA.java new file mode 100644 index 000000000..27fd0338c --- /dev/null +++ b/scribble-demos/scrib/coco/src/coco/fibo/FiboA.java @@ -0,0 +1,101 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package coco.fibo; + +import static coco.fibo.Fibo.Fibonacci.Fibonacci.A; +import static coco.fibo.Fibo.Fibonacci.Fibonacci.B; +import static coco.fibo.Fibo.Fibonacci.Fibonacci.fibonacci; +import static coco.fibo.Fibo.Fibonacci.Fibonacci.stop; + +import org.scribble.runtime.message.ObjectStreamFormatter; +import org.scribble.runtime.net.SocketChannelEndpoint; +import org.scribble.runtime.session.MPSTEndpoint; +import org.scribble.runtime.util.Buf; + +import coco.fibo.Fibo.Fibonacci.Fibonacci; +import coco.fibo.Fibo.Fibonacci.roles.A; +import coco.fibo.Fibo.Fibonacci.statechans.A.EndSocket; +import coco.fibo.Fibo.Fibonacci.statechans.A.Fibonacci_A_1; +import coco.fibo.Fibo.Fibonacci.statechans.A.ioifaces.In_B_fibonacci_Long; +import coco.fibo.Fibo.Fibonacci.statechans.A.ioifaces.Out_B_fibonacci_Long; +import coco.fibo.Fibo.Fibonacci.statechans.A.ioifaces.Out_B_stop; +import coco.fibo.Fibo.Fibonacci.statechans.A.ioifaces.Succ_In_B_fibonacci_Long; +import coco.fibo.Fibo.Fibonacci.statechans.A.ioifaces.Succ_Out_B_fibonacci_Long; + +public class FiboA extends Thread +{ + private final Fibonacci fib; + private Buf b = new Buf<>(0L); + + public FiboA(Fibonacci fib) + { + this.fib = fib; + } + + @Override + public void run() + { + int n = 19; + try (MPSTEndpoint se = new MPSTEndpoint<>(this.fib, A, + new ObjectStreamFormatter())) + { + se.request(B, SocketChannelEndpoint::new, "localhost", 8888); + run(new Fibonacci_A_1(se), n); // 4184 + System.out.println("A #" + n + ": " + this.b.val); + } + catch (Exception x) + { + x.printStackTrace(); + } + } + + private EndSocket run(Fibonacci_A_1 s, int todo) throws Exception + { + return run1(s, todo); + } + + private + < + //*/ + T1 extends + Out_B_fibonacci_Long & Out_B_stop // Action I/f's + & Succ_In_B_fibonacci_Long, // Successor I/f's + T2 extends + In_B_fibonacci_Long + & Succ_Out_B_fibonacci_Long //, E extends Succ_Out_B_stop + /*/ + T1 extends Select_A_B_fibonacci_Long__B_stop, + T2 extends Receive_A_B_fibonacci_Long + //*/ + > + EndSocket run1(T1 s, int todo) throws Exception + { + return (todo > 0) + ? run1( + next(this.b.val, + s.send(B, fibonacci, this.b.val) + .receive(B, fibonacci, this.b), todo), + todo - 2) + : s.send(Fibonacci.B, stop); + } + + //private Fibonacci_A_1 next(long prev, Fibonacci_A_1 s, int todo) + private S next(long prev, S s, int todo) + { + //System.out.println("A: " + prev); + if (todo > 1) + this.b.val += prev; + return s; + } +} \ No newline at end of file diff --git a/scribble-demos/scrib/coco/src/coco/fibo/FiboB.java b/scribble-demos/scrib/coco/src/coco/fibo/FiboB.java new file mode 100644 index 000000000..139d9b216 --- /dev/null +++ b/scribble-demos/scrib/coco/src/coco/fibo/FiboB.java @@ -0,0 +1,84 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package coco.fibo; + +import static coco.fibo.Fibo.Fibonacci.Fibonacci.A; +import static coco.fibo.Fibo.Fibonacci.Fibonacci.B; +import static coco.fibo.Fibo.Fibonacci.Fibonacci.fibonacci; +import static coco.fibo.Fibo.Fibonacci.Fibonacci.stop; + +import org.scribble.runtime.message.ObjectStreamFormatter; +import org.scribble.runtime.net.ScribServerSocket; +import org.scribble.runtime.net.SocketChannelServer; +import org.scribble.runtime.session.MPSTEndpoint; +import org.scribble.runtime.util.Buf; + +import coco.fibo.Fibo.Fibonacci.Fibonacci; +import coco.fibo.Fibo.Fibonacci.roles.B; +import coco.fibo.Fibo.Fibonacci.statechans.B.EndSocket; +import coco.fibo.Fibo.Fibonacci.statechans.B.Fibonacci_B_1; +import coco.fibo.Fibo.Fibonacci.statechans.B.Fibonacci_B_1_Cases; + +public class FiboB extends Thread +{ + private final Fibonacci fib; + private Buf b = new Buf<>(1L); + + public FiboB(Fibonacci fib) + { + this.fib = fib; + } + + @Override + public void run() + { + try ( + ScribServerSocket ss = new SocketChannelServer(8888); + MPSTEndpoint se = new MPSTEndpoint<>(this.fib, B, + new ObjectStreamFormatter())) + { + se.accept(ss, A); + run(new Fibonacci_B_1(se)); + } + catch (Exception x) + { + x.printStackTrace(); + } + } + + private EndSocket run(Fibonacci_B_1 s) throws Exception + { + /* + ... s.branch(A); + switch (...) // Value-switch + { + ... + } + } +} +/*/ + Fibonacci_B_1_Cases c = s.branch(A); + switch (c.op) + { + case fibonacci: + long prev = this.b.val; + return run(c.receive(fibonacci, this.b).send(A, fibonacci, this.b.val += prev)); + case stop: + return c.receive(stop); + default: + throw new RuntimeException("Will never get here"); + } + } +} +//*/ diff --git a/scribble-demos/scrib/coco/src/coco/fibo/FiboBHandler.java b/scribble-demos/scrib/coco/src/coco/fibo/FiboBHandler.java new file mode 100644 index 000000000..c46a00027 --- /dev/null +++ b/scribble-demos/scrib/coco/src/coco/fibo/FiboBHandler.java @@ -0,0 +1,81 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package coco.fibo; + +import static coco.fibo.Fibo.Fibonacci.Fibonacci.A; +import static coco.fibo.Fibo.Fibonacci.Fibonacci.B; +import static coco.fibo.Fibo.Fibonacci.Fibonacci.fibonacci; + +import java.io.IOException; + +import org.scribble.main.ScribRuntimeException; +import org.scribble.runtime.message.ObjectStreamFormatter; +import org.scribble.runtime.net.ScribServerSocket; +import org.scribble.runtime.net.SocketChannelServer; +import org.scribble.runtime.session.MPSTEndpoint; +import org.scribble.runtime.util.Buf; + +import coco.fibo.Fibo.Fibonacci.Fibonacci; +import coco.fibo.Fibo.Fibonacci.ops.fibonacci; +import coco.fibo.Fibo.Fibonacci.ops.stop; +import coco.fibo.Fibo.Fibonacci.roles.B; +import coco.fibo.Fibo.Fibonacci.statechans.B.EndSocket; +import coco.fibo.Fibo.Fibonacci.statechans.B.Fibonacci_B_1; +import coco.fibo.Fibo.Fibonacci.statechans.B.Fibonacci_B_1_Handler; +import coco.fibo.Fibo.Fibonacci.statechans.B.Fibonacci_B_2; + +public class FiboBHandler extends Thread implements Fibonacci_B_1_Handler +{ + private final Fibonacci fib; + private long x = 1; + + public FiboBHandler(Fibonacci fib) + { + this.fib = fib; + } + + @Override + public void run() + { + try ( + ScribServerSocket ss = new SocketChannelServer(8888); + MPSTEndpoint se = new MPSTEndpoint<>(this.fib, B, + new ObjectStreamFormatter())) + { + se.accept(ss, A); + new Fibonacci_B_1(se).branch(A, this); + } + catch (Exception x) + { + x.printStackTrace(); + } + } +/* +} +/*/ + @Override + public void receive(Fibonacci_B_2 s2, fibonacci op, Buf arg1) + throws ScribRuntimeException, IOException, ClassNotFoundException + { + s2.send(A, fibonacci, (this.x += arg1.val)).branch(A, this); + } + + @Override + public void receive(EndSocket end, stop op) + throws ScribRuntimeException, IOException, ClassNotFoundException + { + //System.out.println("B done: " + this.x); + } +} +//*/ diff --git a/scribble-demos/scrib/coco/src/coco/fibo/FiboMain.java b/scribble-demos/scrib/coco/src/coco/fibo/FiboMain.java new file mode 100644 index 000000000..a4f2db47e --- /dev/null +++ b/scribble-demos/scrib/coco/src/coco/fibo/FiboMain.java @@ -0,0 +1,27 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package coco.fibo; + +import coco.fibo.Fibo.Fibonacci.Fibonacci; + +public class FiboMain +{ + public static void main(String[] args) throws Exception + { + Fibonacci fib = new Fibonacci(); + //new MyB(fib).start(); + new FiboBHandler(fib).start(); + new FiboA(fib).start(); + } +} diff --git a/scribble-demos/scrib/coco/src/coco/smtp/MySmtpC.java b/scribble-demos/scrib/coco/src/coco/smtp/MySmtpC.java new file mode 100644 index 000000000..8039da897 --- /dev/null +++ b/scribble-demos/scrib/coco/src/coco/smtp/MySmtpC.java @@ -0,0 +1,110 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +//$ java -cp modules/cli/target/classes/';'modules/core/target/classes';'modules/parser/target/classes';'modules/demos/target/classes/ coco.smtp.Client + +package coco.smtp; + +import static coco.smtp.Smtp.Smtp.Smtp.C; +import static coco.smtp.Smtp.Smtp.Smtp.S; +import static coco.smtp.Smtp.Smtp.Smtp._220; + +import org.scribble.runtime.net.SSLSocketChannelWrapper; +import org.scribble.runtime.net.SocketChannelEndpoint; +import org.scribble.runtime.session.MPSTEndpoint; +import org.scribble.runtime.statechans.LinearSocket; +import org.scribble.runtime.util.Buf; + +import coco.smtp.Smtp.Smtp.Smtp; +import coco.smtp.Smtp.Smtp.roles.C; +import coco.smtp.Smtp.Smtp.statechans.C.Smtp_C_1; +import coco.smtp.Smtp.Smtp.statechans.C.ioifaces.Out_S_Ehlo; +import coco.smtp.Smtp.Smtp.statechans.C.ioifaces.Receive_C_S_220; +import coco.smtp.Smtp.Smtp.statechans.C.ioifaces.Select_C_S_Ehlo; +import coco.smtp.Smtp.Smtp.statechans.C.ioifaces.Select_C_S_Quit; +import coco.smtp.Smtp.Smtp.statechans.C.ioifaces.Select_C_S_StartTls; +import coco.smtp.Smtp.Smtp.statechans.C.ioifaces.Succ_In_S_250; +import coco.smtp.message.SmtpMessageFormatter; +import coco.smtp.message.client.Quit; +import coco.smtp.message.client.StartTls; + +public class MySmtpC +{ + public MySmtpC() throws Exception + { + run(); + } + + public static void main(String[] args) throws Exception + { + new MySmtpC(); + } + + public void run() throws Exception + { + String host = "smtp.cc.ic.ac.uk"; + int port = 25; + + Smtp smtp = new Smtp(); + try (MPSTEndpoint se = new MPSTEndpoint<>(smtp, C, + new SmtpMessageFormatter())) { + se.request(S, SocketChannelEndpoint::new, host, port); + + Smtp_C_1 s1 = new Smtp_C_1(se); + doInit( + LinearSocket.wrapClient( + doInit(s1.receive(S, _220, new Buf<>())) + .to(Select_C_S_StartTls.cast) // Run-time cast + .send(S, new StartTls()) + .to(Receive_C_S_220.cast) // Safe cast + .receive(S, _220, new Buf<>()) + .to(Select_C_S_Ehlo.cast) // Safe cast + , S, SSLSocketChannelWrapper::new) + ) + .to(Select_C_S_Quit.cast) // Run-time cast + .send(S, new Quit()); + } + } + + //* + private Succ_In_S_250 doInit(Out_S_Ehlo s) throws Exception + { + // TODO: ... + return null; + } + /*/ + private Succ_In_S_250 doInit(Select_C_S_Ehlo s) throws Exception + { + Branch_C_S_250__S_250d b = + s.send(S, new Ehlo("test")) + .to(Branch_C_S_250__S_250d.cast); // Safe cast + Buf<_250> b1 = new Buf<>(); + Buf<_250d> b2 = new Buf<>(); + while (true) + { + Case_C_S_250__S_250d c = b.branch(S); + switch (c.getOp()) + { + case _250: + return Client1.printlnBuf(c.receive(S, _250, b1), b1); + case _250d: + b = Client1.printBuf( + c.receive(S, _250d, b2) + .to(Branch_C_S_250__S_250d.cast) // Safe cast + , b2); + break; + } + } + } + //*/ +} diff --git a/scribble-demos/scrib/coco/src/coco/smtp/Smtp.scr b/scribble-demos/scrib/coco/src/coco/smtp/Smtp.scr new file mode 100644 index 000000000..46d9c3311 --- /dev/null +++ b/scribble-demos/scrib/coco/src/coco/smtp/Smtp.scr @@ -0,0 +1,68 @@ +//$ ./scribblec.sh -ip scribble-demos/scrib/coco/src -d scribble-demos/scrib/coco/src scribble-demos/scrib/coco/src/coco/smtp/Smtp.scr -api Smtp C +//$ javadoc -cp scribble-core/target/classes:scribble-runtime/target/classes:scribble-demos/scrib/coco/src scribble-demos/scrib/coco/src/coco/smtp/*.java -subpackages coco.smtp.Smtp.Smtp -d scribble-demos/scrib/coco/javadoc/smtp + +//http://sandbox.kidstrythisathome.com/erdos/ + + +module coco.smtp.Smtp; + +sig "coco.smtp.message.server._220" + from "coco/smtp/message/server/_220.java" as 220; +sig "coco.smtp.message.server._250" + from "coco/smtp/message/server/_250.java" as 250; +sig "coco.smtp.message.server._250d" + from "coco/smtp/message/server/_250d.java" as 250d; + +sig "coco.smtp.message.client.Ehlo" + from "coco/smtp/message/client/Ehlo.java" as Ehlo; +sig "coco.smtp.message.client.StartTls" + from "coco/smtp/message/client/StartTls.java" as StartTls; +sig "coco.smtp.message.client.Quit" + from "coco/smtp/message/client/Quit.java" as Quit; + +global protocol Smtp(role C, role S) +{ + 220 from S to C; //* + do Init(C, S); + do StartTls(C, S); + do Init(C, S); + Quit from C to S; +} +/*/ + choice at C + { + do Init(C, S); + do StartTls(C, S); + do Init(C, S); + Quit from C to S; + } + or + { + Quit from C to S; + } +} +//*/ + +aux global protocol Init(role C, role S) +{ + Ehlo from C to S; + rec X + { + choice at S + { + 250d from S to C; + continue X; + } + or + { + 250 from S to C; + } + } + // or { Quit from C to S; } // FIXME: apigen +} + +aux global protocol StartTls(role C, role S) +{ + StartTls from C to S; + 220 from S to C; +} diff --git a/scribble-demos/scrib/coco/src/coco/smtp/SmtpC1.java b/scribble-demos/scrib/coco/src/coco/smtp/SmtpC1.java new file mode 100644 index 000000000..6ef39d541 --- /dev/null +++ b/scribble-demos/scrib/coco/src/coco/smtp/SmtpC1.java @@ -0,0 +1,137 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +//$ java -cp modules/cli/target/classes/';'modules/core/target/classes';'modules/parser/target/classes';'modules/demos/target/classes/ coco.smtp.Client1 + + +package coco.smtp; + +import static coco.smtp.Smtp.Smtp.Smtp.C; +import static coco.smtp.Smtp.Smtp.Smtp.S; +import static coco.smtp.Smtp.Smtp.Smtp._220; +import static coco.smtp.Smtp.Smtp.Smtp._250; +import static coco.smtp.Smtp.Smtp.Smtp._250d; + +import org.scribble.runtime.net.SSLSocketChannelWrapper; +import org.scribble.runtime.net.SocketChannelEndpoint; +import org.scribble.runtime.session.MPSTEndpoint; +import org.scribble.runtime.statechans.LinearSocket; +import org.scribble.runtime.util.Buf; + +import coco.smtp.Smtp.Smtp.Smtp; +import coco.smtp.Smtp.Smtp.roles.C; +import coco.smtp.Smtp.Smtp.statechans.C.Smtp_C_1; +import coco.smtp.Smtp.Smtp.statechans.C.Smtp_C_2; +import coco.smtp.Smtp.Smtp.statechans.C.Smtp_C_3; +import coco.smtp.Smtp.Smtp.statechans.C.Smtp_C_3_Cases; +import coco.smtp.Smtp.Smtp.statechans.C.Smtp_C_4; +import coco.smtp.Smtp.Smtp.statechans.C.Smtp_C_6; +import coco.smtp.Smtp.Smtp.statechans.C.Smtp_C_7; +import coco.smtp.Smtp.Smtp.statechans.C.Smtp_C_7_Cases; +import coco.smtp.Smtp.Smtp.statechans.C.Smtp_C_8; +import coco.smtp.message.SmtpMessageFormatter; +import coco.smtp.message.client.Ehlo; +import coco.smtp.message.client.Quit; +import coco.smtp.message.client.StartTls; +import coco.smtp.message.server._250; +import coco.smtp.message.server._250d; + +public class SmtpC1 +{ + public SmtpC1() throws Exception + { + run(); + } + + public static void main(String[] args) throws Exception + { + new SmtpC1(); + } + + public void run() throws Exception + { + String host = "...smtp server..."; + int port = 25; + + Smtp smtp = new Smtp(); + try (MPSTEndpoint se = new MPSTEndpoint<>(smtp, C, + new SmtpMessageFormatter())) { + se.request(S, SocketChannelEndpoint::new, host, port); + + Smtp_C_1 s1 = new Smtp_C_1(se); + doInit( + doStartTls( + doInit(s1.receive(S, _220, new Buf<>())) + ) + ) + .send(S, new Quit()); + } + } + + private Smtp_C_4 doInit(Smtp_C_2 s2) throws Exception + { + Smtp_C_3 s3 = s2.send(S, new Ehlo("test")); + Buf<_250> b1 = new Buf<>(); + Buf<_250d> b2 = new Buf<>(); + while (true) + { + Smtp_C_3_Cases c = s3.branch(S); + switch (c.op) + { + case _250: + return printlnBuf(c.receive(S, _250, b1), b1); + case _250d: + s3 = printBuf(c.receive(S, _250d, b2), b2); + break; + } + } + } + + private Smtp_C_8 doInit(Smtp_C_6 s6) throws Exception + { + Smtp_C_7 s7 = s6.send(S, new Ehlo("test")); + Buf<_250> b1 = new Buf<>(); + Buf<_250d> b2 = new Buf<>(); + while (true) + { + Smtp_C_7_Cases c = s7.branch(S); + switch (c.op) + { + case _250: + return printlnBuf(c.receive(S, _250, b1), b1); + case _250d: + s7 = printBuf(c.receive(S, _250d, b2), b2); + break; + } + } + } + + private Smtp_C_6 doStartTls(Smtp_C_4 s4) throws Exception + { + return LinearSocket.wrapClient( + s4.send(S, new StartTls()).receive(S, _220, new Buf<>()), S, SSLSocketChannelWrapper::new + ); + } + + public static > S printBuf(S s, B b) + { + System.out.print(b.val); + return s; + } + + public static > S printlnBuf(S s, B b) + { + System.out.println(b.val); + return s; + } +} diff --git a/scribble-demos/scrib/coco/src/coco/smtp/SmtpC2.java b/scribble-demos/scrib/coco/src/coco/smtp/SmtpC2.java new file mode 100644 index 000000000..ceb0727e0 --- /dev/null +++ b/scribble-demos/scrib/coco/src/coco/smtp/SmtpC2.java @@ -0,0 +1,153 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +//$ java -cp modules/cli/target/classes/';'modules/core/target/classes';'modules/parser/target/classes';'modules/demos/target/classes/ coco.smtp.Client2 + + +package coco.smtp; + +import static coco.smtp.Smtp.Smtp.Smtp.S; +import static coco.smtp.Smtp.Smtp.Smtp._220; +import static coco.smtp.Smtp.Smtp.Smtp._250; +import static coco.smtp.Smtp.Smtp.Smtp._250d; + +import org.scribble.runtime.net.SSLSocketChannelWrapper; +import org.scribble.runtime.net.SocketChannelEndpoint; +import org.scribble.runtime.session.MPSTEndpoint; +import org.scribble.runtime.statechans.LinearSocket; +import org.scribble.runtime.util.Buf; + +import coco.smtp.Smtp.Smtp.Smtp; +import coco.smtp.Smtp.Smtp.roles.C; +import coco.smtp.Smtp.Smtp.statechans.C.Smtp_C_1; +import coco.smtp.Smtp.Smtp.statechans.C.Smtp_C_1_Future; +import coco.smtp.Smtp.Smtp.statechans.C.ioifaces.Branch_C_S_250__S_250d; +import coco.smtp.Smtp.Smtp.statechans.C.ioifaces.Case_C_S_250__S_250d; +import coco.smtp.Smtp.Smtp.statechans.C.ioifaces.Receive_C_S_220; +import coco.smtp.Smtp.Smtp.statechans.C.ioifaces.Select_C_S_Ehlo; +import coco.smtp.Smtp.Smtp.statechans.C.ioifaces.Select_C_S_Quit; +import coco.smtp.Smtp.Smtp.statechans.C.ioifaces.Select_C_S_StartTls; +import coco.smtp.Smtp.Smtp.statechans.C.ioifaces.Succ_In_S_250; +import coco.smtp.message.SmtpMessageFormatter; +import coco.smtp.message.client.Ehlo; +import coco.smtp.message.client.Quit; +import coco.smtp.message.client.StartTls; +import coco.smtp.message.server._250; +import coco.smtp.message.server._250d; + +public class SmtpC2 +{ + public SmtpC2() throws Exception + { + run(); + } + + public static void main(String[] args) throws Exception + { + new SmtpC2(); + } + + public void run() throws Exception + { + String host = "...smtp server..."; + int port = 25; + + Smtp smtp = new Smtp(); + try (MPSTEndpoint se = new MPSTEndpoint<>(smtp, Smtp.C, + new SmtpMessageFormatter())) { + se.request(Smtp.S, SocketChannelEndpoint::new, host, port); + + Buf b1 = new Buf<>(); + Smtp_C_1 s1 = new Smtp_C_1(se); + //Buf b2 = new Buf<>(); // only supported by concrete state chans + doInit( + LinearSocket.wrapClient( + doInit(s1.async(S, _220, b1)) + .to(Select_C_S_StartTls.cast).send(S, new StartTls()) // Run-time cast + .to(Receive_C_S_220.cast) // Safe cast + //.receive(S, _220, new Buf<>()) + .async(S, _220) + .to(Select_C_S_Ehlo.cast) // Safe cast + , S, SSLSocketChannelWrapper::new) + ) + .to(Select_C_S_Quit.cast).send(S, new Quit()); // Run-time cast + + //b1.val.sync(); + //System.out.println("b1: " + b1.val.sync().msg); + //System.out.println("b2: " + b2.val.sync().msg); + } + } + + //private > Succ_In_S_250 doInit(S s) throws Exception + //private Succ_In_S_250 doInit(Select_C_S_Ehlo__S_Quit s) throws Exception + private Succ_In_S_250 doInit(Select_C_S_Ehlo s) throws Exception + { + /* + ... + } + /*/ + Branch_C_S_250__S_250d b = + s.send(S, new Ehlo("test")) + .to(Branch_C_S_250__S_250d.cast); // Safe cast + Buf<_250> b1 = new Buf<>(); + Buf<_250d> b2 = new Buf<>(); + while (true) + { + Case_C_S_250__S_250d c = b.branch(S); + switch (c.getOp()) + { + case _250: + return SmtpC1.printlnBuf(c.receive(S, _250, b1), b1); + case _250d: + b = SmtpC1.printBuf( + c.receive(S, _250d, b2) + .to(Branch_C_S_250__S_250d.cast) // Safe cast + , b2); + break; + } + } + } + //*/ +} + + + + + /*private Succ_In_S_250 doInitiation(Receive_C_S_220 s) throws Exception + { + Branch_C_S_250d__S_250 b = + s.receive(S, _220, new Buf<>()).to(Select_C_S_Ehlo.cast) + .send(S, new Ehlo("test")) + .to(Branch_C_S_250d__S_250.cast); // Safe cast + Buf<_250> b1 = new Buf<>(); + Buf<_250_> b2 = new Buf<>(); + while (true) + { + Case_C_S_250d__S_250 c = b.branch(S); + switch (c.getOp()) + { + case _250d: + { + b = c.receive(S, _250d, b2).to(Branch_C_S_250d__S_250.cast); + System.out.print(b2.val); + break; + } + case _250: + { + Succ_In_S_250 succ = c.receive(S, _250, b1); + System.out.println(b1.val); + return succ; + } + } + } + }*/ \ No newline at end of file diff --git a/scribble-demos/scrib/coco/src/coco/smtp/SmtpC3.java b/scribble-demos/scrib/coco/src/coco/smtp/SmtpC3.java new file mode 100644 index 000000000..5fb4d44ce --- /dev/null +++ b/scribble-demos/scrib/coco/src/coco/smtp/SmtpC3.java @@ -0,0 +1,104 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +//$ java -cp modules/cli/target/classes/';'modules/core/target/classes';'modules/parser/target/classes';'modules/demos/target/classes/ coco.smtp.Client3 + + +package coco.smtp; + +import static coco.smtp.Smtp.Smtp.Smtp.C; +import static coco.smtp.Smtp.Smtp.Smtp.S; +import static coco.smtp.Smtp.Smtp.Smtp._220; +import static coco.smtp.Smtp.Smtp.Smtp._250; +import static coco.smtp.Smtp.Smtp.Smtp._250d; + +import org.scribble.runtime.net.SSLSocketChannelWrapper; +import org.scribble.runtime.net.SocketChannelEndpoint; +import org.scribble.runtime.session.MPSTEndpoint; +import org.scribble.runtime.statechans.LinearSocket; +import org.scribble.runtime.util.Buf; + +import coco.smtp.Smtp.Smtp.Smtp; +import coco.smtp.Smtp.Smtp.roles.C; +import coco.smtp.Smtp.Smtp.statechans.C.Smtp_C_1; +import coco.smtp.Smtp.Smtp.statechans.C.Smtp_C_1_Future; +import coco.smtp.Smtp.Smtp.statechans.C.ioifaces.Branch_C_S_250__S_250d; +import coco.smtp.Smtp.Smtp.statechans.C.ioifaces.Case_C_S_250__S_250d; +import coco.smtp.Smtp.Smtp.statechans.C.ioifaces.Select_C_S_Ehlo; +import coco.smtp.Smtp.Smtp.statechans.C.ioifaces.Succ_In_S_250; +import coco.smtp.message.SmtpMessageFormatter; +import coco.smtp.message.client.Ehlo; +import coco.smtp.message.client.Quit; +import coco.smtp.message.client.StartTls; +import coco.smtp.message.server._250; +import coco.smtp.message.server._250d; + +// "No casts" version -- via generic inference +public class SmtpC3 +{ + public SmtpC3() throws Exception + { + run(); + } + + public static void main(String[] args) throws Exception + { + new SmtpC3(); + } + + public void run() throws Exception + { + String host = "...smtp server..."; + int port = 25; + + Smtp smtp = new Smtp(); + try (MPSTEndpoint se = new MPSTEndpoint<>(smtp, C, new SmtpMessageFormatter())) + { + se.request(S, SocketChannelEndpoint::new, host, port); + + Smtp_C_1 s1 = new Smtp_C_1(se); + Buf b = new Buf<>(); + doInit( + LinearSocket.wrapClient( + doInit(s1.async(S, _220, b)) + .send(S, new StartTls()) + .async(S, _220) + , S, SSLSocketChannelWrapper::new) + ) + .send(S, new Quit()); + + //System.out.println("b1: " + b.val.sync().msg); + } + } + + private , T2 extends Succ_In_S_250> + //T2 doInit(Select_C_S_Ehlo__S_Quit s) throws Exception + T2 doInit(Select_C_S_Ehlo s) throws Exception + { + Branch_C_S_250__S_250d b = s.send(S, new Ehlo("test")); + Buf<_250> b1 = new Buf<>(); + Buf<_250d> b2 = new Buf<>(); + while (true) + { + Case_C_S_250__S_250d c = b.branch(S); + switch (c.getOp()) + { + case _250d: + b = SmtpC1.printBuf(c.receive(S, _250d, b2), b2); + break; + case _250: + return SmtpC1.printlnBuf(c.receive(S, _250, b1), b1); + } + } + } +} diff --git a/scribble-demos/scrib/coco/src/coco/smtp/message/SmtpMessage.java b/scribble-demos/scrib/coco/src/coco/smtp/message/SmtpMessage.java new file mode 100644 index 000000000..ff7499bd9 --- /dev/null +++ b/scribble-demos/scrib/coco/src/coco/smtp/message/SmtpMessage.java @@ -0,0 +1,86 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package coco.smtp.message; + +import org.scribble.core.type.name.Op; +import org.scribble.runtime.message.ScribMessage; +import org.scribble.util.Caller; + +import coco.smtp.Smtp.Smtp.Smtp; + +public abstract class SmtpMessage extends ScribMessage +{ + public static final String _220 = "220"; + public static final String _250 = "250"; + public static final String _250_ = "250-"; + public static final String _235 = "235"; + public static final String _535 = "535"; + public static final String _501 = "501"; + public static final String _354 = "354"; + + public static final String EHLO = "ehlo"; + public static final String STARTTLS = "starttls"; + public static final String AUTH = "auth plain"; + public static final String MAIL = "mail from:"; + public static final String RCPT = "rcpt to:"; + public static final String SUBJECT = "subject:"; + public static final String DATA = "data"; + public static final String QUIT = "quit"; + + public static final String DATA_LINE = ""; + public static final String END_OF_DATA = ""; + + private static final long serialVersionUID = 1L; + + protected static final String CRLF = "\r\n"; + + public SmtpMessage(Op op) + { + super(op); + } + + public SmtpMessage(Op op, String body) + { + super(op, body); + } + + public String getBody() + { + return (this.payload.length == 0) ? "" : (String) this.payload[0]; + } + + public byte[] toBytes() + { + byte[] bs = (getOpString(this.op) + " " + getBody() + SmtpMessage.CRLF).getBytes(SmtpMessageFormatter.cs); // Can give "utf-8" as arg directly + return bs; + } + + @Override + public String toString() + { + return new String(toBytes()); + } + + protected static String getOpString(Op op) + { + return + (op.equals(Smtp._220)) ? SmtpMessage._220 + : (op.equals(Smtp._250)) ? SmtpMessage._250 + : (op.equals(Smtp._250d)) ? SmtpMessage._250_ + : (op.equals(Smtp.Ehlo)) ? SmtpMessage.EHLO + : (op.equals(Smtp.StartTls)) ? SmtpMessage.STARTTLS + : (op.equals(Smtp.Quit)) ? SmtpMessage.QUIT + : new Caller().call(() -> { throw new RuntimeException("TODO: " + op); }); + } +} diff --git a/scribble-demos/scrib/coco/src/coco/smtp/message/SmtpMessageFormatter.java b/scribble-demos/scrib/coco/src/coco/smtp/message/SmtpMessageFormatter.java new file mode 100644 index 000000000..cd010038f --- /dev/null +++ b/scribble-demos/scrib/coco/src/coco/smtp/message/SmtpMessageFormatter.java @@ -0,0 +1,446 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package coco.smtp.message; + +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.Charset; + +import org.scribble.runtime.message.ScribMessage; +import org.scribble.runtime.message.ScribMessageFormatter; + +import coco.smtp.message.server._220; +import coco.smtp.message.server._250; +import coco.smtp.message.server._250d; + +// Currently supports only client-side reading, not server-side +public class SmtpMessageFormatter implements ScribMessageFormatter +{ + //.. fix formatting + //.. try ssl wrapper + //.. add connection (transport) actions + + public static Charset cs = Charset.forName("UTF8"); + //private static CharsetDecoder cd = cs.newDecoder(); + + public SmtpMessageFormatter() + { + + } + + @Override + public byte[] toBytes(ScribMessage m) throws IOException + { + return ((SmtpMessage) m).toBytes(); + } + + @Override + public ScribMessage fromBytes(ByteBuffer bb) throws IOException, ClassNotFoundException + { + bb.flip(); + //byte[] bs = new byte[2]; + int rem = bb.remaining(); + if (rem < 2) + { + bb.compact(); + return null; + } + + int pos = bb.position(); + String front = new String(new byte[] { bb.get(pos), bb.get(pos + 1) }, SmtpMessageFormatter.cs); + if (front.equals(SmtpMessage.CRLF)) + { + throw new RuntimeException("TODO: "); + } + + if (rem < pos + 4) + { + bb.compact(); + return null; + } + front += new String(new byte[] { bb.get(pos + 2), bb.get(pos + 3) }, SmtpMessageFormatter.cs); + int code = isStatusCode(front); + if (code > -1) + { + String body = readLine(bb, pos + 4).trim(); // Whitespace already built into the message classes + bb.compact(); + if (body == null) + { + return null; + } + switch (code) + { + case 220: return new _220(body); + case 250: + { + if (front.charAt(3) == '-') + { + return new _250d(body); + } + return new _250(body); + } + /*case 235: return new _235(body); + case 535: return new _535(body); + case 501: return new _501(body); + case 354: return new _354(body);*/ + default: throw new RuntimeException("Unknown status code " + code + ": " + body); + } + } + /*else if (front.startsWith(HttpMessage.GET)) // TODO: server-side (EHLO, STARTTLS, etc) + { + }*/ + else + { + // TODO: server-side (MAIL FROM:, RCPT TO:, etc) + String line = front + readLine(bb, pos + 4); + bb.compact(); + /*if (line == null) // deadcode + { + return null; + }*/ + throw new RuntimeException("Cannot parse message: " + line); + } + } + + private static String readLine(ByteBuffer bb, int i) throws IOException + { + StringBuilder sb = new StringBuilder(); + for (int limit = bb.limit(); i <= limit; ) + { + char c = (char) bb.get(i++); + sb.append(c); + if (c == '\r') + { + c = (char) bb.get(i++); + sb.append(c); + if (c == '\n') + { + bb.position(i); + return sb.substring(0, sb.length() - 2).toString(); + } + } + } + return null; + } + + // Duplicated from HttpMessageFormatter // FIXME: factor out + private int isStatusCode(String front) + { + String code = ""; + for (int i = 0; i < 4; i++) + { + //char c = (char) bs[i]; + char c = front.charAt(i); + if (i < 3) + { + if (c < '0' || c > '9') + { + return -1; + } + code += c; + } + else + { + if (c != ' ' && c != '-') // HACK: hypen + { + return -1; + } + } + } + return Integer.parseInt(code); + } + + /*private static String readWord(ByteBuffer bb, int i) throws IOException + { + StringBuilder sb = new StringBuilder(); + for (int limit = bb.limit(); i <= limit; ) + { + char c = (char) bb.get(i); + if (c == ' ') + { + bb.position(i); + return sb.toString(); + } + sb.append(c); + } + return null; + }*/ + + /* // Pre: flipped ready for reading + @Override + public SmtpMessage readMessage(DataInputStream dis) throws IOException + { + String header = getHeader(dis); + switch (header) + { + // FIXME: factor out text constants with Session constants? + case "220 ": + { + return new _220(getBody(dis)); + } + case "235 ": + { + return new _235(getBody(dis)); + } + case "250-": + { + return new _250_(getBody(dis)); + } + case "250 ": + { + return new _250(getBody(dis)); + } + case "354 ": + { + return new _354(getBody(dis)); + } + case "501 ": + { + return new _501(getBody(dis)); + } + case "535 ": + { + return new _535(getBody(dis)); + } + default: + { + throw new RuntimeException("Unknown header: " + header); + } + } + } + + // *4* char headers (3 digits, dash or space) + private String getHeader(DataInputStream dis) throws IOException + { + readMinimumBytes(dis, 4); + + int limit = bb.limit(); + bb.limit(4); + String header = cd.decode(bb).toString(); // updates bb position + bb.limit(limit); + bb.compact(); + bb.flip(); + return header; + } + + // Reads up to \r\n inclusive; doesn't return the \r\n + private String getBody(DataInputStream dis) throws IOException + { + int min = 2; + readMinimumBytes(dis, min); // Min should be more? + while (true) + { + String all = cd.decode(bb).toString(); // updates bb position + if (all.contains("\n")) // FIXME: didn't check exactly \r\n + { + int i = all.indexOf("\n"); + String body = all.substring(0, i - 1); + bb.position(i + 1); // \r\n -- ASCII 1-to-1 byte-char index + bb.compact(); + bb.flip(); + return body; + } + bb.rewind(); + readMinimumBytes(dis, ++min); // FIXME: buffered readLine would be more efficient + } + } + + // FIXME: min should mean min fresh (i.e. not including bb cached -- there currently is no cache: is.available doesn't work for SSLSocket, always returns 0) + private void readMinimumBytes(DataInputStream dis, int min) throws IOException + { + for (int remaining = bb.remaining(); remaining < min; remaining = bb.remaining()) + { + bb.compact(); + bb.put((byte) dis.read()); // FIXME: check for buffer overflow + bb.flip(); + } + }*/ + + @Override + public void writeMessage(DataOutputStream dos, ScribMessage m) throws IOException + { + dos.write(((SmtpMessage) m).toBytes()); + dos.flush(); + } + + @Override + public SmtpMessage readMessage(DataInputStream dis) throws IOException + { + byte[] bs = new byte[2]; + dis.readFully(bs); + String front = new String(bs, SmtpMessageFormatter.cs); + if (front.equals(SmtpMessage.CRLF)) + { + throw new RuntimeException("TODO: "); + } + bs = new byte[2]; + dis.readFully(bs); + front += new String(bs, SmtpMessageFormatter.cs); + int code = isStatusCode(front); + if (code > -1) + { + String body = readLine(dis).trim(); // Whitespace already built into the message classes + switch (code) + { + case 220: return new _220(body); + case 250: + { + if (front.charAt(3) == '-') + { + return new _250d(body); + } + return new _250(body); + } + /*case 235: return new _235(body); + case 535: return new _535(body); + case 501: return new _501(body); + case 354: return new _354(body);*/ + default: throw new RuntimeException("Unknown status code: " + code); + } + } + /*else if (front.startsWith(HttpMessage.GET)) + { + }*/ + else + { + String line = front + readLine(dis); + throw new RuntimeException("Cannot parse message: " + line); + } + } + + private static String readLine(DataInputStream dis) throws IOException + { + StringBuilder sb = new StringBuilder(); + for (; true; ) + { + char c = (char) dis.read(); // readChar is not the same + sb.append(c); + if (c == '\r') + { + c = (char) dis.read(); + sb.append(c); + if (c == '\n') + { + return sb.substring(0, sb.length() - 2).toString(); + } + } + } + } + + /*private static String readWord(DataInputStream dis) throws IOException + { + StringBuilder sb = new StringBuilder(); + for (; true; ) + { + char c = (char) dis.read(); + if (c == ' ') + { + return sb.toString(); + } + sb.append(c); + } + }*/ + + /* // Pre: flipped ready for reading + @Override + public SmtpMessage readMessage(DataInputStream dis) throws IOException + { + String header = getHeader(dis); + switch (header) + { + // FIXME: factor out text constants with Session constants? + case "220 ": + { + return new _220(getBody(dis)); + } + case "235 ": + { + return new _235(getBody(dis)); + } + case "250-": + { + return new _250_(getBody(dis)); + } + case "250 ": + { + return new _250(getBody(dis)); + } + case "354 ": + { + return new _354(getBody(dis)); + } + case "501 ": + { + return new _501(getBody(dis)); + } + case "535 ": + { + return new _535(getBody(dis)); + } + default: + { + throw new RuntimeException("Unknown header: " + header); + } + } + } + + // *4* char headers (3 digits, dash or space) + private String getHeader(DataInputStream dis) throws IOException + { + readMinimumBytes(dis, 4); + + int limit = bb.limit(); + bb.limit(4); + String header = cd.decode(bb).toString(); // updates bb position + bb.limit(limit); + bb.compact(); + bb.flip(); + return header; + } + + // Reads up to \r\n inclusive; doesn't return the \r\n + private String getBody(DataInputStream dis) throws IOException + { + int min = 2; + readMinimumBytes(dis, min); // Min should be more? + while (true) + { + String all = cd.decode(bb).toString(); // updates bb position + if (all.contains("\n")) // FIXME: didn't check exactly \r\n + { + int i = all.indexOf("\n"); + String body = all.substring(0, i - 1); + bb.position(i + 1); // \r\n -- ASCII 1-to-1 byte-char index + bb.compact(); + bb.flip(); + return body; + } + bb.rewind(); + readMinimumBytes(dis, ++min); // FIXME: buffered readLine would be more efficient + } + } + + // FIXME: min should mean min fresh (i.e. not including bb cached -- there currently is no cache: is.available doesn't work for SSLSocket, always returns 0) + private void readMinimumBytes(DataInputStream dis, int min) throws IOException + { + for (int remaining = bb.remaining(); remaining < min; remaining = bb.remaining()) + { + bb.compact(); + bb.put((byte) dis.read()); // FIXME: check for buffer overflow + bb.flip(); + } + }*/ +} diff --git a/scribble-demos/scrib/coco/src/coco/smtp/message/client/Ehlo.java b/scribble-demos/scrib/coco/src/coco/smtp/message/client/Ehlo.java new file mode 100644 index 000000000..13b1cd279 --- /dev/null +++ b/scribble-demos/scrib/coco/src/coco/smtp/message/client/Ehlo.java @@ -0,0 +1,32 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package coco.smtp.message.client; + +import coco.smtp.Smtp.Smtp.Smtp; +import coco.smtp.message.SmtpMessage; + +public class Ehlo extends SmtpMessage +{ + private static final long serialVersionUID = 1L; + + public Ehlo() + { + super(Smtp.Ehlo); + } + + public Ehlo(String body) + { + super(Smtp.Ehlo, body); + } +} diff --git a/scribble-demos/scrib/coco/src/coco/smtp/message/client/Quit.java b/scribble-demos/scrib/coco/src/coco/smtp/message/client/Quit.java new file mode 100644 index 000000000..63e0dde10 --- /dev/null +++ b/scribble-demos/scrib/coco/src/coco/smtp/message/client/Quit.java @@ -0,0 +1,27 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package coco.smtp.message.client; + +import coco.smtp.Smtp.Smtp.Smtp; +import coco.smtp.message.SmtpMessage; + +public class Quit extends SmtpMessage +{ + private static final long serialVersionUID = 1L; + + public Quit() + { + super(Smtp.Quit); + } +} diff --git a/scribble-demos/scrib/coco/src/coco/smtp/message/client/StartTls.java b/scribble-demos/scrib/coco/src/coco/smtp/message/client/StartTls.java new file mode 100644 index 000000000..2e1688fc1 --- /dev/null +++ b/scribble-demos/scrib/coco/src/coco/smtp/message/client/StartTls.java @@ -0,0 +1,27 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package coco.smtp.message.client; + +import coco.smtp.Smtp.Smtp.Smtp; +import coco.smtp.message.SmtpMessage; + +public class StartTls extends SmtpMessage +{ + private static final long serialVersionUID = 1L; + + public StartTls() + { + super(Smtp.StartTls); + } +} diff --git a/scribble-demos/scrib/coco/src/coco/smtp/message/server/_220.java b/scribble-demos/scrib/coco/src/coco/smtp/message/server/_220.java new file mode 100644 index 000000000..fedec067e --- /dev/null +++ b/scribble-demos/scrib/coco/src/coco/smtp/message/server/_220.java @@ -0,0 +1,38 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package coco.smtp.message.server; + +import coco.smtp.Smtp.Smtp.Smtp; +import coco.smtp.message.SmtpMessage; + +public class _220 extends SmtpMessage +{ + private static final long serialVersionUID = 1L; + + public _220() + { + super(Smtp._220); + } + + public _220(String body) + { + super(Smtp._220, body); + } + + /*@Override + public Operator getOperator() + { + return Smtp._220; + }*/ +} diff --git a/scribble-demos/scrib/coco/src/coco/smtp/message/server/_250.java b/scribble-demos/scrib/coco/src/coco/smtp/message/server/_250.java new file mode 100644 index 000000000..c121479c0 --- /dev/null +++ b/scribble-demos/scrib/coco/src/coco/smtp/message/server/_250.java @@ -0,0 +1,32 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package coco.smtp.message.server; + +import coco.smtp.Smtp.Smtp.Smtp; +import coco.smtp.message.SmtpMessage; + +public class _250 extends SmtpMessage +{ + private static final long serialVersionUID = 1L; + + public _250() + { + super(Smtp._250); + } + + public _250(String body) + { + super(Smtp._250, body); + } +} diff --git a/scribble-demos/scrib/coco/src/coco/smtp/message/server/_250d.java b/scribble-demos/scrib/coco/src/coco/smtp/message/server/_250d.java new file mode 100644 index 000000000..651c9b072 --- /dev/null +++ b/scribble-demos/scrib/coco/src/coco/smtp/message/server/_250d.java @@ -0,0 +1,40 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package coco.smtp.message.server; + +import coco.smtp.Smtp.Smtp.Smtp; +import coco.smtp.message.SmtpMessage; +import coco.smtp.message.SmtpMessageFormatter; + +public class _250d extends SmtpMessage +{ + private static final long serialVersionUID = 1L; + + public _250d() + { + super(Smtp._250d); + } + + public _250d(String body) + { + super(Smtp._250d, body); + } + + @Override + public byte[] toBytes() + { + // No space after op + return (getOpString(this.op) + getBody() + SmtpMessage.CRLF).getBytes(SmtpMessageFormatter.cs); + } +} diff --git a/scribble-demos/scrib/fase16/src/fase16/adder/Adder.scr b/scribble-demos/scrib/fase16/src/fase16/adder/Adder.scr new file mode 100644 index 000000000..2abbcbe52 --- /dev/null +++ b/scribble-demos/scrib/fase16/src/fase16/adder/Adder.scr @@ -0,0 +1,24 @@ +//$ ./scribblec.sh -ip scribble-demos/scrib/fase16/src -d scribble-demos/scrib/fase16/src scribble-demos/scrib/fase16/src/fase16/adder/Adder.scr -api Adder C +//$ javadoc -cp scribble-core/target/classes:scribble-runtime/target/classes:scribble-demos/scrib/fase16/src/ scribble-demos/scrib/fase16/src/fase16/adder/Adder/Adder/*.java -subpackages fase16.adder.Adder.Adder -d scribble-demos/scrib/fase16/javadoc/adder + + +module fase16.adder.Adder; + + +data "java.lang.Integer" from "rt.jar" as Integer; + + +global protocol Adder(role C, role S) +{ + choice at C + { + Add(Integer, Integer) from C to S; + Res(Integer) from S to C; + do Adder(C, S); + } + or + { + Bye() from C to S; + Bye() from S to C; + } +} diff --git a/scribble-demos/scrib/fase16/src/fase16/adder/AdderC.java b/scribble-demos/scrib/fase16/src/fase16/adder/AdderC.java new file mode 100644 index 000000000..7bf12f0d1 --- /dev/null +++ b/scribble-demos/scrib/fase16/src/fase16/adder/AdderC.java @@ -0,0 +1,98 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package fase16.adder; + +import static fase16.adder.Adder.Adder.Adder.Add; +import static fase16.adder.Adder.Adder.Adder.Bye; +import static fase16.adder.Adder.Adder.Adder.C; +import static fase16.adder.Adder.Adder.Adder.Res; +import static fase16.adder.Adder.Adder.Adder.S; + +import org.scribble.runtime.message.ObjectStreamFormatter; +import org.scribble.runtime.net.SocketChannelEndpoint; +import org.scribble.runtime.session.MPSTEndpoint; +import org.scribble.runtime.util.Buf; + +import fase16.adder.Adder.Adder.Adder; +import fase16.adder.Adder.Adder.roles.C; +import fase16.adder.Adder.Adder.statechans.C.Adder_C_1; +import fase16.adder.Adder.Adder.statechans.C.Adder_C_3; + +public class AdderC +{ + private static final int N = 10; + + public static void main(String[] args) throws Exception + { + //adder(); + fib(); + } + + private static void adder() throws Exception + { + Adder adder = new Adder(); + try (MPSTEndpoint se = new MPSTEndpoint<>(adder, C, + new ObjectStreamFormatter())) { + se.request(S, SocketChannelEndpoint::new, "localhost", 8888); + + Adder_C_1 s1 = new Adder_C_1(se); + + + + Buf i = new Buf<>(1); + //* + for (int j = 0; j < N; j++) + { + s1 = s1.send(S, Add, i.val, i.val).receive(S, Res, i); + } + s1.send(S, Bye).receive(S, Bye); + + + + + /*/ + s1.send(S, Add, i.val, i.val) + .receive(S, Res, i) + .send(S, Add, i.val, i.val) + .receive(S, Res, i) + //... + .send(S, Bye).receive(S, Bye); + //*/ + + System.out.println("C: " + i.val); + } + } + + private static void fib() throws Exception + { + Adder adder = new Adder(); + try (MPSTEndpoint se = new MPSTEndpoint<>(adder, C, new ObjectStreamFormatter())) + { + se.request(S, SocketChannelEndpoint::new, "localhost", 8888); + + Adder_C_1 s1 = new Adder_C_1(se); + Buf i = new Buf<>(0); + fib(s1, i, new Buf(1), 0).receive(S, Bye); + + System.out.println("Fib: " + i.val); + } + } + + private static Adder_C_3 fib(Adder_C_1 s1, Buf i1, Buf i2, int i) throws Exception + { + return (i < N) + ? fib(s1.send(S, Add, i1.val, i1.val=i2.val).receive(S, Res, i2), i1, i2, i+1) + : s1.send(S, Bye); + } +} diff --git a/scribble-demos/scrib/fase16/src/fase16/adder/AdderS.java b/scribble-demos/scrib/fase16/src/fase16/adder/AdderS.java new file mode 100644 index 000000000..5ba75ebb3 --- /dev/null +++ b/scribble-demos/scrib/fase16/src/fase16/adder/AdderS.java @@ -0,0 +1,80 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package fase16.adder; + +import static fase16.adder.Adder.Adder.Adder.Add; +import static fase16.adder.Adder.Adder.Adder.Bye; +import static fase16.adder.Adder.Adder.Adder.C; +import static fase16.adder.Adder.Adder.Adder.Res; +import static fase16.adder.Adder.Adder.Adder.S; + +import java.io.IOException; + +import org.scribble.main.ScribRuntimeException; +import org.scribble.runtime.message.ObjectStreamFormatter; +import org.scribble.runtime.net.ScribServerSocket; +import org.scribble.runtime.net.SocketChannelServer; +import org.scribble.runtime.session.MPSTEndpoint; +import org.scribble.runtime.util.Buf; + +import fase16.adder.Adder.Adder.Adder; +import fase16.adder.Adder.Adder.roles.S; +import fase16.adder.Adder.Adder.statechans.S.Adder_S_1; +import fase16.adder.Adder.Adder.statechans.S.Adder_S_1_Cases; +import fase16.adder.Adder.Adder.statechans.S.Adder_S_3; + + +public class AdderS +{ + public static void main(String[] args) throws Exception + { + try (ScribServerSocket ss = new SocketChannelServer(8888)) + { + Buf i1 = new Buf<>(); + Buf i2 = new Buf<>(); + + while (true) + { + Adder adder = new Adder(); + try (MPSTEndpoint se = new MPSTEndpoint<>(adder, S, + new ObjectStreamFormatter())) { + se.accept(ss, C); + + add(new Adder_S_1(se), i1, i2).send(C, Bye); + } + catch (ScribRuntimeException | IOException | ClassNotFoundException e) + { + e.printStackTrace(); + } + } + } + } + + private static Adder_S_3 add(Adder_S_1 s1, Buf i1, Buf i2) throws Exception + { + Adder_S_1_Cases cases = s1.branch(C); + switch (cases.op) + { + case Add: + return add( + cases.receive(Add, i1, i2) + .send(C, Res, i1.val+i2.val) + , i1, i2); + case Bye: + return cases.receive(Bye); + default: + throw new RuntimeException("Will never get here."); + } + } +} diff --git a/scribble-demos/scrib/fase16/src/fase16/adder/MyAdderC.java b/scribble-demos/scrib/fase16/src/fase16/adder/MyAdderC.java new file mode 100644 index 000000000..2e413a086 --- /dev/null +++ b/scribble-demos/scrib/fase16/src/fase16/adder/MyAdderC.java @@ -0,0 +1,63 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package fase16.adder; + +import static fase16.adder.Adder.Adder.Adder.Add; +import static fase16.adder.Adder.Adder.Adder.Bye; +import static fase16.adder.Adder.Adder.Adder.C; +import static fase16.adder.Adder.Adder.Adder.Res; +import static fase16.adder.Adder.Adder.Adder.S; + +import org.scribble.runtime.message.ObjectStreamFormatter; +import org.scribble.runtime.net.SocketChannelEndpoint; +import org.scribble.runtime.session.MPSTEndpoint; +import org.scribble.runtime.util.Buf; + +import fase16.adder.Adder.Adder.Adder; +import fase16.adder.Adder.Adder.roles.C; +import fase16.adder.Adder.Adder.statechans.C.Adder_C_1; +import fase16.adder.Adder.Adder.statechans.C.Adder_C_3; + +public class MyAdderC +{ + public static void main(String[] args) throws Exception + { + Adder adder = new Adder(); + try (MPSTEndpoint se = new MPSTEndpoint<>(adder, C, + new ObjectStreamFormatter())) + { + se.request(S, SocketChannelEndpoint::new, "localhost", 8888); + + + Buf i = new Buf<>(); + + Adder_C_1 c1 = new Adder_C_1(se); + + for (int j = 0; j<3; j++) + { + c1 = c1.send(S, Add, 1, 2).receive(S, Res, i); + } + c1.send(S, Bye).receive(S, Bye); + + } + } + + private static final int N = 10; + + private static Adder_C_3 fib(Adder_C_1 s1, Buf i1, Buf i2, + int i) throws Exception + { + return null; + } +} diff --git a/scribble-demos/scrib/fase16/src/fase16/smtp/Smtp.scr b/scribble-demos/scrib/fase16/src/fase16/smtp/Smtp.scr new file mode 100644 index 000000000..653424a96 --- /dev/null +++ b/scribble-demos/scrib/fase16/src/fase16/smtp/Smtp.scr @@ -0,0 +1,68 @@ +//http://sandbox.kidstrythisathome.com/erdos/ + +//$ ./scribblec.sh -ip scribble-demos/scrib/fase16/src -d scribble-demos/scrib/fase16/src scribble-demos/scrib/fase16/src/fase16/smtp/Smtp.scr -subtypes -api Smtp C +//$ javadoc -cp scribble-core/target/classes:scribble-runtime/target/classes:scribble-demos/scrib/fase16/src scribble-demos/scrib/fase16/src/fase16/smtp/*.java -subpackages fase16.smtp.Smtp.Smtp -d scribble-demos/scrib/fase16/javadoc/smtp + + +module fase16.smtp.Smtp; + +sig "fase16.smtp.message.server._220" + from "fase16/smtp/message/server/_220.java" as 220; +sig "fase16.smtp.message.server._250" + from "fase16/smtp/message/server/_250.java" as 250; +sig "fase16.smtp.message.server._250d" + from "fase16/smtp/message/server/_250d.java" as 250d; + +sig "fase16.smtp.message.client.Ehlo" + from "fase16/smtp/message/client/Ehlo.java" as Ehlo; +sig "fase16.smtp.message.client.StartTls" + from "fase16/smtp/message/client/StartTls.java" as StartTls; +sig "fase16.smtp.message.client.Quit" + from "fase16/smtp/message/client/Quit.java" as Quit; + +global protocol Smtp(role C, role S) +{ + 220 from S to C; //* + do Init(C, S); + do StartTls(C, S); + do Init(C, S); + Quit from C to S; +} +/*/ + choice at C + { + do Init(C, S); + do StartTls(C, S); + do Init(C, S); + Quit from C to S; + } + or + { + Quit from C to S; + } +} +//*/ + +global protocol Init(role C, role S) +{ + Ehlo from C to S; + rec X + { + choice at S + { + 250d from S to C; + continue X; + } + or + { + 250 from S to C; + } + } + // or Quit from C to S; // FIXME: +} + +global protocol StartTls(role C, role S) +{ + StartTls from C to S; + 220 from S to C; +} diff --git a/scribble-demos/scrib/fase16/src/fase16/smtp/SmtpC.java b/scribble-demos/scrib/fase16/src/fase16/smtp/SmtpC.java new file mode 100644 index 000000000..49b1ecbf9 --- /dev/null +++ b/scribble-demos/scrib/fase16/src/fase16/smtp/SmtpC.java @@ -0,0 +1,194 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ + + +//$ java -cp scribble-core/target/classes:scribble-runtime/target/classes:scribble-demos/target/classes fase16.smtp.SmtpC + + +package fase16.smtp; + +import static fase16.smtp.Smtp.Smtp.Smtp.S; +import static fase16.smtp.Smtp.Smtp.Smtp._220; +import static fase16.smtp.Smtp.Smtp.Smtp._250; +import static fase16.smtp.Smtp.Smtp.Smtp._250d; + +import java.io.IOException; + +import org.scribble.main.ScribRuntimeException; +import org.scribble.runtime.net.SSLSocketChannelWrapper; +import org.scribble.runtime.net.SocketChannelEndpoint; +import org.scribble.runtime.session.MPSTEndpoint; +import org.scribble.runtime.statechans.LinearSocket; +import org.scribble.runtime.util.Buf; + +import fase16.smtp.Smtp.Smtp.Smtp; +import fase16.smtp.Smtp.Smtp.roles.C; +import fase16.smtp.Smtp.Smtp.statechans.C.Smtp_C_1; +import fase16.smtp.Smtp.Smtp.statechans.C.Smtp_C_1_Future; +import fase16.smtp.Smtp.Smtp.statechans.C.Smtp_C_3; +import fase16.smtp.Smtp.Smtp.statechans.C.Smtp_C_3_Handler; +import fase16.smtp.Smtp.Smtp.statechans.C.Smtp_C_4; +import fase16.smtp.Smtp.Smtp.statechans.C.ioifaces.Branch_C_S_250__S_250d; +import fase16.smtp.Smtp.Smtp.statechans.C.ioifaces.Case_C_S_250__S_250d; +import fase16.smtp.Smtp.Smtp.statechans.C.ioifaces.Select_C_S_Ehlo; +import fase16.smtp.Smtp.Smtp.statechans.C.ioifaces.Succ_In_S_250; +import fase16.smtp.message.SmtpMessageFormatter; +import fase16.smtp.message.client.Ehlo; +import fase16.smtp.message.client.Quit; +import fase16.smtp.message.client.StartTls; +import fase16.smtp.message.server._250; +import fase16.smtp.message.server._250d; + +public class SmtpC +{ + public SmtpC() throws Exception + { + run(); + } + + public static void main(String[] args) throws Exception + { + new SmtpC(); + } + + public void run() throws Exception + { + String host = "smtp.cc.ic.ac.uk"; + int port = 25; + + Smtp smtp = new Smtp(); + try (MPSTEndpoint se = new MPSTEndpoint<>(smtp, Smtp.C, + new SmtpMessageFormatter())) + { + se.request(Smtp.S, SocketChannelEndpoint::new, host, port); + + Buf f1 = new Buf<>(); + Smtp_C_1 s1 = new Smtp_C_1(se); + + /* + doInit( + LinearSocket.wrapClient( + doInit(s1.async(S, _220, b1)) + .to(Select_C_S_StartTls.cast).send(S, new StartTls()) + .to(Receive_C_S_220.cast).async(S, _220) + .to(Select_C_S_Ehlo.cast) + , S, SSLSocketChannelWrapper::new) + ) + .to(Select_C_S_Quit.cast).send(S, new Quit()); + /*/ + doInit( + LinearSocket.wrapClient( + doInit(s1.async(S, _220, f1)) + .send(S, new StartTls()) + .async(S, _220) + , S, SSLSocketChannelWrapper::new) + ) + .send(S, new Quit()); + //*/ + + System.out.println("Server greeting: " + f1.val.sync().msg); + } + } + + private Succ_In_S_250 doInitWithCasts(Select_C_S_Ehlo s) throws Exception + { + Branch_C_S_250__S_250d b = + s.send(S, new Ehlo("test")).to(Branch_C_S_250__S_250d.cast); + Buf<_250> b1 = new Buf<>(); + Buf<_250d> b2 = new Buf<>(); + for (Case_C_S_250__S_250d c = b.branch(S); true; c = b.branch(S)) + { + switch (c.getOp()) + { + case _250: + return printlnBuf(c.receive(S, _250, b1), b1); + case _250d: + b = printBuf(c.receive(S, _250d, b2).to(Branch_C_S_250__S_250d.cast), b2); + break; + } + } + } + + private + < + S1 extends Branch_C_S_250__S_250d, + S2 extends Succ_In_S_250 + > + S2 doInit(Select_C_S_Ehlo s) throws Exception + { + Branch_C_S_250__S_250d b = s.send(S, new Ehlo("test")); + Buf<_250> b1 = new Buf<>(); + Buf<_250d> b2 = new Buf<>(); + for (Case_C_S_250__S_250d c = b.branch(S); true; c = b.branch(S)) + { + switch (c.getOp()) + { + case _250: + return printlnBuf(c.receive(S, _250, b1), b1); + case _250d: + b = printBuf(c.receive(S, _250d, b2), b2); + break; + } + } + } + + public static > S printBuf(S s, B b) + { + System.out.print(b.val); + return s; + } + + public static > S printlnBuf(S s, B b) + { + System.out.println(b.val); + return s; + } + + class MySmtpC3Handler implements Smtp_C_3_Handler + { + @Override + public void receive(Smtp_C_3 s3, fase16.smtp.Smtp.Smtp.ops._250d op, + Buf<_250d> arg) + throws ScribRuntimeException, IOException, ClassNotFoundException + { + s3.branch(S, this); + } + + @Override + public void receive(Smtp_C_4 s4, fase16.smtp.Smtp.Smtp.ops._250 op, + Buf<_250> arg) + throws ScribRuntimeException, IOException, ClassNotFoundException + { + try + { + doInit( + LinearSocket.wrapClient( + s4.send(S, new StartTls()) + .async(S, _220) + , S, SSLSocketChannelWrapper::new) + ) + .send(S, new Quit()); + } + catch (ScribRuntimeException | IOException | ClassNotFoundException x) + { + throw x; + } + catch (Exception x) + { + throw new ScribRuntimeException(x); + } + } + } +} + diff --git a/scribble-demos/scrib/fase16/src/fase16/smtp/message/SmtpMessage.java b/scribble-demos/scrib/fase16/src/fase16/smtp/message/SmtpMessage.java new file mode 100644 index 000000000..621094a83 --- /dev/null +++ b/scribble-demos/scrib/fase16/src/fase16/smtp/message/SmtpMessage.java @@ -0,0 +1,86 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package fase16.smtp.message; + +import org.scribble.core.type.name.Op; +import org.scribble.runtime.message.ScribMessage; +import org.scribble.util.Caller; + +import fase16.smtp.Smtp.Smtp.Smtp; + +public abstract class SmtpMessage extends ScribMessage +{ + public static final String _220 = "220"; + public static final String _250 = "250"; + public static final String _250_ = "250-"; + public static final String _235 = "235"; + public static final String _535 = "535"; + public static final String _501 = "501"; + public static final String _354 = "354"; + + public static final String EHLO = "ehlo"; + public static final String STARTTLS = "starttls"; + public static final String AUTH = "auth plain"; + public static final String MAIL = "mail from:"; + public static final String RCPT = "rcpt to:"; + public static final String SUBJECT = "subject:"; + public static final String DATA = "data"; + public static final String QUIT = "quit"; + + public static final String DATA_LINE = ""; + public static final String END_OF_DATA = ""; + + private static final long serialVersionUID = 1L; + + protected static final String CRLF = "\r\n"; + + public SmtpMessage(Op op) + { + super(op); + } + + public SmtpMessage(Op op, String body) + { + super(op, body); + } + + public String getBody() + { + return (this.payload.length == 0) ? "" : (String) this.payload[0]; + } + + public byte[] toBytes() + { + byte[] bs = (getOpString(this.op) + " " + getBody() + SmtpMessage.CRLF).getBytes(SmtpMessageFormatter.cs); // Can give "utf-8" as arg directly + return bs; + } + + @Override + public String toString() + { + return new String(toBytes()); + } + + protected static String getOpString(Op op) + { + return + (op.equals(Smtp._220)) ? SmtpMessage._220 + : (op.equals(Smtp._250)) ? SmtpMessage._250 + : (op.equals(Smtp._250d)) ? SmtpMessage._250_ + : (op.equals(Smtp.Ehlo)) ? SmtpMessage.EHLO + : (op.equals(Smtp.StartTls)) ? SmtpMessage.STARTTLS + : (op.equals(Smtp.Quit)) ? SmtpMessage.QUIT + : new Caller().call(() -> { throw new RuntimeException("TODO: " + op); }); + } +} diff --git a/scribble-demos/scrib/fase16/src/fase16/smtp/message/SmtpMessageFormatter.java b/scribble-demos/scrib/fase16/src/fase16/smtp/message/SmtpMessageFormatter.java new file mode 100644 index 000000000..fcb8f4771 --- /dev/null +++ b/scribble-demos/scrib/fase16/src/fase16/smtp/message/SmtpMessageFormatter.java @@ -0,0 +1,447 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package fase16.smtp.message; + +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.Charset; + +import org.scribble.runtime.message.ScribMessage; +import org.scribble.runtime.message.ScribMessageFormatter; + +import fase16.smtp.message.server._220; +import fase16.smtp.message.server._250; +import fase16.smtp.message.server._250d; + +// Currently supports only client-side reading, not server-side +public class SmtpMessageFormatter implements ScribMessageFormatter +{ + //.. fix formatting + //.. try ssl wrapper + //.. add connection (transport) actions + + public static Charset cs = Charset.forName("UTF8"); + //private static CharsetDecoder cd = cs.newDecoder(); + + public SmtpMessageFormatter() + { + + } + + @Override + public byte[] toBytes(ScribMessage m) throws IOException + { + return ((SmtpMessage) m).toBytes(); + } + + @Override + public ScribMessage fromBytes(ByteBuffer bb) + throws IOException, ClassNotFoundException + { + bb.flip(); + //byte[] bs = new byte[2]; + int rem = bb.remaining(); + if (rem < 2) + { + bb.compact(); + return null; + } + + int pos = bb.position(); + String front = new String(new byte[] { bb.get(pos), bb.get(pos + 1) }, SmtpMessageFormatter.cs); + if (front.equals(SmtpMessage.CRLF)) + { + throw new RuntimeException("TODO: "); + } + + if (rem < pos + 4) + { + bb.compact(); + return null; + } + front += new String(new byte[] { bb.get(pos + 2), bb.get(pos + 3) }, SmtpMessageFormatter.cs); + int code = isStatusCode(front); + if (code > -1) + { + String body = readLine(bb, pos + 4).trim(); // Whitespace already built into the message classes + bb.compact(); + if (body == null) + { + return null; + } + switch (code) + { + case 220: return new _220(body); + case 250: + { + if (front.charAt(3) == '-') + { + return new _250d(body); + } + return new _250(body); + } + /*case 235: return new _235(body); + case 535: return new _535(body); + case 501: return new _501(body); + case 354: return new _354(body);*/ + default: throw new RuntimeException("Unknown status code " + code + ": " + body); + } + } + /*else if (front.startsWith(HttpMessage.GET)) // TODO: server-side (EHLO, STARTTLS, etc) + { + }*/ + else + { + // TODO: server-side (MAIL FROM:, RCPT TO:, etc) + String line = front + readLine(bb, pos + 4); + bb.compact(); + /*if (line == null) // deadcode + { + return null; + }*/ + throw new RuntimeException("Cannot parse message: " + line); + } + } + + private static String readLine(ByteBuffer bb, int i) throws IOException + { + StringBuilder sb = new StringBuilder(); + for (int limit = bb.limit(); i <= limit; ) + { + char c = (char) bb.get(i++); + sb.append(c); + if (c == '\r') + { + c = (char) bb.get(i++); + sb.append(c); + if (c == '\n') + { + bb.position(i); + return sb.substring(0, sb.length() - 2).toString(); + } + } + } + return null; + } + + // Duplicated from HttpMessageFormatter // FIXME: factor out + private int isStatusCode(String front) + { + String code = ""; + for (int i = 0; i < 4; i++) + { + //char c = (char) bs[i]; + char c = front.charAt(i); + if (i < 3) + { + if (c < '0' || c > '9') + { + return -1; + } + code += c; + } + else + { + if (c != ' ' && c != '-') // HACK: hypen + { + return -1; + } + } + } + return Integer.parseInt(code); + } + + /*private static String readWord(ByteBuffer bb, int i) throws IOException + { + StringBuilder sb = new StringBuilder(); + for (int limit = bb.limit(); i <= limit; ) + { + char c = (char) bb.get(i); + if (c == ' ') + { + bb.position(i); + return sb.toString(); + } + sb.append(c); + } + return null; + }*/ + + /* // Pre: flipped ready for reading + @Override + public SmtpMessage readMessage(DataInputStream dis) throws IOException + { + String header = getHeader(dis); + switch (header) + { + // FIXME: factor out text constants with Session constants? + case "220 ": + { + return new _220(getBody(dis)); + } + case "235 ": + { + return new _235(getBody(dis)); + } + case "250-": + { + return new _250_(getBody(dis)); + } + case "250 ": + { + return new _250(getBody(dis)); + } + case "354 ": + { + return new _354(getBody(dis)); + } + case "501 ": + { + return new _501(getBody(dis)); + } + case "535 ": + { + return new _535(getBody(dis)); + } + default: + { + throw new RuntimeException("Unknown header: " + header); + } + } + } + + // *4* char headers (3 digits, dash or space) + private String getHeader(DataInputStream dis) throws IOException + { + readMinimumBytes(dis, 4); + + int limit = bb.limit(); + bb.limit(4); + String header = cd.decode(bb).toString(); // updates bb position + bb.limit(limit); + bb.compact(); + bb.flip(); + return header; + } + + // Reads up to \r\n inclusive; doesn't return the \r\n + private String getBody(DataInputStream dis) throws IOException + { + int min = 2; + readMinimumBytes(dis, min); // Min should be more? + while (true) + { + String all = cd.decode(bb).toString(); // updates bb position + if (all.contains("\n")) // FIXME: didn't check exactly \r\n + { + int i = all.indexOf("\n"); + String body = all.substring(0, i - 1); + bb.position(i + 1); // \r\n -- ASCII 1-to-1 byte-char index + bb.compact(); + bb.flip(); + return body; + } + bb.rewind(); + readMinimumBytes(dis, ++min); // FIXME: buffered readLine would be more efficient + } + } + + // FIXME: min should mean min fresh (i.e. not including bb cached -- there currently is no cache: is.available doesn't work for SSLSocket, always returns 0) + private void readMinimumBytes(DataInputStream dis, int min) throws IOException + { + for (int remaining = bb.remaining(); remaining < min; remaining = bb.remaining()) + { + bb.compact(); + bb.put((byte) dis.read()); // FIXME: check for buffer overflow + bb.flip(); + } + }*/ + + @Override + public void writeMessage(DataOutputStream dos, ScribMessage m) throws IOException + { + dos.write(((SmtpMessage) m).toBytes()); + dos.flush(); + } + + @Override + public SmtpMessage readMessage(DataInputStream dis) throws IOException + { + byte[] bs = new byte[2]; + dis.readFully(bs); + String front = new String(bs, SmtpMessageFormatter.cs); + if (front.equals(SmtpMessage.CRLF)) + { + throw new RuntimeException("TODO: "); + } + bs = new byte[2]; + dis.readFully(bs); + front += new String(bs, SmtpMessageFormatter.cs); + int code = isStatusCode(front); + if (code > -1) + { + String body = readLine(dis).trim(); // Whitespace already built into the message classes + switch (code) + { + case 220: return new _220(body); + case 250: + { + if (front.charAt(3) == '-') + { + return new _250d(body); + } + return new _250(body); + } + /*case 235: return new _235(body); + case 535: return new _535(body); + case 501: return new _501(body); + case 354: return new _354(body);*/ + default: throw new RuntimeException("Unknown status code: " + code); + } + } + /*else if (front.startsWith(HttpMessage.GET)) + { + }*/ + else + { + String line = front + readLine(dis); + throw new RuntimeException("Cannot parse message: " + line); + } + } + + private static String readLine(DataInputStream dis) throws IOException + { + StringBuilder sb = new StringBuilder(); + for (; true; ) + { + char c = (char) dis.read(); // readChar is not the same + sb.append(c); + if (c == '\r') + { + c = (char) dis.read(); + sb.append(c); + if (c == '\n') + { + return sb.substring(0, sb.length() - 2).toString(); + } + } + } + } + + /*private static String readWord(DataInputStream dis) throws IOException + { + StringBuilder sb = new StringBuilder(); + for (; true; ) + { + char c = (char) dis.read(); + if (c == ' ') + { + return sb.toString(); + } + sb.append(c); + } + }*/ + + /* // Pre: flipped ready for reading + @Override + public SmtpMessage readMessage(DataInputStream dis) throws IOException + { + String header = getHeader(dis); + switch (header) + { + // FIXME: factor out text constants with Session constants? + case "220 ": + { + return new _220(getBody(dis)); + } + case "235 ": + { + return new _235(getBody(dis)); + } + case "250-": + { + return new _250_(getBody(dis)); + } + case "250 ": + { + return new _250(getBody(dis)); + } + case "354 ": + { + return new _354(getBody(dis)); + } + case "501 ": + { + return new _501(getBody(dis)); + } + case "535 ": + { + return new _535(getBody(dis)); + } + default: + { + throw new RuntimeException("Unknown header: " + header); + } + } + } + + // *4* char headers (3 digits, dash or space) + private String getHeader(DataInputStream dis) throws IOException + { + readMinimumBytes(dis, 4); + + int limit = bb.limit(); + bb.limit(4); + String header = cd.decode(bb).toString(); // updates bb position + bb.limit(limit); + bb.compact(); + bb.flip(); + return header; + } + + // Reads up to \r\n inclusive; doesn't return the \r\n + private String getBody(DataInputStream dis) throws IOException + { + int min = 2; + readMinimumBytes(dis, min); // Min should be more? + while (true) + { + String all = cd.decode(bb).toString(); // updates bb position + if (all.contains("\n")) // FIXME: didn't check exactly \r\n + { + int i = all.indexOf("\n"); + String body = all.substring(0, i - 1); + bb.position(i + 1); // \r\n -- ASCII 1-to-1 byte-char index + bb.compact(); + bb.flip(); + return body; + } + bb.rewind(); + readMinimumBytes(dis, ++min); // FIXME: buffered readLine would be more efficient + } + } + + // FIXME: min should mean min fresh (i.e. not including bb cached -- there currently is no cache: is.available doesn't work for SSLSocket, always returns 0) + private void readMinimumBytes(DataInputStream dis, int min) throws IOException + { + for (int remaining = bb.remaining(); remaining < min; remaining = bb.remaining()) + { + bb.compact(); + bb.put((byte) dis.read()); // FIXME: check for buffer overflow + bb.flip(); + } + }*/ +} diff --git a/scribble-demos/scrib/fase16/src/fase16/smtp/message/client/Ehlo.java b/scribble-demos/scrib/fase16/src/fase16/smtp/message/client/Ehlo.java new file mode 100644 index 000000000..732b68550 --- /dev/null +++ b/scribble-demos/scrib/fase16/src/fase16/smtp/message/client/Ehlo.java @@ -0,0 +1,32 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package fase16.smtp.message.client; + +import fase16.smtp.Smtp.Smtp.Smtp; +import fase16.smtp.message.SmtpMessage; + +public class Ehlo extends SmtpMessage +{ + private static final long serialVersionUID = 1L; + + public Ehlo() + { + super(Smtp.Ehlo); + } + + public Ehlo(String body) + { + super(Smtp.Ehlo, body); + } +} diff --git a/scribble-demos/scrib/fase16/src/fase16/smtp/message/client/Quit.java b/scribble-demos/scrib/fase16/src/fase16/smtp/message/client/Quit.java new file mode 100644 index 000000000..128aa9004 --- /dev/null +++ b/scribble-demos/scrib/fase16/src/fase16/smtp/message/client/Quit.java @@ -0,0 +1,27 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package fase16.smtp.message.client; + +import fase16.smtp.Smtp.Smtp.Smtp; +import fase16.smtp.message.SmtpMessage; + +public class Quit extends SmtpMessage +{ + private static final long serialVersionUID = 1L; + + public Quit() + { + super(Smtp.Quit); + } +} diff --git a/scribble-demos/scrib/fase16/src/fase16/smtp/message/client/StartTls.java b/scribble-demos/scrib/fase16/src/fase16/smtp/message/client/StartTls.java new file mode 100644 index 000000000..4565fb371 --- /dev/null +++ b/scribble-demos/scrib/fase16/src/fase16/smtp/message/client/StartTls.java @@ -0,0 +1,27 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package fase16.smtp.message.client; + +import fase16.smtp.Smtp.Smtp.Smtp; +import fase16.smtp.message.SmtpMessage; + +public class StartTls extends SmtpMessage +{ + private static final long serialVersionUID = 1L; + + public StartTls() + { + super(Smtp.StartTls); + } +} diff --git a/scribble-demos/scrib/fase16/src/fase16/smtp/message/server/_220.java b/scribble-demos/scrib/fase16/src/fase16/smtp/message/server/_220.java new file mode 100644 index 000000000..2e60f7ce5 --- /dev/null +++ b/scribble-demos/scrib/fase16/src/fase16/smtp/message/server/_220.java @@ -0,0 +1,38 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package fase16.smtp.message.server; + +import fase16.smtp.Smtp.Smtp.Smtp; +import fase16.smtp.message.SmtpMessage; + +public class _220 extends SmtpMessage +{ + private static final long serialVersionUID = 1L; + + public _220() + { + super(Smtp._220); + } + + public _220(String body) + { + super(Smtp._220, body); + } + + /*@Override + public Operator getOperator() + { + return Smtp._220; + }*/ +} diff --git a/scribble-demos/scrib/fase16/src/fase16/smtp/message/server/_250.java b/scribble-demos/scrib/fase16/src/fase16/smtp/message/server/_250.java new file mode 100644 index 000000000..a79d8aa36 --- /dev/null +++ b/scribble-demos/scrib/fase16/src/fase16/smtp/message/server/_250.java @@ -0,0 +1,32 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package fase16.smtp.message.server; + +import fase16.smtp.Smtp.Smtp.Smtp; +import fase16.smtp.message.SmtpMessage; + +public class _250 extends SmtpMessage +{ + private static final long serialVersionUID = 1L; + + public _250() + { + super(Smtp._250); + } + + public _250(String body) + { + super(Smtp._250, body); + } +} diff --git a/scribble-demos/scrib/fase16/src/fase16/smtp/message/server/_250d.java b/scribble-demos/scrib/fase16/src/fase16/smtp/message/server/_250d.java new file mode 100644 index 000000000..68179cd15 --- /dev/null +++ b/scribble-demos/scrib/fase16/src/fase16/smtp/message/server/_250d.java @@ -0,0 +1,40 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package fase16.smtp.message.server; + +import fase16.smtp.Smtp.Smtp.Smtp; +import fase16.smtp.message.SmtpMessage; +import fase16.smtp.message.SmtpMessageFormatter; + +public class _250d extends SmtpMessage +{ + private static final long serialVersionUID = 1L; + + public _250d() + { + super(Smtp._250d); + } + + public _250d(String body) + { + super(Smtp._250d, body); + } + + @Override + public byte[] toBytes() + { + // No space after op + return (getOpString(this.op) + getBody() + SmtpMessage.CRLF).getBytes(SmtpMessageFormatter.cs); + } +} diff --git a/scribble-demos/scrib/fib/src/fib/AdderClient.java b/scribble-demos/scrib/fib/src/fib/AdderClient.java new file mode 100644 index 000000000..5350e50e5 --- /dev/null +++ b/scribble-demos/scrib/fib/src/fib/AdderClient.java @@ -0,0 +1,106 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +//$ java -cp modules/cli/target/classes/';'modules/core/target/classes';'modules/trace/target/classes';'modules/parser/target/classes';c:\Users\Raymond\.m2\repository\org\antlr\antlr-runtime\3.2\antlr-runtime-3.2.jar;'modules/validation/target/classes/';'modules/projection/target/classes/';C:\Users\Raymond\.m2\repository\org\codehaus\jackson\jackson-mapper-asl\1.9.9\jackson-mapper-asl-1.9.9.jar;C:\Users\Raymond\.m2\repository\org\codehaus\jackson\jackson-core-asl\1.9.9\jackson-core-asl-1.9.9.jar' org.scribble2.cli.CommandLine -path modules/validation/src/test/scrib/src modules/validation/src/test/scrib/src/Test.scr -session Foo -d modules/validation/src/main/java +//$ java -cp modules/cli/target/classes/';'modules/core/target/classes';'modules/trace/target/classes';'modules/parser/target/classes';c:\Users\Raymond\.m2\repository\org\antlr\antlr-runtime\3.2\antlr-runtime-3.2.jar;'modules/validation/target/classes/';'modules/projection/target/classes/';C:\Users\Raymond\.m2\repository\org\codehaus\jackson\jackson-mapper-asl\1.9.9\jackson-mapper-asl-1.9.9.jar;C:\Users\Raymond\.m2\repository\org\codehaus\jackson\jackson-core-asl\1.9.9\jackson-core-asl-1.9.9.jar' org.scribble2.cli.CommandLine -path modules/validation/src/test/scrib/src modules/validation/src/test/scrib/src/Test.scr -api Foo A -d modules/validation/src/main/java + +package fib; + +import java.io.IOException; +import java.net.UnknownHostException; +import java.util.concurrent.ExecutionException; + +import org.scribble.main.ScribRuntimeException; +import org.scribble.runtime.message.ObjectStreamFormatter; +import org.scribble.runtime.net.SocketChannelEndpoint; +import org.scribble.runtime.session.MPSTEndpoint; +import org.scribble.runtime.util.Buf; + +import fib.Fib.Adder.Adder; +import fib.Fib.Adder.roles.C; +import fib.Fib.Adder.statechans.C.Adder_C_1; +import fib.Fib.Adder.statechans.C.ioifaces.Receive_C_S_BYE; +import fib.Fib.Adder.statechans.C.ioifaces.Receive_C_S_RES_Int; +import fib.Fib.Adder.statechans.C.ioifaces.Select_C_S_ADD_Int_Int__S_BYE; +import fib.Fib.Adder.statechans.C.ioifaces.Succ_Out_S_BYE; + + +public class AdderClient +{ + public static void main(String[] args) + throws UnknownHostException, ScribRuntimeException, IOException, + ClassNotFoundException, ExecutionException, InterruptedException + { + Buf i1 = new Buf<>(1); + //Buf i2 = new Buf<>(2); + + Adder adder = new Adder(); + try (MPSTEndpoint se = new MPSTEndpoint<>(adder, Adder.C, + new ObjectStreamFormatter())) + { + se.request(Adder.S, SocketChannelEndpoint::new, "localhost", 8888); + + Adder_C_1 s1 = new Adder_C_1(se); + + /*s1.send(Adder.S, Adder.ADD, i1.val, i1.val) + .receive(Adder.S, Adder.RES, i1) + .send(Adder.S, Adder.ADD, i1.val, i1.val) + .receive(Adder.S, Adder.RES, i1) + .send(Adder.S, Adder.BYE) + .receive(Adder.S, Adder.BYE);*/ + + /*while (i1.val < 100) + { + s1 = s1.send(Adder.S, Adder.ADD, i1.val, i1.val).receive(Adder.S, Adder.RES, i1); + } + s1.send(Adder.S, Adder.BYE).receive(Adder.S, Adder.BYE) + .end();*/ + + //fib(i1, i2, s1).end(); + + foo(s1, i1).to(Receive_C_S_BYE.cast).receive(Adder.S, Adder.BYE); + //foo(s1, i1); + + System.out.println("Client: " + i1.val); + } + } + + private static Succ_Out_S_BYE foo(Select_C_S_ADD_Int_Int__S_BYE s, Buf i) throws ClassNotFoundException, ScribRuntimeException, IOException + //private static EndSocket foo(Select_C_S_ADD_Integer_Integer__S_BYE s, Buf i) throws ClassNotFoundException, ScribRuntimeException, IOException + { + return (i.val < 100) + ? foo( + s.send(Adder.S, Adder.ADD, i.val, i.val) + .to(Receive_C_S_RES_Int.cast) + .receive(Adder.S, Adder.RES, i) + .to(Select_C_S_ADD_Int_Int__S_BYE.cast) + , i) + : s.send(Adder.S, Adder.BYE); + } + + /*private static EndSocket fib(Buf i1, Buf i2, Adder_C_1 s1) throws ScribRuntimeException, IOException, ClassNotFoundException, ExecutionException, InterruptedException + { + return (i1.val < 100) + ? fib(i1, i2, + side(i1, i2, s1.send(Adder.S, Adder.ADD, i1.val, i2.val)).receive(Adder.S, Adder.RES, i2) + ) + : s1.send(Adder.S, Adder.BYE).receive(Adder.S, Adder.BYE); + } + + private static Adder_C_2 side(Buf i1, Buf i2, Adder_C_2 s2) + { + i1.val = i2.val; + System.out.print(i1.val + " "); + return s2; + }*/ +} diff --git a/scribble-demos/scrib/fib/src/fib/AdderServer.java b/scribble-demos/scrib/fib/src/fib/AdderServer.java new file mode 100644 index 000000000..5465ae60a --- /dev/null +++ b/scribble-demos/scrib/fib/src/fib/AdderServer.java @@ -0,0 +1,81 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package fib; + +import java.io.IOException; +import java.util.concurrent.ExecutionException; + +import org.scribble.main.ScribRuntimeException; +import org.scribble.runtime.message.ObjectStreamFormatter; +import org.scribble.runtime.net.ScribServerSocket; +import org.scribble.runtime.net.SocketChannelServer; +import org.scribble.runtime.session.MPSTEndpoint; +import org.scribble.runtime.util.Buf; + +import fib.Fib.Adder.Adder; +import fib.Fib.Adder.roles.S; +import fib.Fib.Adder.statechans.S.Adder_S_1; +import fib.Fib.Adder.statechans.S.Adder_S_1_Cases; +import fib.Fib.Adder.statechans.S.Adder_S_3; + +public class AdderServer +{ + public static void main(String[] args) throws IOException, + ScribRuntimeException, ExecutionException, InterruptedException + { + try (ScribServerSocket ss = new SocketChannelServer(8888)) + { + Buf i1 = new Buf<>(); + Buf i2 = new Buf<>(); + + while (true) + { + Adder foo = new Adder(); + try (MPSTEndpoint se = new MPSTEndpoint<>(foo, Adder.S, + new ObjectStreamFormatter())) + { + se.accept(ss, Adder.C); + + X(new Adder_S_1(se), i1, i2).send(Adder.C, Adder.BYE); + } + catch (ScribRuntimeException | IOException | ClassNotFoundException e) + { + e.printStackTrace(); + } + } + } + } + + private static Adder_S_3 X(Adder_S_1 s1, Buf i1, Buf i2) + throws ClassNotFoundException, ScribRuntimeException, IOException, + ExecutionException, InterruptedException + { + Adder_S_1_Cases cases = s1.branch(Adder.C); + switch (cases.op) + { + case BYE: + { + return cases.receive(Adder.BYE); + } + case ADD: + { + return X(cases.receive(Adder.ADD, i1, i2).send(Adder.C, Adder.RES, i1.val + i2.val), i1, i2); + } + default: + { + throw new RuntimeException("Won't get here: "); + } + } + } +} diff --git a/scribble-demos/scrib/fib/src/fib/Fib.scr b/scribble-demos/scrib/fib/src/fib/Fib.scr new file mode 100644 index 000000000..3a2be9408 --- /dev/null +++ b/scribble-demos/scrib/fib/src/fib/Fib.scr @@ -0,0 +1,46 @@ +//$ ./scribblec.sh -ip scribble-demos/scrib/fib/src -d scribble-demos/scrib/fib/src scribble-demos/scrib/fib/src/fib/Fib.scr -api Adder C +//$ javadoc -cp scribble-core/target/classes:scribble-runtime/target/classes:scribble-demos/scrib/fib/src scribble-demos/scrib/fib/src/fib/*.java -subpackages fib.Fib.Adder -d scribble-demos/scrib/fib/javadoc/adder + +module fib.Fib; + + +data "java.lang.Integer" from "rt.jar" as Int; + + +global protocol Adder(role C, role S) +{ + /*[x+1<10 && x<9 && x<10] + ADD(x:Int) from C to S;*/ + + choice at C + { + ADD(Int, Int) from C to S; + RES(Int) from S to C; + do Adder(C, S); + } + or + { + BYE() from C to S; + BYE() from S to C; + } +} + + + + +global protocol Fibonacci(role A, role B) +{ + rec Fib + { + choice at A + { + fibonacci(Int) from A to B; + fibonacci(Int) from B to A; + continue Fib; + } + or + { + end() from A to B; + } + } +} diff --git a/scribble-demos/scrib/fib/src/fib/FibClient.java b/scribble-demos/scrib/fib/src/fib/FibClient.java new file mode 100644 index 000000000..69c929601 --- /dev/null +++ b/scribble-demos/scrib/fib/src/fib/FibClient.java @@ -0,0 +1,69 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package fib; + +import java.io.IOException; +import java.net.UnknownHostException; +import java.util.concurrent.ExecutionException; + +import org.scribble.main.ScribRuntimeException; +import org.scribble.runtime.message.ObjectStreamFormatter; +import org.scribble.runtime.net.SocketChannelEndpoint; +import org.scribble.runtime.session.MPSTEndpoint; +import org.scribble.runtime.util.Buf; + +import fib.Fib.Adder.Adder; +import fib.Fib.Adder.roles.C; +import fib.Fib.Adder.statechans.C.Adder_C_1; +import fib.Fib.Adder.statechans.C.Adder_C_2; +import fib.Fib.Adder.statechans.C.Adder_C_3; + +public class FibClient +{ + public static void main(String[] args) + throws UnknownHostException, ScribRuntimeException, IOException, + ClassNotFoundException, ExecutionException, InterruptedException + { + Buf i1 = new Buf<>(0); + Buf i2 = new Buf<>(1); + + Adder adder = new Adder(); + try (MPSTEndpoint se = new MPSTEndpoint<>(adder, Adder.C, + new ObjectStreamFormatter())) + { + se.request(Adder.S, SocketChannelEndpoint::new, "localhost", 8888); + + Adder_C_1 s1 = new Adder_C_1(se); + + fib(s1, i1, i2, 0).receive(Adder.S, Adder.BYE); + } + } + + private static Adder_C_3 fib(Adder_C_1 s1, Buf i1, Buf i2, + int i) throws ClassNotFoundException, ScribRuntimeException, IOException, + ExecutionException, InterruptedException + { + return (i < 20) + //? fib(side(s1.send(Adder.S, Adder.ADD, i1.val, i2.val), i1, i2).receive(Adder.RES, i2), i1, i2, i + 1) + ? fib(side(s1.send(Adder.S, Adder.ADD, i1.val, i1.val = i2.val), i1, i2).receive(Adder.S, Adder.RES, i2), i1, i2, i + 1) + : s1.send(Adder.S, Adder.BYE); + } + + private static Adder_C_2 side(Adder_C_2 s2, Buf i1, Buf i2) + { + System.out.print(i1.val + " "); + //i1.val = i2.val; + return s2; + } +} diff --git a/scribble-demos/scrib/fib/src/fib/Fibo.java b/scribble-demos/scrib/fib/src/fib/Fibo.java new file mode 100644 index 000000000..acf74a8b2 --- /dev/null +++ b/scribble-demos/scrib/fib/src/fib/Fibo.java @@ -0,0 +1,135 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +//$ bin/scribblec.sh modules/core/src/test/scrib/demo/fib/Fib.scr -ip modules/core/src/test/scrib/ -d modules/core/src/test/scrib/ -api Fibonacci A -api Fibonacci B + +package fib; + +import java.io.IOException; + +import org.scribble.main.ScribRuntimeException; +import org.scribble.runtime.message.ObjectStreamFormatter; +import org.scribble.runtime.net.ScribServerSocket; +import org.scribble.runtime.net.SocketChannelEndpoint; +import org.scribble.runtime.net.SocketChannelServer; +import org.scribble.runtime.session.MPSTEndpoint; +import org.scribble.runtime.util.Buf; + +import fib.Fib.Fibonacci.Fibonacci; +import fib.Fib.Fibonacci.ops.end; +import fib.Fib.Fibonacci.ops.fibonacci; +import fib.Fib.Fibonacci.roles.A; +import fib.Fib.Fibonacci.roles.B; +import fib.Fib.Fibonacci.statechans.A.Fibonacci_A_1; +import fib.Fib.Fibonacci.statechans.B.EndSocket; +import fib.Fib.Fibonacci.statechans.B.Fibonacci_B_1; +import fib.Fib.Fibonacci.statechans.B.Fibonacci_B_1_Handler; +import fib.Fib.Fibonacci.statechans.B.Fibonacci_B_2; + +public class Fibo +{ + public static void main(String[] args) throws Exception + { + Fibonacci fib = new Fibonacci(); + new MyB(fib).start(); + new MyA(fib).start(); + } +} + +class MyB extends Thread implements Fibonacci_B_1_Handler +{ + private final Fibonacci fib; + private int x = 1; + + public MyB(Fibonacci fib) + { + this.fib = fib; + } + + @Override + public void run() + { + try (ScribServerSocket ss = new SocketChannelServer(8888); + MPSTEndpoint se = new MPSTEndpoint<>(this.fib, + Fibonacci.B, new ObjectStreamFormatter())) + { + se.accept(ss, Fibonacci.A); + new Fibonacci_B_1(se).branch(Fibonacci.A, this); + } + catch (Exception x) + { + x.printStackTrace(); + } + } + + @Override + public void receive(Fibonacci_B_2 s, fibonacci op, Buf arg1) + throws ScribRuntimeException, IOException, ClassNotFoundException + { + s.send(Fibonacci.A, Fibonacci.fibonacci, (this.x += arg1.val)).branch(Fibonacci.A, this); + } + + @Override + public void receive(EndSocket schan, end op) + throws ScribRuntimeException, IOException, ClassNotFoundException + { + //System.out.println("B done: " + this.x); + } +} + +class MyA extends Thread +{ + private final Fibonacci fib; + private Buf b = new Buf<>(0); + + public MyA(Fibonacci fib) + { + this.fib = fib; + } + + @Override + public void run() + { + try (MPSTEndpoint se = new MPSTEndpoint<>(this.fib, + Fibonacci.A, new ObjectStreamFormatter())) + { + se.request(Fibonacci.B, SocketChannelEndpoint::new, "localhost", 8888); + run(new Fibonacci_A_1(se), 19); // 4184 + System.out.println("A done: " + this.b.val); + } + catch (Exception x) + { + x.printStackTrace(); + } + } + + private fib.Fib.Fibonacci.statechans.A.EndSocket run(Fibonacci_A_1 s, int todo) + throws Exception + { + return (todo > 0) + ? run( + next(this.b.val, + s.send(Fibonacci.B, Fibonacci.fibonacci, this.b.val) + .receive(Fibonacci.B, Fibonacci.fibonacci, this.b), todo), + todo - 2) + : s.send(Fibonacci.B, Fibonacci.end); + } + + private Fibonacci_A_1 next(int prev, Fibonacci_A_1 s, int todo) + { + //System.out.println("A: " + prev); + if (todo > 1) + this.b.val += prev; + return s; + } +} diff --git a/scribble-demos/scrib/fib/src/fib/MyAdderC.java b/scribble-demos/scrib/fib/src/fib/MyAdderC.java new file mode 100644 index 000000000..2755ae8ea --- /dev/null +++ b/scribble-demos/scrib/fib/src/fib/MyAdderC.java @@ -0,0 +1,46 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package fib; + +import org.scribble.runtime.message.ObjectStreamFormatter; +import org.scribble.runtime.net.SocketChannelEndpoint; +import org.scribble.runtime.session.MPSTEndpoint; + +import fib.Fib.Adder.Adder; +import fib.Fib.Adder.roles.C; +import fib.Fib.Adder.statechans.C.Adder_C_1; + +public class MyAdderC +{ + public static void main(String[] args) throws Exception + { + Adder adder = new Adder(); + try (MPSTEndpoint se = new MPSTEndpoint<>(adder, Adder.C, + new ObjectStreamFormatter())) + { + se.request(Adder.S, SocketChannelEndpoint::new, "localhost", 8888); + + Adder_C_1 s1 = new Adder_C_1(se); + + //System.out.println("Client: " + buf.val); + } + } + + /*private static Adder_C_3 side(Buff i1, Buff i2, Adder_C_3 s3) + { + System.out.print(i1.val + " "); + i1.val = i2.val; + return s3; + }*/ +} diff --git a/scribble-demos/scrib/game/src/game/Game1.scr b/scribble-demos/scrib/game/src/game/Game1.scr new file mode 100644 index 000000000..8765d54e1 --- /dev/null +++ b/scribble-demos/scrib/game/src/game/Game1.scr @@ -0,0 +1,47 @@ +//$ ./scribblec.sh -ip scribble-demos/scrib/game/src -d scribble-demos/scrib/game/src scribble-demos/scrib/game/src/game/Game1.scr + + +module game.Game1; + + +global protocol Proto(role Client, role S1, role S2) +{ + choice at S1 + { + playAsA() from S1 to Client; + do Game(Client, S1, S2); + } + or + { + playAsB(Game@B) from S1 to Client; + fin() from S1 to S2; + } + or + { + playAsC(Game@C) from S1 to Client; + fin() from S1 to S2; + } +} + + +aux global protocol Game(role A, role B, role C) +{ + // Arbitrary for now + rec X + { + choice at A + { + 1() from A to B; + 1() from B to C; + 1() from C to A; + continue X; + } + or + { + 2() from A to B; + 2() from B to C; + 2() from C to A; + } + } +} + diff --git a/scribble-demos/scrib/game/src/game/Game2.scr b/scribble-demos/scrib/game/src/game/Game2.scr new file mode 100644 index 000000000..3e6e6f429 --- /dev/null +++ b/scribble-demos/scrib/game/src/game/Game2.scr @@ -0,0 +1,43 @@ +//$ ./scribblec.sh -ip scribble-demos/scrib/game/src -d scribble-demos/scrib/game/src scribble-demos/scrib/game/src/game/Game2.scr + +module game.Game2; + + +global protocol Proto(role C, role S) +{ + choice at S + { + playAsA(Game@A) from S to C; + } + or + { + playAsB(Game@B) from S to C; + } + or + { + playAsC(Game@C) from S to C; + } +} + + +global protocol Game(role A, role B, role C) +{ + // Arbitrary for now + rec X + { + choice at A + { + 1() from A to B; + 1() from B to C; + 1() from C to A; + continue X; + } + or + { + 2() from A to B; + 2() from B to C; + 2() from C to A; + } + } +} + diff --git a/scribble-demos/scrib/http/src/http/longvers/HttpLong.scr b/scribble-demos/scrib/http/src/http/longvers/HttpLong.scr new file mode 100644 index 000000000..de847c5a3 --- /dev/null +++ b/scribble-demos/scrib/http/src/http/longvers/HttpLong.scr @@ -0,0 +1,285 @@ +//$ ./scribblec.sh -ip scribble-demos/scrib/http/src -d scribble-demos/scrib/http/src scribble-demos/scrib/http/src/http/longvers/HttpLong.scr -api Http C +//$ javadoc -cp scribble-core/target/classes:scribble-runtime/target/classes:scribble-demos/scrib/http/src/ scribble-demos/scrib/http/src/http/longvers/*.java -subpackages http.longvers.HttpLong.Http -d scribble-demos/scrib/http/javadoc/longvers + + +module http.longvers.HttpLong; + +/*Connected to www.doc.ic.ac.uk. +Escape character is '^]'. +GET /~rhu/ HTTP/1.1 +host: www.doc.ic.ac.uk + +HTTP/1.1 200 OK // 200 is a separate message +Date: Mon, 13 Jun 2016 19:42:34 GMT +Server: Apache +Strict-Transport-Security: max-age=31536000; preload; includeSubDomains +Strict-Transport-Security: max-age=31536000; preload; includeSubDomains // BUG? (Apache configuration) +Last-Modified: Thu, 14 Apr 2016 12:46:24 GMT +ETag: "74a-53071482f6e0f" +Accept-Ranges: bytes +Content-Length: 1866 // Not using Transfer-Encoding: Chunked +Vary: Accept-Encoding +Content-Type: text/html +Via: 1.1 www.doc.ic.ac.uk*/ + + +sig "http.longvers.message.client.RequestLine" + from "http/longvers/message/RequestLine.java" + as REQUESTL; // GET /~rhu/ HTTP/1.1 + +sig "http.longvers.message.client.Host" + from "http/longvers/message/Host.java" + as HOST; // host: www.doc.ic.ac.uk + +//sig "http.longvers.message.CRLF" from "http.longvers.message.CRLF.java" as CRLF; + +sig "http.longvers.message.Body" + from "http/longvers/message/Body.java" + as BODY; + +sig "http.longvers.message.client.UserAgent" + from "http/longvers/message/UserAgent.java" + as USERA; // User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; rv:38.0) Gecko/20100101 Firefox/38.0 + +sig "http.longvers.message.client.Accept" + from "http/longvers/message/Accept.java" + as ACCEPT; // Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 + +sig "http.longvers.message.client.AcceptLanguage" + from "http/longvers/message/AcceptLanguage.java" + as ACCEPTL; // Accept-Language: en-GB,en;q=0.5 + +sig "http.longvers.message.client.AcceptEncoding" + from "http/longvers/message/AcceptEncoding.java" + as ACCEPTE; // Accept-Encoding: gzip, deflate + +sig "http.longvers.message.client.DoNotTrack" + from "http/longvers/message/DoNotTrack.java" + as DNT; // DNT: 1 + +sig "http.longvers.message.client.Connection" + from "http/longvers/message/Connection.java" + as CONNECTION; // Connection: keep-alive + +sig "http.longvers.message.client.UpgradeInsecureRequests" + from "http/longvers/message/UpgradeInsecureRequests.java" + as UPGRADEIR; // Upgrade-Insecure-Requests: 1 + +sig "http.longvers.message.client.Cookie" + from "http/longvers/message/Cookie.java" + as COOKIE; // Cookie: __utma=111872281.1372348290.1498163262.1498163262.1498163262.1; __utmz=111872281.1498163262.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none) + + +sig "http.longvers.message.server.HttpVersion" + from "http/longvers/message/HttpVersion.java" + as HTTPV; // HTTP/1.1 + +sig "http.longvers.message.server._200" // "Status" line (with HTTPV) + from "http/longvers/message/_200.java" + as 200; // 200 OK + +sig "http.longvers.message.server._404" + from "http/longvers/message/_404.java" + as 404; + +sig "http.longvers.message.server.Date" + from "http/longvers/message/Date.java" + as DATE; // Date: Sun, 24 May 2015 21:04:36 GMT + +sig "http.longvers.message.server.Server" + from "http/longvers/message/Server.java" + as SERVER; // Server: Apache + +sig "http.longvers.message.server.StrictTransportSecurity" + from "http/longvers/message/StrictTransportSecurity.java" + as STRICTTS; // Strict-Transport-Security: max-age=31536000; preload; includeSubDomains + //as STRICT_TRANSPORT_SECURITY; + +sig "http.longvers.message.server.LastModified" + from "http/longvers/message/LastModified.java" + as LASTM; // Last-Modified: Sat, 23 Jul 2011 09:38:43 GMT + +sig "http.longvers.message.server.ETag" + from "http/longvers/message/ETag.java" + as ETAG; // ETag: "ac6fa008-559-4a8b95908aec0" + +sig "http.longvers.message.server.AcceptRanges" + from "http/longvers/message/AcceptRanges.java" + as ACCEPTR; // Accept-Ranges: bytes + +sig "http.longvers.message.server.ContentLength" + from "http/longvers/message/ContentLength.java" + as CONTENTL; // Content-Length: 1369 + +sig "http.longvers.message.server.Vary" + from "http/longvers/message/Vary.java" + as VARY; // Vary: Accept-Encoding + +sig "http.longvers.message.server.ContentType" + from "http/longvers/message/ContentType.java" + as CONTENTT; // Content-Type: text/html + +sig "http.longvers.message.server.Via" + from "http/longvers/message/Via.java" + as VIA; // Via: 1.1 www.doc.ic.ac.uk + + +global protocol Http(role C, role S) +{ + do Request(C, S); + do Response(C, S); +} + +aux global protocol Request(role C, role S) +{ + choice at C + { + REQUESTL from C to S; // GET /~rhu/ HTTP/1.1 + rec X + { + choice at C + { + HOST from C to S; // Host: www.doc.ic.ac.uk + continue X; + } + or + { + USERA from C to S; // User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; rv:38.0) Gecko/20100101 Firefox/38.0 + continue X; + } + or + { + ACCEPT from C to S; // Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 + continue X; + } + or + { + ACCEPTL from C to S; // Accept-Language: en-GB,en;q=0.5 + continue X; + } + or + { + ACCEPTE from C to S; // Accept-Encoding: gzip, deflate + continue X; + } + or + { + DNT from C to S; // DNT: 1 + continue X; + } + or + { + CONNECTION from C to S; // Connection: keep-alive + continue X; + } + or + { + UPGRADEIR from C to S; // Upgrade-Insecure-Requests: 1 + continue X; + } + or + { + COOKIE from C to S; // Cookie: __utma=111872281.1372348290.1498163262.1498163262.1498163262.1; __utmz=111872281.1498163262.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none) + continue X; + } + or + { + //CRLF from C to S; + BODY from C to S; // FIXME: should be empty for client (maybe just ignored by server) without Content-Length (or Transfer-Encoding) headers + } + } + } + /*or + { + ... + }*/ +} + +/*interruptible +{ + par + { + HOST from C to S; + } + and + { + USERA from C to S; + } + ... +} +with // finally? +{ + BODY by C; +}*/ + +aux global protocol Response(role C, role S) +{ + HTTPV from S to C; // HTTP/1.1 + choice at S + { + 200 from S to C; // 200 OK + } + or + { + 404 from S to C; + } + + rec Y + { + choice at S + { + DATE from S to C; // Date: Sun, 24 May 2015 21:04:36 GMT + continue Y; + } + or + { + SERVER from S to C; // Server: Apache + continue Y; + } + or + { + STRICTTS from S to C; // Strict-Transport-Security: max-age=31536000; preload; includeSubDomains + //STRICT_TRANSPORT_SECURITY from S to C; + continue Y; + } + or + { + LASTM from S to C; // Last-Modified: Sat, 23 Jul 2011 09:38:43 GMT + continue Y; + } + or + { + ETAG from S to C; // ETag: "ac6fa008-559-4a8b95908aec0" + continue Y; + } + or + { + ACCEPTR from S to C; // Accept-Ranges: bytes + continue Y; + } + or + { + CONTENTL from S to C; // Content-Length: 1369 + continue Y; + } + or + { + VARY from S to C; // Vary: Accept-Encoding + continue Y; + } + or + { + CONTENTT from S to C; // Content-Type: text/html + continue Y; + } + or + { + VIA from S to C; // Via: 1.1 www.doc.ic.ac.uk + continue Y; + } + or + { + BODY from S to C; // Message length indicated by Content-Length + } + } +} diff --git a/scribble-demos/scrib/http/src/http/longvers/HttpLongC.java b/scribble-demos/scrib/http/src/http/longvers/HttpLongC.java new file mode 100644 index 000000000..683ad2d54 --- /dev/null +++ b/scribble-demos/scrib/http/src/http/longvers/HttpLongC.java @@ -0,0 +1,229 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package http.longvers; + +import static http.longvers.HttpLong.Http.Http.ACCEPTR; +import static http.longvers.HttpLong.Http.Http.BODY; +import static http.longvers.HttpLong.Http.Http.C; +import static http.longvers.HttpLong.Http.Http.CONTENTL; +import static http.longvers.HttpLong.Http.Http.CONTENTT; +import static http.longvers.HttpLong.Http.Http.DATE; +import static http.longvers.HttpLong.Http.Http.ETAG; +import static http.longvers.HttpLong.Http.Http.HTTPV; +import static http.longvers.HttpLong.Http.Http.LASTM; +import static http.longvers.HttpLong.Http.Http.S; +import static http.longvers.HttpLong.Http.Http.SERVER; +import static http.longvers.HttpLong.Http.Http.STRICTTS; +import static http.longvers.HttpLong.Http.Http.VARY; +import static http.longvers.HttpLong.Http.Http.VIA; +import static http.longvers.HttpLong.Http.Http._200; +import static http.longvers.HttpLong.Http.Http._404; + +import org.scribble.runtime.net.SocketChannelEndpoint; +import org.scribble.runtime.session.MPSTEndpoint; +import org.scribble.runtime.util.Buf; +import org.scribble.util.Caller; + +import http.longvers.HttpLong.Http.Http; +import http.longvers.HttpLong.Http.roles.C; +import http.longvers.HttpLong.Http.statechans.C.Http_C_1; +import http.longvers.HttpLong.Http.statechans.C.Http_C_3; +import http.longvers.HttpLong.Http.statechans.C.Http_C_4_Cases; +import http.longvers.HttpLong.Http.statechans.C.Http_C_5; +import http.longvers.HttpLong.Http.statechans.C.Http_C_5_Cases; +import http.longvers.HttpLong.Http.statechans.C.ioifaces.Branch_C_S_200__S_404.Branch_C_S_200__S_404_Enum; +import http.longvers.message.Body; +import http.longvers.message.HttpLongMessageFormatter; +import http.longvers.message.client.Host; +import http.longvers.message.client.RequestLine; +import http.longvers.message.server.ContentLength; +import http.longvers.message.server.ContentType; +import http.longvers.message.server.HttpVersion; +import http.longvers.message.server.Server; + + +/** TODO + * + * Cannot parse header field: Cache-Control: max-age=604800 + * at http.longvers.message.HttpLongMessageFormatter.fromBytes(HttpLongMessageFormatter.java:198) + */ + +public class HttpLongC +{ + public HttpLongC() throws Exception + { + run(); + } + + public static void main(String[] args) throws Exception + { + new HttpLongC(); + } + + public void run() throws Exception + { + Http http = new Http(); + try (MPSTEndpoint client = new MPSTEndpoint<>(http, C, + new HttpLongMessageFormatter())) { + + String host = "example.com"; int port = 80; String file = "/~rhu/"; + //String host = "localhost"; int port = 8080; String file = "/"; + + client.request(S, SocketChannelEndpoint::new, host, port); + + doResponse( + doRequest(new Http_C_1(client), host, file) + ); + } + } + + private Http_C_3 doRequest(Http_C_1 s1, String host, String file) throws Exception + { + return s1.send(S, new RequestLine(file, "1.1")) + .send(S, new Host(host)) + .send(S, new Body("")); + } + + private void doResponse(Http_C_3 s3) throws Exception + { + Http_C_4_Cases s4cases = s3.async(S, HTTPV).branch(S); + switch (s4cases.op) + { + case _200: doResponseAux(s4cases.receive(_200)); break; + case _404: doResponseAux(s4cases.receive(_404)); break; + default: throw new RuntimeException("[TODO]: " + s4cases.op); + } + } + + private void doResponseAux(Http_C_5 s5) throws Exception + { + Http_C_5_Cases cases = s5.branch(S); + switch (cases.op) + { + case ACCEPTR: doResponseAux(cases.receive(ACCEPTR)); break; + case CONTENTL: doResponseAux(cases.receive(CONTENTL)); break; + case CONTENTT: doResponseAux(cases.receive(CONTENTT)); break; + case DATE: doResponseAux(cases.receive(DATE)); break; + case ETAG: doResponseAux(cases.receive(ETAG)); break; + case LASTM: doResponseAux(cases.receive(LASTM)); break; + case SERVER: doResponseAux(cases.receive(SERVER)); break; + case STRICTTS: doResponseAux(cases.receive(STRICTTS)); break; + case VARY: doResponseAux(cases.receive(VARY)); break; + case VIA: doResponseAux(cases.receive(VIA)); break; + case BODY: + { + Buf buf_body = new Buf<>(); + cases.receive(BODY, buf_body); + System.out.println(buf_body.val.getBody()); + return; + } + default: throw new RuntimeException("[TODO]: " + cases.op); + } + } + + public void run1() throws Exception + { + Buf b_vers = new Buf<>(); + Buf b_clen = new Buf<>(); + Buf b_ctype = new Buf<>(); + Buf b_body = new Buf<>(); + Buf b_serv = new Buf<>(); + + Http http = new Http(); + try (MPSTEndpoint se = new MPSTEndpoint<>(http, Http.C, new HttpLongMessageFormatter())) + { + String host = "www.doc.ic.ac.uk"; int port = 80; + //String host = "localhost"; int port = 8080; + + se.request(S, SocketChannelEndpoint::new, host, port); + + Http_C_1 s1 = new Http_C_1(se); + + Http_C_4_Cases s4cases = + s1.send(S, new RequestLine("/~rhu/", "1.1")) + .send(S, new Host(host)) + .send(S, new Body("")) + .receive(S, HTTPV, b_vers) + .branch(S); + Http_C_5 s5 = // S?{ 200: ..., 404: ..., ... } + (s4cases.op == Branch_C_S_200__S_404_Enum._200) ? s4cases.receive(_200) + : (s4cases.op == Branch_C_S_200__S_404_Enum._404) ? s4cases.receive(_404) + : new Caller().call(() -> { throw new RuntimeException("Unknown status code: " + s4cases.op); }); + + Y: while (true) + { + Http_C_5_Cases cases = s5.branch(S); + switch (cases.op) + { + case ACCEPTR: + { + s5 = cases.receive(ACCEPTR); + break; + } + case BODY: + { + cases.receive(BODY, b_body); + System.out.println(b_body.val.getBody()); + break Y; + } + case CONTENTL: + { + s5 = cases.receive(CONTENTL, b_clen); + break; + } + case CONTENTT: + { + s5 = cases.receive(CONTENTT, b_ctype); + break; + } + case DATE: + { + s5 = cases.receive(DATE); + break; + } + case ETAG: + { + s5 = cases.receive(ETAG); + break; + } + case LASTM: + { + s5 = cases.receive(LASTM); + break; + } + case SERVER: + { + s5 = cases.receive(SERVER, b_serv); + break; + } + case STRICTTS: + { + s5 = cases.receive(STRICTTS); + break; + } + case VARY: + { + s5 = cases.receive(VARY); + break; + } + case VIA: + { + s5 = cases.receive(VIA); + break; + } + } + } + } + } +} diff --git a/scribble-demos/scrib/http/src/http/longvers/HttpLongS.java b/scribble-demos/scrib/http/src/http/longvers/HttpLongS.java new file mode 100644 index 000000000..375d8c8cf --- /dev/null +++ b/scribble-demos/scrib/http/src/http/longvers/HttpLongS.java @@ -0,0 +1,144 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package http.longvers; + +import org.scribble.runtime.net.ScribServerSocket; +import org.scribble.runtime.net.SocketChannelServer; +import org.scribble.runtime.session.MPSTEndpoint; +import org.scribble.runtime.util.Buf; + +import http.longvers.HttpLong.Http.Http; +import http.longvers.HttpLong.Http.roles.S; +import http.longvers.HttpLong.Http.statechans.S.Http_S_1; +import http.longvers.HttpLong.Http.statechans.S.Http_S_2; +import http.longvers.HttpLong.Http.statechans.S.Http_S_2_Cases; +import http.longvers.message.Body; +import http.longvers.message.HttpLongMessageFormatter; +import http.longvers.message.client.Accept; +import http.longvers.message.client.AcceptEncoding; +import http.longvers.message.client.AcceptLanguage; +import http.longvers.message.client.Connection; +import http.longvers.message.client.Cookie; +import http.longvers.message.client.DoNotTrack; +import http.longvers.message.client.Host; +import http.longvers.message.client.RequestLine; +import http.longvers.message.client.UpgradeInsecureRequests; +import http.longvers.message.client.UserAgent; +import http.longvers.message.server.ContentLength; +import http.longvers.message.server.HttpVersion; +import http.longvers.message.server._200; + +public class HttpLongS +{ + public HttpLongS() + { + + } + + public static void main(String[] args) throws Exception + { + Buf b_reql = new Buf<>(); + Buf b_host = new Buf<>(); + Buf b_usera = new Buf<>(); + Buf b_acc = new Buf<>(); + Buf b_accl = new Buf<>(); + Buf b_acce = new Buf<>(); + Buf b_dnt = new Buf<>(); + Buf b_conn = new Buf<>(); + Buf b_upgradeir = new Buf<>(); + Buf b_cookie = new Buf<>(); + Buf b_body = new Buf<>(); + + try (ScribServerSocket ss = new SocketChannelServer(8080)) + { + while (true) + { + Http http = new Http(); + try (MPSTEndpoint se = new MPSTEndpoint<>(http, Http.S, new HttpLongMessageFormatter())) + { + se.accept(ss, Http.C); + + Http_S_1 s1 = new Http_S_1(se); + Http_S_2 s2 = s1.receive(Http.C, Http.REQUESTL, b_reql); + + System.out.println("Requested: " + b_reql.val); + + X: while (true) + { + Http_S_2_Cases s2cases = s2.branch(Http.C); + switch (s2cases.op) + { + case ACCEPT: + { + s2 = s2cases.receive(Http.ACCEPT, b_acc); + break; + } + case ACCEPTE: + { + s2 = s2cases.receive(Http.ACCEPTE, b_acce); + break; + } + case ACCEPTL: + { + s2 = s2cases.receive(Http.ACCEPTL, b_accl); + break; + } + case BODY: + { + //String body = ""; + String body = "Hello, world!"; + s2cases.receive(Http.BODY, b_body) + .send(Http.C, new HttpVersion("1.1")) + .send(Http.C, new _200("OK")) + .send(Http.C, new ContentLength(body.length())) + .send(Http.C, new Body(body)); + break X; + } + case CONNECTION: + { + s2 = s2cases.receive(Http.CONNECTION, b_conn); + break; + } + case DNT: + { + s2 = s2cases.receive(Http.DNT, b_dnt); + break; + } + case UPGRADEIR: + { + s2 = s2cases.receive(Http.UPGRADEIR, b_upgradeir); + break; + } + case COOKIE: + { + s2 = s2cases.receive(Http.COOKIE, b_cookie); + break; + } + case HOST: + { + s2 = s2cases.receive(Http.HOST, b_host); + break; + } + case USERA: + { + s2 = s2cases.receive(Http.USERA, b_usera); + break; + } + } + } + } + } + } + } +} diff --git a/scribble-demos/scrib/http/src/http/longvers/message/Body.java b/scribble-demos/scrib/http/src/http/longvers/message/Body.java new file mode 100644 index 000000000..2c4cb94ae --- /dev/null +++ b/scribble-demos/scrib/http/src/http/longvers/message/Body.java @@ -0,0 +1,32 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package http.longvers.message; + +import http.longvers.HttpLong.Http.Http; + +public class Body extends HttpLongMessage +{ + private static final long serialVersionUID = 1L; + + public Body(String body) + { + super(Http.BODY, body); + } + + @Override + public byte[] toBytes() + { + return (getOpString(this.op) + getBody()).getBytes(HttpLongMessageFormatter.cs); // opString should be empty + } +} diff --git a/scribble-demos/scrib/http/src/http/longvers/message/HeaderField.java b/scribble-demos/scrib/http/src/http/longvers/message/HeaderField.java new file mode 100644 index 000000000..0c6774462 --- /dev/null +++ b/scribble-demos/scrib/http/src/http/longvers/message/HeaderField.java @@ -0,0 +1,26 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package http.longvers.message; + +import org.scribble.core.type.name.Op; + +public abstract class HeaderField extends HttpLongMessage +{ + private static final long serialVersionUID = 1L; + + public HeaderField(Op name, String value) + { + super(name, ": " + value + " "); + } +} diff --git a/scribble-demos/scrib/http/src/http/longvers/message/HttpLongMessage.java b/scribble-demos/scrib/http/src/http/longvers/message/HttpLongMessage.java new file mode 100644 index 000000000..2dea67fc9 --- /dev/null +++ b/scribble-demos/scrib/http/src/http/longvers/message/HttpLongMessage.java @@ -0,0 +1,154 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package http.longvers.message; + +import org.scribble.runtime.message.ScribMessage; +import org.scribble.core.type.name.Op; + +import http.longvers.HttpLong.Http.Http; + +// Unlike ScribMessage, HttpMessage is not actually "sent", but we use it as the base class since the socket API takes ScribMessages +public abstract class HttpLongMessage extends ScribMessage +{ + private static final long serialVersionUID = 1L; + + // " " after ops done by HeaderField + public static final String GET = "GET"; + public static final String HTTP = "HTTP"; + public static final String HOST = "Host"; + + public static final String USER_AGENT = "User-Agent"; + public static final String ACCEPT = "Accept"; + public static final String ACCEPT_LANGUAGE = "Accept-Language"; + public static final String ACCEPT_ENCODING = "Accept-Encoding"; + public static final String DO_NOT_TRACK = "DNT"; + public static final String CONNECTION = "Connection"; + + public static final String UPGRADE_INSECURE_REQUESTS = "Upgrade-Insecure-Requests"; + public static final String COOKIE = "Cookie"; + + public static final String DATE = "Date"; + public static final String CONTENT_TYPE = "Content-Type"; + public static final String _404 = "404"; + public static final String _200 = "200"; + public static final String ACCEPT_RANGES = "Accept-Ranges"; + public static final String LAST_MODIFIED = "Last-Modified"; + public static final String VARY = "Vary"; + public static final String SERVER = "Server"; + public static final String STRICT_TRANSPORT_SECURITY = "Strict-Transport-Security"; + public static final String VIA = "Via"; + public static final String ETAG = "ETag"; + public static final String CONTENT_LENGTH = "Content-Length"; + + protected static final String CRLF = "\r\n"; + + public HttpLongMessage(Op op) + { + super(op); + } + + public HttpLongMessage(Op op, String body) + { + super(op, body); + } + + public String getBody() + { + return (this.payload.length == 0) ? "" : (String) this.payload[0]; + } + + public byte[] toBytes() + { + return (getOpString(this.op) + getBody() + HttpLongMessage.CRLF).getBytes(HttpLongMessageFormatter.cs); // Can give "utf-8" as arg directly + } + + @Override + public String toString() + { + return new String(toBytes()); + } + + // " " after ops done by HeaderField + protected static String getOpString(Op op) + { + if (op.equals(Http.CONTENTL)) + { + return HttpLongMessage.CONTENT_LENGTH; + } + else if (op.equals(Http.ETAG)) + { + return HttpLongMessage.ETAG; + } + else if (op.equals(Http.BODY)) + { + return HttpLongMessage.CRLF; // This CRLF "op" actually enacts the empty line for end-of-headers + } + else if (op.equals(Http.VIA)) + { + return HttpLongMessage.VIA; + } + else if (op.equals(Http.SERVER)) + { + return HttpLongMessage.SERVER; + } + else if (op.equals(Http.VARY)) + { + return HttpLongMessage.VARY; + } + else if (op.equals(HttpLongMessage.CRLF)) + { + return ""; + } + else if (op.equals(Http.REQUESTL)) // FIXME: not just GET (POST..) + { + return HttpLongMessage.GET; + } + else if (op.equals(Http.LASTM)) + { + return HttpLongMessage.LAST_MODIFIED; + } + else if (op.equals(Http.ACCEPTR)) + { + return HttpLongMessage.ACCEPT_RANGES; + } + else if (op.equals(Http.HOST)) + { + return HttpLongMessage.HOST; + } + else if (op.equals(Http.HTTPV)) + { + return HttpLongMessage.HTTP; + } + else if (op.equals(Http._200)) + { + return HttpLongMessage._200; + } + else if (op.equals(Http._404)) + { + return HttpLongMessage._404; + } + else if (op.equals(Http.CONTENTT)) + { + return HttpLongMessage.CONTENT_TYPE; + } + else if (op.equals(Http.DATE)) + { + return HttpLongMessage.DATE; + } + else + { + throw new RuntimeException("TODO: " + op); + } + } +} diff --git a/scribble-demos/scrib/http/src/http/longvers/message/HttpLongMessageFormatter.java b/scribble-demos/scrib/http/src/http/longvers/message/HttpLongMessageFormatter.java new file mode 100644 index 000000000..6c4ecdb98 --- /dev/null +++ b/scribble-demos/scrib/http/src/http/longvers/message/HttpLongMessageFormatter.java @@ -0,0 +1,416 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package http.longvers.message; + +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.Charset; + +import org.scribble.runtime.message.ScribMessage; +import org.scribble.runtime.message.ScribMessageFormatter; + +import http.longvers.message.client.Accept; +import http.longvers.message.client.AcceptEncoding; +import http.longvers.message.client.AcceptLanguage; +import http.longvers.message.client.Connection; +import http.longvers.message.client.Cookie; +import http.longvers.message.client.DoNotTrack; +import http.longvers.message.client.Host; +import http.longvers.message.client.RequestLine; +import http.longvers.message.client.UpgradeInsecureRequests; +import http.longvers.message.client.UserAgent; +import http.longvers.message.server.AcceptRanges; +import http.longvers.message.server.ContentLength; +import http.longvers.message.server.ContentType; +import http.longvers.message.server.Date; +import http.longvers.message.server.ETag; +import http.longvers.message.server.HttpVersion; +import http.longvers.message.server.LastModified; +import http.longvers.message.server.Server; +import http.longvers.message.server.StrictTransportSecurity; +import http.longvers.message.server.Vary; +import http.longvers.message.server.Via; +import http.longvers.message.server._200; +import http.longvers.message.server._404; + +// FIXME: investigate if factoring out the C/S deserialization simplifies things +public class HttpLongMessageFormatter implements ScribMessageFormatter +{ + public static final Charset cs = Charset.forName("UTF8"); + //private static CharsetDecoder cd = cs.newDecoder(); + + private int len = -1; + + public HttpLongMessageFormatter() + { + + } + + @Override + public byte[] toBytes(ScribMessage m) throws IOException + { + return ((HttpLongMessage) m).toBytes(); + } + + @Override + public ScribMessage fromBytes(ByteBuffer bb) throws IOException, ClassNotFoundException + { + bb.flip(); + int rem = bb.remaining(); + if (rem < 2) + { + bb.compact(); + return null; + } + + int pos = bb.position(); + String front = new String(new byte[] { bb.get(pos), bb.get(pos + 1) }, HttpLongMessageFormatter.cs); + if (front.equals(HttpLongMessage.CRLF)) // not sound? -- actually, due to sess types it is safe (same reason why interpreting any of these messages without context is sound) -- parsing doesn't have to follow the *full protocol* BNF any more to be sound + { + if (this.len == -1) + { + return new Body(""); + } + if (rem < this.len + 2) + { + bb.compact(); + return null; + } + //String body = readLine(dis) + HttpMessage.CRLF; // HACK: assumes at least 1 CRLF + StringBuffer sb = new StringBuffer(); + //for (int i = body.length(); i < this.len; i++) + for (int i = 0; i < this.len; i++) + { + sb.append((char) bb.get()); + } + this.len = -1; + //return new Body(body + sb.toString()); + return new Body(sb.toString()); + } + + if (rem < pos + 4) + { + bb.compact(); + return null; + } + //byte[] bs = new byte[2]; + //dis.readFully(bs); + front += new String(new byte[] { bb.get(pos + 2), bb.get(pos + 3) }, HttpLongMessageFormatter.cs); + // FIXME: factor out with HttpMessage op strings + int code = isStatusCode(front); + if (code > -1) + { + String reason = readLine(bb, pos + 4).trim(); // Whitespace already built into the message classes + bb.compact(); + if (reason == null) + { + return null; + } + switch (code) + { + case 200: return new _200(reason); + case 404: return new _404(reason); + default: throw new RuntimeException("Unknown status code: " + code); + } + } + else if (front.startsWith(HttpLongMessage.GET)) + { + String reql = readLine(bb, pos + 4).trim(); + bb.compact(); + if (reql == null) + { + return null; + } + String target = reql.substring(0, reql.indexOf(' ')); + String vers = reql.substring(reql.indexOf(' ') + 1).trim(); + vers = vers.substring(vers.indexOf('/') + 1); + return new RequestLine(target, vers); + } + else if (front.equals(HttpLongMessage.HTTP)) + { + //dis.read(); // '/' + if (rem < pos + 5) + { + bb.compact(); + return null; + } + String word = readWord(bb, pos + 5); + bb.compact(); + if (word == null) + { + return null; + } + return new HttpVersion(word); + } + else + { + String line = readLine(bb, pos + 4); + bb.compact(); + if (line == null) + { + return null; + } + line = front + line; + int colon = line.indexOf(':'); + if (colon > -1) + { + String name = line.substring(0, colon); + String value = line.substring(colon + 1).trim(); // Whitespace already built into the message classes + switch (name) + { + case HttpLongMessage.HOST: return new Host("value"); + case HttpLongMessage.USER_AGENT: return new UserAgent(value); + case HttpLongMessage.ACCEPT: return new Accept(value); + case HttpLongMessage.ACCEPT_LANGUAGE: return new AcceptLanguage(value); + case HttpLongMessage.ACCEPT_ENCODING: return new AcceptEncoding(value); + case HttpLongMessage.DO_NOT_TRACK: return new DoNotTrack(Integer.parseInt(value)); + case HttpLongMessage.CONNECTION: return new Connection(value); + case HttpLongMessage.UPGRADE_INSECURE_REQUESTS: return new UpgradeInsecureRequests(Integer.parseInt(value)); + case HttpLongMessage.COOKIE: return new Cookie(value); + + case HttpLongMessage.DATE: return new Date(value); + case HttpLongMessage.SERVER: return new Server(value); + case HttpLongMessage.STRICT_TRANSPORT_SECURITY: return new StrictTransportSecurity(value); + case HttpLongMessage.LAST_MODIFIED: return new LastModified(value); + case HttpLongMessage.ETAG: return new ETag(value); + case HttpLongMessage.ACCEPT_RANGES: return new AcceptRanges(value); + case HttpLongMessage.CONTENT_LENGTH: + { + len = Integer.parseInt(value.trim()); + return new ContentLength(len); + } + case HttpLongMessage.VARY: return new Vary(value); + case HttpLongMessage.CONTENT_TYPE: return new ContentType(value); + case HttpLongMessage.VIA: return new Via(value); + default: { + //throw new RuntimeException("Cannot parse header field: " + line); + System.err.println("Cannot parse header field, attempting to skip: " + line); + return fromBytes(bb); + } + } + } + else + { + throw new RuntimeException("Cannot parse message: " + line); + } + } + } + + private static String readLine(ByteBuffer bb, int i) throws IOException + { + StringBuilder sb = new StringBuilder(); + for (int limit = bb.limit(); i <= limit; ) + { + char c = (char) bb.get(i++); // readChar is not the same + sb.append(c); + if (c == '\r') + { + if (i > limit) + { + return null; + } + c = (char) bb.get(i++); + sb.append(c); + if (c == '\n') + { + bb.position(i); + return sb.substring(0, sb.length() - 2).toString(); + } + } + } + return null; + } + + private static String readWord(ByteBuffer bb, int i) throws IOException + { + StringBuilder sb = new StringBuilder(); + for (int limit = bb.limit(); i <= limit; ) + { + char c = (char) bb.get(i++); + if (c == ' ') + { + bb.position(i); + return sb.toString(); + } + sb.append(c); + } + return null; + } + + //private int isStatusCode(byte[] bs) + private int isStatusCode(String front) + { + String code = ""; + for (int i = 0; i < 4; i++) + { + //char c = (char) bs[i]; + char c = front.charAt(i); + if (i < 3) + { + if (c < '0' || c > '9') + { + return -1; + } + code += c; + } + else + { + if (c != ' ') + { + return -1; + } + } + } + return Integer.parseInt(code); + } + + + + // FIXME: delete + @Deprecated @Override + public void writeMessage(DataOutputStream dos, ScribMessage m) throws IOException + { + dos.write(((HttpLongMessage) m).toBytes()); + dos.flush(); + } + + @Deprecated @Override + public ScribMessage readMessage(DataInputStream dis) throws IOException + { + byte[] bs = new byte[2]; + dis.readFully(bs); + String front = new String(bs, HttpLongMessageFormatter.cs); + if (front.equals(HttpLongMessage.CRLF)) // not sound? -- actually, due to sess types it is safe (same reason why interpreting any of these messages without context is sound) -- parsing doesn't have to follow the *full protocol* BNF any more to be sound + { + if (this.len == -1) + { + return new Body(""); + } + //String body = readLine(dis) + HttpMessage.CRLF; // HACK: assumes at least 1 CRLF + StringBuffer sb = new StringBuffer(); + //for (int i = body.length(); i < this.len; i++) + for (int i = 0; i < this.len; i++) + { + sb.append((char) dis.read()); + } + this.len = -1; + //return new Body(body + sb.toString()); + return new Body(sb.toString()); + } + + bs = new byte[2]; + dis.readFully(bs); + front += new String(bs, HttpLongMessageFormatter.cs); + // FIXME: factor out with HttpMessage op strings + int code = isStatusCode(front); + if (code > -1) + { + String reason = readLine(dis).trim(); // Whitespace already built into the message classes + switch (code) + { + case 200: return new _200(reason); + case 404: return new _404(reason); + default: throw new RuntimeException("Unknown status code: " + code); + } + } + else if (front.startsWith(HttpLongMessage.GET)) + { + String reql = readLine(dis).trim(); + String target = reql.substring(0, reql.indexOf(' ')); + String vers = reql.substring(reql.indexOf(' ') + 1).trim(); + vers = vers.substring(vers.indexOf('/') + 1); + return new RequestLine(target, vers); + } + else if (front.equals(HttpLongMessage.HTTP)) + { + dis.read(); // '/' + String word = readWord(dis); + return new HttpVersion(word); + } + else + { + String line = front + readLine(dis); + int colon = line.indexOf(':'); + if (colon > -1) + { + String name = line.substring(0, colon); + String value = line.substring(colon + 1).trim(); // Whitespace already built into the message classes + switch (name) + { + case HttpLongMessage.HOST: return new Host("value"); + case HttpLongMessage.USER_AGENT: return new UserAgent(value); + case HttpLongMessage.ACCEPT: return new Accept(value); + case HttpLongMessage.ACCEPT_LANGUAGE: return new AcceptLanguage(value); + case HttpLongMessage.ACCEPT_ENCODING: return new AcceptEncoding(value); + case HttpLongMessage.DO_NOT_TRACK: return new DoNotTrack(Integer.parseInt(value)); + case HttpLongMessage.CONNECTION: return new Connection(value); + + case HttpLongMessage.DATE: return new Date(value); + case HttpLongMessage.SERVER: return new Server(value); + case HttpLongMessage.LAST_MODIFIED: return new LastModified(value); + case HttpLongMessage.ETAG: return new ETag(value); + case HttpLongMessage.ACCEPT_RANGES: return new AcceptRanges(value); + case HttpLongMessage.CONTENT_LENGTH: + { + len = Integer.parseInt(value.trim()); + return new ContentLength(len); + } + case HttpLongMessage.VARY: return new Vary(value); + case HttpLongMessage.CONTENT_TYPE: return new ContentType(value); + case HttpLongMessage.VIA: return new Via(value); + default: throw new RuntimeException("Cannot parse header field: " + line); + } + } + else + { + throw new RuntimeException("Cannot parse message: " + line); + } + } + } + + private static String readLine(DataInputStream dis) throws IOException + { + StringBuilder sb = new StringBuilder(); + for (; true; ) + { + char c = (char) dis.read(); // readChar is not the same + sb.append(c); + if (c == '\r') + { + c = (char) dis.read(); + sb.append(c); + if (c == '\n') + { + return sb.substring(0, sb.length() - 2).toString(); + } + } + } + } + + private static String readWord(DataInputStream dis) throws IOException + { + StringBuilder sb = new StringBuilder(); + for (; true; ) + { + char c = (char) dis.read(); + if (c == ' ') + { + return sb.toString(); + } + sb.append(c); + } + } +} diff --git a/scribble-demos/scrib/http/src/http/longvers/message/StartLine.java b/scribble-demos/scrib/http/src/http/longvers/message/StartLine.java new file mode 100644 index 000000000..54d86be69 --- /dev/null +++ b/scribble-demos/scrib/http/src/http/longvers/message/StartLine.java @@ -0,0 +1,26 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package http.longvers.message; + +import org.scribble.core.type.name.Op; + +public abstract class StartLine extends HttpLongMessage +{ + private static final long serialVersionUID = 1L; + + public StartLine(Op op, String body) + { + super(op, body); + } +} diff --git a/scribble-demos/scrib/http/src/http/longvers/message/client/Accept.java b/scribble-demos/scrib/http/src/http/longvers/message/client/Accept.java new file mode 100644 index 000000000..9c37257a8 --- /dev/null +++ b/scribble-demos/scrib/http/src/http/longvers/message/client/Accept.java @@ -0,0 +1,27 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package http.longvers.message.client; + +import http.longvers.HttpLong.Http.Http; +import http.longvers.message.HeaderField; + +public class Accept extends HeaderField +{ + private static final long serialVersionUID = 1L; + + public Accept(String text) + { + super(Http.ACCEPT, text); + } +} diff --git a/scribble-demos/scrib/http/src/http/longvers/message/client/AcceptEncoding.java b/scribble-demos/scrib/http/src/http/longvers/message/client/AcceptEncoding.java new file mode 100644 index 000000000..137a409f2 --- /dev/null +++ b/scribble-demos/scrib/http/src/http/longvers/message/client/AcceptEncoding.java @@ -0,0 +1,27 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package http.longvers.message.client; + +import http.longvers.HttpLong.Http.Http; +import http.longvers.message.HeaderField; + +public class AcceptEncoding extends HeaderField +{ + private static final long serialVersionUID = 1L; + + public AcceptEncoding(String text) + { + super(Http.ACCEPTE, text); + } +} diff --git a/scribble-demos/scrib/http/src/http/longvers/message/client/AcceptLanguage.java b/scribble-demos/scrib/http/src/http/longvers/message/client/AcceptLanguage.java new file mode 100644 index 000000000..8d44d5cd2 --- /dev/null +++ b/scribble-demos/scrib/http/src/http/longvers/message/client/AcceptLanguage.java @@ -0,0 +1,27 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package http.longvers.message.client; + +import http.longvers.HttpLong.Http.Http; +import http.longvers.message.HeaderField; + +public class AcceptLanguage extends HeaderField +{ + private static final long serialVersionUID = 1L; + + public AcceptLanguage(String text) + { + super(Http.ACCEPTL, text); + } +} diff --git a/scribble-demos/scrib/http/src/http/longvers/message/client/Connection.java b/scribble-demos/scrib/http/src/http/longvers/message/client/Connection.java new file mode 100644 index 000000000..a464e240a --- /dev/null +++ b/scribble-demos/scrib/http/src/http/longvers/message/client/Connection.java @@ -0,0 +1,27 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package http.longvers.message.client; + +import http.longvers.HttpLong.Http.Http; +import http.longvers.message.HeaderField; + +public class Connection extends HeaderField +{ + private static final long serialVersionUID = 1L; + + public Connection(String text) + { + super(Http.CONNECTION, text); + } +} diff --git a/scribble-demos/scrib/http/src/http/longvers/message/client/Cookie.java b/scribble-demos/scrib/http/src/http/longvers/message/client/Cookie.java new file mode 100644 index 000000000..fee652fd2 --- /dev/null +++ b/scribble-demos/scrib/http/src/http/longvers/message/client/Cookie.java @@ -0,0 +1,27 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package http.longvers.message.client; + +import http.longvers.HttpLong.Http.Http; +import http.longvers.message.HeaderField; + +public class Cookie extends HeaderField +{ + private static final long serialVersionUID = 1L; + + public Cookie(String val) + { + super(Http.COOKIE, val); + } +} diff --git a/scribble-demos/scrib/http/src/http/longvers/message/client/DoNotTrack.java b/scribble-demos/scrib/http/src/http/longvers/message/client/DoNotTrack.java new file mode 100644 index 000000000..7d9734d74 --- /dev/null +++ b/scribble-demos/scrib/http/src/http/longvers/message/client/DoNotTrack.java @@ -0,0 +1,27 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package http.longvers.message.client; + +import http.longvers.HttpLong.Http.Http; +import http.longvers.message.HeaderField; + +public class DoNotTrack extends HeaderField +{ + private static final long serialVersionUID = 1L; + + public DoNotTrack(int val) + { + super(Http.DNT, Integer.toString(val)); + } +} diff --git a/scribble-demos/scrib/http/src/http/longvers/message/client/Host.java b/scribble-demos/scrib/http/src/http/longvers/message/client/Host.java new file mode 100644 index 000000000..de3c6ad7a --- /dev/null +++ b/scribble-demos/scrib/http/src/http/longvers/message/client/Host.java @@ -0,0 +1,27 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package http.longvers.message.client; + +import http.longvers.HttpLong.Http.Http; +import http.longvers.message.HeaderField; + +public class Host extends HeaderField +{ + private static final long serialVersionUID = 1L; + + public Host(String host) + { + super(Http.HOST, host); + } +} diff --git a/scribble-demos/scrib/http/src/http/longvers/message/client/RequestLine.java b/scribble-demos/scrib/http/src/http/longvers/message/client/RequestLine.java new file mode 100644 index 000000000..289ec1aea --- /dev/null +++ b/scribble-demos/scrib/http/src/http/longvers/message/client/RequestLine.java @@ -0,0 +1,29 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package http.longvers.message.client; + +import http.longvers.HttpLong.Http.Http; +import http.longvers.message.StartLine; + + +// FIXME: not just GET +public class RequestLine extends StartLine +{ + private static final long serialVersionUID = 1L; + + public RequestLine(String reqtarget, String vers) + { + super(Http.REQUESTL, " " + reqtarget + " HTTP" + "/" + vers); + } +} diff --git a/scribble-demos/scrib/http/src/http/longvers/message/client/UpgradeInsecureRequests.java b/scribble-demos/scrib/http/src/http/longvers/message/client/UpgradeInsecureRequests.java new file mode 100644 index 000000000..84db1ed7c --- /dev/null +++ b/scribble-demos/scrib/http/src/http/longvers/message/client/UpgradeInsecureRequests.java @@ -0,0 +1,27 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package http.longvers.message.client; + +import http.longvers.HttpLong.Http.Http; +import http.longvers.message.HeaderField; + +public class UpgradeInsecureRequests extends HeaderField +{ + private static final long serialVersionUID = 1L; + + public UpgradeInsecureRequests(int val) + { + super(Http.UPGRADEIR, Integer.toString(val)); + } +} diff --git a/scribble-demos/scrib/http/src/http/longvers/message/client/UserAgent.java b/scribble-demos/scrib/http/src/http/longvers/message/client/UserAgent.java new file mode 100644 index 000000000..03d6e6507 --- /dev/null +++ b/scribble-demos/scrib/http/src/http/longvers/message/client/UserAgent.java @@ -0,0 +1,27 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package http.longvers.message.client; + +import http.longvers.HttpLong.Http.Http; +import http.longvers.message.HeaderField; + +public class UserAgent extends HeaderField +{ + private static final long serialVersionUID = 1L; + + public UserAgent(String text) + { + super(Http.USERA, text); + } +} diff --git a/scribble-demos/scrib/http/src/http/longvers/message/server/AcceptRanges.java b/scribble-demos/scrib/http/src/http/longvers/message/server/AcceptRanges.java new file mode 100644 index 000000000..eac61312a --- /dev/null +++ b/scribble-demos/scrib/http/src/http/longvers/message/server/AcceptRanges.java @@ -0,0 +1,27 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package http.longvers.message.server; + +import http.longvers.HttpLong.Http.Http; +import http.longvers.message.HeaderField; + +public class AcceptRanges extends HeaderField +{ + private static final long serialVersionUID = 1L; + + public AcceptRanges(String text) + { + super(Http.ACCEPTR, text); + } +} diff --git a/scribble-demos/scrib/http/src/http/longvers/message/server/CRLF.java b/scribble-demos/scrib/http/src/http/longvers/message/server/CRLF.java new file mode 100644 index 000000000..3655d546e --- /dev/null +++ b/scribble-demos/scrib/http/src/http/longvers/message/server/CRLF.java @@ -0,0 +1,29 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package http.longvers.message.server; + +import http.longvers.message.HttpLongMessage; + +@Deprecated +public class CRLF extends HttpLongMessage +{ + private static final long serialVersionUID = 1L; + + public CRLF() + { + //super(Http.CRLF, HttpMessage.CRLF); // No: HttpMessage already appends the CRLF + //super(Http.CRLF, ""); + super(null, ""); + } +} diff --git a/scribble-demos/scrib/http/src/http/longvers/message/server/ContentLength.java b/scribble-demos/scrib/http/src/http/longvers/message/server/ContentLength.java new file mode 100644 index 000000000..145380f67 --- /dev/null +++ b/scribble-demos/scrib/http/src/http/longvers/message/server/ContentLength.java @@ -0,0 +1,27 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package http.longvers.message.server; + +import http.longvers.HttpLong.Http.Http; +import http.longvers.message.HeaderField; + +public class ContentLength extends HeaderField +{ + private static final long serialVersionUID = 1L; + + public ContentLength(Integer len) + { + super(Http.CONTENTL, len.toString()); + } +} diff --git a/scribble-demos/scrib/http/src/http/longvers/message/server/ContentType.java b/scribble-demos/scrib/http/src/http/longvers/message/server/ContentType.java new file mode 100644 index 000000000..3ac9797a2 --- /dev/null +++ b/scribble-demos/scrib/http/src/http/longvers/message/server/ContentType.java @@ -0,0 +1,27 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package http.longvers.message.server; + +import http.longvers.HttpLong.Http.Http; +import http.longvers.message.HeaderField; + +public class ContentType extends HeaderField +{ + private static final long serialVersionUID = 1L; + + public ContentType(String type) + { + super(Http.CONTENTT, type); + } +} diff --git a/scribble-demos/scrib/http/src/http/longvers/message/server/Date.java b/scribble-demos/scrib/http/src/http/longvers/message/server/Date.java new file mode 100644 index 000000000..9b087aee7 --- /dev/null +++ b/scribble-demos/scrib/http/src/http/longvers/message/server/Date.java @@ -0,0 +1,27 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package http.longvers.message.server; + +import http.longvers.HttpLong.Http.Http; +import http.longvers.message.HeaderField; + +public class Date extends HeaderField +{ + private static final long serialVersionUID = 1L; + + public Date(String date) + { + super(Http.DATE, date); + } +} diff --git a/scribble-demos/scrib/http/src/http/longvers/message/server/ETag.java b/scribble-demos/scrib/http/src/http/longvers/message/server/ETag.java new file mode 100644 index 000000000..7c510d61a --- /dev/null +++ b/scribble-demos/scrib/http/src/http/longvers/message/server/ETag.java @@ -0,0 +1,27 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package http.longvers.message.server; + +import http.longvers.HttpLong.Http.Http; +import http.longvers.message.HeaderField; + +public class ETag extends HeaderField +{ + private static final long serialVersionUID = 1L; + + public ETag(String tag) + { + super(Http.ETAG, tag); + } +} diff --git a/scribble-demos/scrib/http/src/http/longvers/message/server/HttpVersion.java b/scribble-demos/scrib/http/src/http/longvers/message/server/HttpVersion.java new file mode 100644 index 000000000..5aca34437 --- /dev/null +++ b/scribble-demos/scrib/http/src/http/longvers/message/server/HttpVersion.java @@ -0,0 +1,34 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package http.longvers.message.server; + +import http.longvers.HttpLong.Http.Http; +import http.longvers.message.HttpLongMessage; +import http.longvers.message.HttpLongMessageFormatter; + +public class HttpVersion extends HttpLongMessage +{ + private static final long serialVersionUID = 1L; + + public HttpVersion(String version) + { + super(Http.HTTPV, "/" + version); + } + + @Override + public byte[] toBytes() + { + return (getOpString(op) + getBody() + " ").getBytes(HttpLongMessageFormatter.cs); + } +} diff --git a/scribble-demos/scrib/http/src/http/longvers/message/server/LastModified.java b/scribble-demos/scrib/http/src/http/longvers/message/server/LastModified.java new file mode 100644 index 000000000..3791725c6 --- /dev/null +++ b/scribble-demos/scrib/http/src/http/longvers/message/server/LastModified.java @@ -0,0 +1,27 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package http.longvers.message.server; + +import http.longvers.HttpLong.Http.Http; +import http.longvers.message.HeaderField; + +public class LastModified extends HeaderField +{ + private static final long serialVersionUID = 1L; + + public LastModified(String date) + { + super(Http.LASTM, date); + } +} diff --git a/scribble-demos/scrib/http/src/http/longvers/message/server/Server.java b/scribble-demos/scrib/http/src/http/longvers/message/server/Server.java new file mode 100644 index 000000000..4db3a69ca --- /dev/null +++ b/scribble-demos/scrib/http/src/http/longvers/message/server/Server.java @@ -0,0 +1,27 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package http.longvers.message.server; + +import http.longvers.HttpLong.Http.Http; +import http.longvers.message.HeaderField; + +public class Server extends HeaderField +{ + private static final long serialVersionUID = 1L; + + public Server(String server) + { + super(Http.SERVER, server); + } +} diff --git a/scribble-demos/scrib/http/src/http/longvers/message/server/StatusCode.java b/scribble-demos/scrib/http/src/http/longvers/message/server/StatusCode.java new file mode 100644 index 000000000..730d707cf --- /dev/null +++ b/scribble-demos/scrib/http/src/http/longvers/message/server/StatusCode.java @@ -0,0 +1,28 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package http.longvers.message.server; + +import org.scribble.core.type.name.Op; + +import http.longvers.message.HttpLongMessage; + +public abstract class StatusCode extends HttpLongMessage +{ + private static final long serialVersionUID = 1L; + + public StatusCode(Op code, String reason) + { + super(code, " " + reason); + } +} diff --git a/scribble-demos/scrib/http/src/http/longvers/message/server/StrictTransportSecurity.java b/scribble-demos/scrib/http/src/http/longvers/message/server/StrictTransportSecurity.java new file mode 100644 index 000000000..9db70f2b6 --- /dev/null +++ b/scribble-demos/scrib/http/src/http/longvers/message/server/StrictTransportSecurity.java @@ -0,0 +1,28 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package http.longvers.message.server; + +import http.longvers.HttpLong.Http.Http; +import http.longvers.message.HeaderField; + +public class StrictTransportSecurity extends HeaderField +{ + private static final long serialVersionUID = 1L; + + public StrictTransportSecurity(String server) + { + super(Http.STRICTTS, server); + //super(Http.STRICT_TRANSPORT_SECURITY, server); + } +} diff --git a/scribble-demos/scrib/http/src/http/longvers/message/server/Vary.java b/scribble-demos/scrib/http/src/http/longvers/message/server/Vary.java new file mode 100644 index 000000000..db8a53d41 --- /dev/null +++ b/scribble-demos/scrib/http/src/http/longvers/message/server/Vary.java @@ -0,0 +1,27 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package http.longvers.message.server; + +import http.longvers.HttpLong.Http.Http; +import http.longvers.message.HeaderField; + +public class Vary extends HeaderField +{ + private static final long serialVersionUID = 1L; + + public Vary(String text) + { + super(Http.VARY, text); + } +} diff --git a/scribble-demos/scrib/http/src/http/longvers/message/server/Via.java b/scribble-demos/scrib/http/src/http/longvers/message/server/Via.java new file mode 100644 index 000000000..cbae6a33c --- /dev/null +++ b/scribble-demos/scrib/http/src/http/longvers/message/server/Via.java @@ -0,0 +1,27 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package http.longvers.message.server; + +import http.longvers.HttpLong.Http.Http; +import http.longvers.message.HeaderField; + +public class Via extends HeaderField +{ + private static final long serialVersionUID = 1L; + + public Via(String text) + { + super(Http.VIA, text); + } +} diff --git a/scribble-demos/scrib/http/src/http/longvers/message/server/_200.java b/scribble-demos/scrib/http/src/http/longvers/message/server/_200.java new file mode 100644 index 000000000..7d7dd1638 --- /dev/null +++ b/scribble-demos/scrib/http/src/http/longvers/message/server/_200.java @@ -0,0 +1,26 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package http.longvers.message.server; + +import http.longvers.HttpLong.Http.Http; + +public class _200 extends StatusCode +{ + private static final long serialVersionUID = 1L; + + public _200(String reason) + { + super(Http._200, reason); + } +} diff --git a/scribble-demos/scrib/http/src/http/longvers/message/server/_404.java b/scribble-demos/scrib/http/src/http/longvers/message/server/_404.java new file mode 100644 index 000000000..8e8d3114e --- /dev/null +++ b/scribble-demos/scrib/http/src/http/longvers/message/server/_404.java @@ -0,0 +1,26 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package http.longvers.message.server; + +import http.longvers.HttpLong.Http.Http; + +public class _404 extends StatusCode +{ + private static final long serialVersionUID = 1L; + + public _404(String reason) + { + super(Http._404, reason); + } +} diff --git a/scribble-demos/scrib/http/src/http/shortvers/HttpShort.scr b/scribble-demos/scrib/http/src/http/shortvers/HttpShort.scr new file mode 100644 index 000000000..42de41bc9 --- /dev/null +++ b/scribble-demos/scrib/http/src/http/shortvers/HttpShort.scr @@ -0,0 +1,39 @@ +//$ ./scribblec.sh -ip scribble-demos/scrib/http/src -d scribble-demos/scrib/http/src scribble-demos/scrib/http/src/http/shortvers/HttpShort.scr -api Http C +//$ javadoc -cp scribble-core/target/classes:scribble-runtime/target/classes:scribble-demos/scrib/http/src/ scribble-demos/scrib/http/src/http/shortvers/*.java -subpackages http.shortvers.HttpShort.Http -d scribble-demos/scrib/http/javadoc/shortvers + +module http.shortvers.HttpShort; + +/*Connected to www.doc.ic.ac.uk. +Escape character is '^]'. +GET /~rhu/ HTTP/1.1 +host: www.doc.ic.ac.uk + +HTTP/1.1 200 OK // 200 is a separate message +Date: Mon, 13 Jun 2016 19:42:34 GMT +Server: Apache +Strict-Transport-Security: max-age=31536000; preload; includeSubDomains +Strict-Transport-Security: max-age=31536000; preload; includeSubDomains // BUG? (Apache configuration) +Last-Modified: Thu, 14 Apr 2016 12:46:24 GMT +ETag: "74a-53071482f6e0f" +Accept-Ranges: bytes +Content-Length: 1866 // Not using Transfer-Encoding: Chunked +Vary: Accept-Encoding +Content-Type: text/html +Via: 1.1 www.doc.ic.ac.uk*/ + + +sig "http.shortvers.message.client.Request" + from "http/shortvers/message/Request.java" + as REQUEST; + +sig "http.shortvers.message.server.Response" + from "http/shortvers/message/Response.java" + as RESPONSE; + + +// Could use RequestResponse subproto +global protocol Http(role C, role S) +{ + REQUEST from C to S; + RESPONSE from S to C; +} diff --git a/scribble-demos/scrib/http/src/http/shortvers/HttpShortC.java b/scribble-demos/scrib/http/src/http/shortvers/HttpShortC.java new file mode 100644 index 000000000..d863860e1 --- /dev/null +++ b/scribble-demos/scrib/http/src/http/shortvers/HttpShortC.java @@ -0,0 +1,61 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package http.shortvers; + +import static http.shortvers.HttpShort.Http.Http.C; +import static http.shortvers.HttpShort.Http.Http.RESPONSE; +import static http.shortvers.HttpShort.Http.Http.S; + +import org.scribble.runtime.util.Buf; +import org.scribble.runtime.session.MPSTEndpoint; +import org.scribble.runtime.net.SocketChannelEndpoint; + +import http.shortvers.HttpShort.Http.Http; +import http.shortvers.HttpShort.Http.statechans.C.Http_C_1; +import http.shortvers.HttpShort.Http.roles.C; +import http.shortvers.message.HttpShortMessageFormatter; +import http.shortvers.message.client.Request; +import http.shortvers.message.server.Response; + +public class HttpShortC +{ + public HttpShortC() throws Exception + { + run(); + } + + public static void main(String[] args) throws Exception + { + new HttpShortC(); + } + + public void run() throws Exception + { + Http http = new Http(); + try (MPSTEndpoint client = new MPSTEndpoint<>(http, C, new HttpShortMessageFormatter())) + { + String host = "example.com"; int port = 80; String file = "/"; + //String host = "localhost"; int port = 8080; String file = "/"; + + client.request(S, SocketChannelEndpoint::new, host, port); + + Buf buf = new Buf<>(); + new Http_C_1(client) + .send(S, new Request(file, "1.1", host)) + .receive(S, RESPONSE, buf); + + System.out.println("Response:\n" + buf.val); + } + } +} diff --git a/scribble-demos/scrib/http/src/http/shortvers/HttpShortS.java b/scribble-demos/scrib/http/src/http/shortvers/HttpShortS.java new file mode 100644 index 000000000..03161daf1 --- /dev/null +++ b/scribble-demos/scrib/http/src/http/shortvers/HttpShortS.java @@ -0,0 +1,69 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package http.shortvers; + +import static http.shortvers.HttpShort.Http.Http.C; +import static http.shortvers.HttpShort.Http.Http.REQUEST; +import static http.shortvers.HttpShort.Http.Http.S; + +import java.io.IOException; + +import org.scribble.main.ScribRuntimeException; +import org.scribble.runtime.net.ScribServerSocket; +import org.scribble.runtime.net.SocketChannelServer; +import org.scribble.runtime.session.MPSTEndpoint; +import org.scribble.runtime.util.Buf; + +import http.shortvers.HttpShort.Http.Http; +import http.shortvers.HttpShort.Http.roles.S; +import http.shortvers.HttpShort.Http.statechans.S.Http_S_1; +import http.shortvers.HttpShort.Http.statechans.S.Http_S_2; +import http.shortvers.message.HttpShortMessageFormatter; +import http.shortvers.message.client.Request; +import http.shortvers.message.server.Response; + +public class HttpShortS +{ + public HttpShortS() + { + + } + + public static void main(String[] args) throws IOException + { + try (ScribServerSocket ss = new SocketChannelServer(8080)) + { + while (true) + { + Http http = new Http(); + try (MPSTEndpoint se = new MPSTEndpoint<>(http, S, + new HttpShortMessageFormatter())) + { + se.accept(ss, C); + + Buf buf = new Buf<>(); + Http_S_2 s2 = new Http_S_1(se).receive(C, REQUEST, buf); + + System.out.println("Request:\n" + buf.val); + + s2.send(C, new Response("1.1", "Hello")); + } + catch (IOException | ClassNotFoundException | ScribRuntimeException e) + { + e.printStackTrace(); + } + } + } + } +} diff --git a/scribble-demos/scrib/http/src/http/shortvers/message/HttpShortMessage.java b/scribble-demos/scrib/http/src/http/shortvers/message/HttpShortMessage.java new file mode 100644 index 000000000..7c452ff0f --- /dev/null +++ b/scribble-demos/scrib/http/src/http/shortvers/message/HttpShortMessage.java @@ -0,0 +1,67 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package http.shortvers.message; + +import org.scribble.runtime.message.ScribMessage; +import org.scribble.core.type.name.Op; + +import http.shortvers.HttpShort.Http.Http; + +public abstract class HttpShortMessage extends ScribMessage +{ + private static final long serialVersionUID = 1L; + + public static final String GET = "GET"; + public static final String HTTP = "HTTP"; + + public static final String CRLF = "\r\n"; + + public HttpShortMessage(Op op, String m) + { + super(op, m); + } + + public String getHeadersAndBody() + { + return (this.payload.length == 0) ? "" : (String) this.payload[0]; + } + + public byte[] toBytes() + { + // FIXME: factor better with Request/Response (e.g. " " after op, terminal CRLF, etc) + return (getOpString(this.op) + getHeadersAndBody()).getBytes(HttpShortMessageFormatter.cs); // Can give "utf-8" as arg directly + } + + @Override + public String toString() + { + return new String(toBytes()); + } + + protected static String getOpString(Op op) + { + if (op.equals(Http.REQUEST)) + { + return HttpShortMessage.GET; + } + else if (op.equals(Http.RESPONSE)) + { + return HttpShortMessage.HTTP; + } + else + { + throw new RuntimeException("TODO: " + op); + } + } +} diff --git a/scribble-demos/scrib/http/src/http/shortvers/message/HttpShortMessageFormatter.java b/scribble-demos/scrib/http/src/http/shortvers/message/HttpShortMessageFormatter.java new file mode 100644 index 000000000..fe1898a5c --- /dev/null +++ b/scribble-demos/scrib/http/src/http/shortvers/message/HttpShortMessageFormatter.java @@ -0,0 +1,258 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package http.shortvers.message; + +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.Charset; +import java.util.Arrays; + +import org.scribble.runtime.message.ScribMessage; +import org.scribble.runtime.message.ScribMessageFormatter; + +import http.shortvers.message.client.Request; +import http.shortvers.message.server.Response; + +public class HttpShortMessageFormatter implements ScribMessageFormatter +{ + public static final Charset cs = Charset.forName("UTF8"); + //private static CharsetDecoder cd = cs.newDecoder(); + + public HttpShortMessageFormatter() + { + + } + + @Override + public byte[] toBytes(ScribMessage m) throws IOException + { + return ((HttpShortMessage) m).toBytes(); + } + + @Override + public ScribMessage fromBytes(ByteBuffer bb) throws IOException, ClassNotFoundException + { + bb.flip(); + int rem = bb.remaining(); + if (rem < 2) + { + bb.compact(); + return null; + } + + String curr = new String(Arrays.copyOf(bb.array(), bb.remaining()), HttpShortMessageFormatter.cs); + String endOfHeaders = HttpShortMessage.CRLF + HttpShortMessage.CRLF; + if (!curr.contains(endOfHeaders)) + { + bb.compact(); + return null; + } + + if (curr.contains(Response.CONTENT_LENGTH)) + { + int eoh = curr.indexOf(endOfHeaders); + if (eoh == -1) + { + bb.compact(); + return null; + } + String contentLenSplit = curr.substring(curr.indexOf(Response.CONTENT_LENGTH)); + int len = Integer.parseInt(contentLenSplit.substring(Response.CONTENT_LENGTH.length()+2, contentLenSplit.indexOf('\r')).trim()); + if (curr.length() < eoh+4) + { + bb.compact(); + return null; + } + String body = curr.substring(eoh+4); + if (body.getBytes(HttpShortMessageFormatter.cs).length < len) + { + bb.compact(); + return null; + } + byte[] bs = new byte[bb.remaining()]; // FIXME: hardcoded Response parsing based on presence of Content-Length + bb.get(bs); + bb.compact(); + return parseResponse(new String(bs, HttpShortMessageFormatter.cs)); + } + else + { + byte[] bs = new byte[bb.remaining()]; + bb.get(bs); + bb.compact(); + return parseRequest(new String(bs, HttpShortMessageFormatter.cs)); // FIXME: assuming empty-body Request if no Content-Length + } + } + + // Assumes no body + private static HttpShortMessage parseRequest(String msg) + { + String get = null; + String http = null; + String host = null; + String userA = null; + String accept = null; + String acceptL = null; + String acceptE = null; + String dnt = null; + String connection = null; + String upgradeIR = null; + String cookie = null; + + for (boolean eoh = false; !eoh; ) + { + //if (msg.startsWith(HttpMessage.CRLF + HttpMessage.CRLF)) + if (msg.startsWith(HttpShortMessage.CRLF)) // First CRLF already trimmed after last header + { + eoh = true; + //msg = msg.substring(4); + msg = msg.substring(2); + break; + } + + msg = msg.replace("\\A\\s+", ""); + int i = msg.indexOf(":"); + if (i == -1) + { + throw new RuntimeException("Shouldn't get in here: " + msg); + } + if (msg.startsWith(HttpShortMessage.GET)) // FIXME + { + int j = msg.indexOf(' '); + get = msg.substring(j+1, msg.indexOf(' ', j+1)).trim(); + j = msg.indexOf('\r'); + http = msg.substring(msg.indexOf('/')+1, j).trim(); + msg = msg.substring(j+2); + } + else + { + String header = msg.substring(0, i); + int j = msg.indexOf("\r"); + switch (header) // FIXME: duplicates not checked + { + case Request.HOST: host = msg.substring(i+1, j).trim(); break; + case Request.USER_AGENT: userA = msg.substring(i+1, j).trim(); break; + case Request.ACCEPT: accept = msg.substring(i+1, j).trim(); break; + case Request.ACCEPT_LANGUAGE: acceptL = msg.substring(i+1, j).trim(); break; + case Request.ACCEPT_ENCODING: acceptE = msg.substring(i+1, j).trim(); break; + case Request.DO_NOT_TRACK: dnt = msg.substring(i+1, j).trim(); break; + case Request.CONNECTION: connection = msg.substring(i+1, j).trim(); break; + case Request.UPGRADE_INSECURE_REQUESTS: upgradeIR = msg.substring(i+1, j).trim(); break; + case Request.COOKIE: cookie = msg.substring(i+1, j).trim(); break; + default: { + //throw new RuntimeException("Cannot parse header field: " + msg.substring(0, j)); + System.err.println("Cannot parse header field, attempting to skip: " + msg.substring(0, j)); + } + } + msg = msg.substring(j+2); + } + } + if (!msg.isEmpty()) + { + throw new RuntimeException("Shouldn't get in here: " + msg); + } + return new Request(get, http, host, userA, accept, acceptL, acceptE, dnt, connection, upgradeIR, cookie); + } + + private static HttpShortMessage parseResponse(String msg) + { + String httpv = null; + String ack = null; + String date = null; + String server = null; + String strictTS = null; + String lastMod = null; + String eTag = null; + String acceptR = null; + String contentL = null; + String vary = null; + String contentT = null; + String via = null; + String body = null; + + for (boolean eoh = false; !eoh; ) + { + //if (msg.startsWith(HttpMessage.CRLF + HttpMessage.CRLF)) + if (msg.startsWith(HttpShortMessage.CRLF)) // First CRLF already trimmed after last header + { + eoh = true; + //msg = msg.substring(4); + msg = msg.substring(2); + break; + } + + msg = msg.trim(); + int i = msg.indexOf(":"); + if (i == -1) + { + throw new RuntimeException("Shouldn't get in here: " + msg); + } + if (msg.startsWith(HttpShortMessage.HTTP)) // FIXME + { + int j = msg.indexOf(' '); + httpv = msg.substring(msg.indexOf('/')+1, j); + + int k = msg.indexOf('\r'); + ack = msg.substring(j+1, k); + /*if (!ack.equals("200 OK")) + { + if (!ack.startsWith("404")) + { + throw new RuntimeException("[TODO]: " + msg); + } + } + ack = "OK"; // Hardcoded*/ + msg = msg.substring(k+2); + } + else + { + String header = msg.substring(0, i); + int j = msg.indexOf("\r"); + switch (header) + { + case Response.DATE: date = msg.substring(i+1, j).trim(); break; + case Response.SERVER: server = msg.substring(i+1, j).trim(); break; + case Response.STRICT_TRANSPORT_SECURITY: strictTS = msg.substring(i+1, j).trim(); break; + case Response.LAST_MODIFIED: lastMod = msg.substring(i+1, j).trim(); break; + case Response.ETAG: eTag = msg.substring(i+1, j).trim(); break; + case Response.ACCEPT_RANGES: acceptR = msg.substring(i+1, j).trim(); break; + case Response.CONTENT_LENGTH: contentL = msg.substring(i+1, j).trim(); break; + case Response.VARY: vary = msg.substring(i+1, j).trim(); break; + case Response.CONTENT_TYPE: contentT = msg.substring(i+1, j).trim(); break; + case Response.VIA: via = msg.substring(i+1, j).trim(); break; + default: + //throw new RuntimeException("Cannot parse header field: " + msg.substring(0, msg.indexOf('\r'))); + System.err.println("[Warning] Attempting to skip over response field: " + header + "\n" + msg.substring(i+1, j).trim()); + } + msg = msg.substring(j+2); + } + } + body = msg; + return new Response(httpv, ack, date, server, strictTS, lastMod, eTag, acceptR, contentL, vary, contentT, via, body); + } + + // FIXME: delete + @Deprecated @Override + public void writeMessage(DataOutputStream dos, ScribMessage m) throws IOException + { + throw new RuntimeException("Shouldn't get in here: " + m); + } + + @Deprecated @Override + public ScribMessage readMessage(DataInputStream dis) throws IOException + { + throw new RuntimeException("Shouldn't get in here: "); + } +} diff --git a/scribble-demos/scrib/http/src/http/shortvers/message/client/Request.java b/scribble-demos/scrib/http/src/http/shortvers/message/client/Request.java new file mode 100644 index 000000000..611077482 --- /dev/null +++ b/scribble-demos/scrib/http/src/http/shortvers/message/client/Request.java @@ -0,0 +1,63 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package http.shortvers.message.client; + +import http.shortvers.HttpShort.Http.Http; +import http.shortvers.message.HttpShortMessage; + +public class Request extends HttpShortMessage +{ + private static final long serialVersionUID = 1L; + + //public static final String GET = "GET"; + //public static final String HTTP = "HTTP"; + public static final String HOST = "Host"; + + public static final String USER_AGENT = "User-Agent"; + public static final String ACCEPT = "Accept"; + public static final String ACCEPT_LANGUAGE = "Accept-Language"; + public static final String ACCEPT_ENCODING = "Accept-Encoding"; + public static final String DO_NOT_TRACK = "DNT"; + public static final String CONNECTION = "Connection"; + public static final String UPGRADE_INSECURE_REQUESTS = "Upgrade-Insecure-Requests"; + public static final String COOKIE = "Cookie"; + + public Request(String get, String http, String host, String userA, String accept, String acceptL, String acceptE, String dnt, String connection, String upgradeIR, String cookie) + { + super(Http.REQUEST, getHeadersAndBody(get, http, host, userA, accept, acceptL, acceptE, dnt, connection, upgradeIR, cookie)); + } + + /*GET /~rhu/ HTTP/1.1 + host: www.doc.ic.ac.uk*/ + public Request(String get, String http, String host) + { + this(get, http, host, null, null, null, null, null, null, null, null); + } + + // Empty body + protected static String getHeadersAndBody(String get, String http, String host, String userA, String accept, String acceptL, String acceptE, String dnt, String connection, String upgradeIR, String cookie) { + return " " + + get + " " + HttpShortMessage.HTTP + "/" + http + HttpShortMessage.CRLF + + Request.HOST + ": " + host + HttpShortMessage.CRLF + + ((userA == null) ? "" : Request.USER_AGENT + ": " + userA + HttpShortMessage.CRLF) + + ((accept == null) ? "" : Request.ACCEPT + ": " + accept + HttpShortMessage.CRLF) + + ((acceptL == null) ? "" : Request.ACCEPT_LANGUAGE + ": " + acceptL + HttpShortMessage.CRLF) + + ((acceptE == null) ? "" : Request.ACCEPT_ENCODING + ": " + acceptE + HttpShortMessage.CRLF) + + ((dnt == null) ? "" : Request.DO_NOT_TRACK + ": " + dnt + HttpShortMessage.CRLF) + + ((connection == null) ? "" : Request.CONNECTION + ": " + connection + HttpShortMessage.CRLF) + + ((upgradeIR == null) ? "" : Request.UPGRADE_INSECURE_REQUESTS + ": " + upgradeIR + HttpShortMessage.CRLF) + + ((cookie == null) ? "" : Request.COOKIE + ": " + cookie + HttpShortMessage.CRLF) + + "" + HttpShortMessage.CRLF; // Empty body + } +} diff --git a/scribble-demos/scrib/http/src/http/shortvers/message/server/Response.java b/scribble-demos/scrib/http/src/http/shortvers/message/server/Response.java new file mode 100644 index 000000000..19b1a9373 --- /dev/null +++ b/scribble-demos/scrib/http/src/http/shortvers/message/server/Response.java @@ -0,0 +1,98 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package http.shortvers.message.server; + +import http.shortvers.HttpShort.Http.Http; +import http.shortvers.message.HttpShortMessage; + +public class Response extends HttpShortMessage +{ + private static final long serialVersionUID = 1L; + + public static final String DATE = "Date"; + public static final String CONTENT_TYPE = "Content-Type"; + public static final String _404 = "404"; + public static final String _200 = "200"; + public static final String ACCEPT_RANGES = "Accept-Ranges"; + public static final String LAST_MODIFIED = "Last-Modified"; + public static final String VARY = "Vary"; + public static final String SERVER = "Server"; + public static final String STRICT_TRANSPORT_SECURITY = "Strict-Transport-Security"; + public static final String VIA = "Via"; + public static final String ETAG = "ETag"; + public static final String CONTENT_LENGTH = "Content-Length"; + + /*HTTP/1.1 200 OK + Date: Mon, 13 Jun 2016 19:42:34 GMT + Server: Apache + Strict-Transport-Security: max-age=31536000; preload; includeSubDomains + Strict-Transport-Security: max-age=31536000; preload; includeSubDomains // BUG? (Apache configuration) + Last-Modified: Thu, 14 Apr 2016 12:46:24 GMT + ETag: "74a-53071482f6e0f" + Accept-Ranges: bytes + Content-Length: 1866 + Vary: Accept-Encoding + Content-Type: text/html + Via: 1.1 www.doc.ic.ac.uk*/ + public Response(String httpv, String ack, String date, String server, String strictTS, String lastMod, + String eTag, String acceptR, String contentL, String vary, String contentT, String via, String body) + { + super(Http.RESPONSE, getHeadersAndBody( + httpv, ack, date, server, strictTS, lastMod, eTag, acceptR, contentL, vary, contentT, via, body)); + } + + /*public Response(String httpv, String ack, String contentL, String body) + { + super(Http.RESPONSE, getHeadersAndBody(httpv, ack, contentL, body)); + }*/ + + public Response(String httpv, String body) + { + this(httpv, Response._200 + " OK", null, null, null, null, null, null, Integer.toString(body.length()), null, null, null, body); + } + + // ack includes "op", e.g. 200, 404, ... + protected static String getHeadersAndBody(String httpv, String ack, String date, String server, String strictTS, String lastMod, + String eTag, String acceptR, String contentL, String vary, String contentT, String via, String body) + { + if (!ack.startsWith(Response._200) && !ack.startsWith(Response._404)) + { + throw new RuntimeException("[TODO]: " + ack); + } + return "/" + httpv + " " + + ack + HttpShortMessage.CRLF // Hardcoded + + ((date == null) ? "" : Response.DATE + ": " + date + HttpShortMessage.CRLF) + + ((server == null) ? "" : Response.SERVER + ": " + server + HttpShortMessage.CRLF) + + ((strictTS == null) ? "" : Response.STRICT_TRANSPORT_SECURITY + ": " + strictTS + HttpShortMessage.CRLF) + + ((lastMod == null) ? "" : Response.LAST_MODIFIED + ": " + lastMod + HttpShortMessage.CRLF) + + ((eTag == null) ? "" : Response.ETAG + ": " + eTag + HttpShortMessage.CRLF) + + ((acceptR == null) ? "" : Response.ACCEPT_RANGES + ": " + acceptR + HttpShortMessage.CRLF) + + Response.CONTENT_LENGTH + ": " + contentL + HttpShortMessage.CRLF + + ((vary == null) ? "" : Response.VARY + ": " + vary + HttpShortMessage.CRLF) + + ((contentT == null) ? "" : Response.CONTENT_TYPE + ": " + contentT + HttpShortMessage.CRLF) + + ((via == null) ? "" : Response.VIA + ": " + via + HttpShortMessage.CRLF) + + HttpShortMessage.CRLF // Empty line for end of headers + + body + HttpShortMessage.CRLF; + } + + /*// 404 + protected static String getHeadersAndBody(String httpv, String ack, String contentL, String body) + { + return "/" + httpv + " " + + _404 + ack + HttpMessage.CRLF // Hardcoded + + Response.CONTENT_LENGTH + ": " + contentL + HttpMessage.CRLF + + HttpMessage.CRLF // Empty line for end of headers + + body + HttpMessage.CRLF; + }*/ +} diff --git a/scribble-demos/scrib/loan/src/loan/LoanApplicant.java b/scribble-demos/scrib/loan/src/loan/LoanApplicant.java new file mode 100644 index 000000000..39d3b0df9 --- /dev/null +++ b/scribble-demos/scrib/loan/src/loan/LoanApplicant.java @@ -0,0 +1,62 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package loan; + +import static loan.LoanApplication.BuyerBrokerSupplier.BuyerBrokerSupplier.Applicant; +import static loan.LoanApplication.BuyerBrokerSupplier.BuyerBrokerSupplier.ApplicationPortal; +import static loan.LoanApplication.BuyerBrokerSupplier.BuyerBrokerSupplier.applyForLoan; +import static loan.LoanApplication.BuyerBrokerSupplier.BuyerBrokerSupplier.reject; +import static loan.LoanApplication.BuyerBrokerSupplier.BuyerBrokerSupplier.requestConfirmation; + +import org.scribble.runtime.message.ObjectStreamFormatter; +import org.scribble.runtime.net.SocketChannelEndpoint; +import org.scribble.runtime.session.MPSTEndpoint; +import org.scribble.runtime.util.Buf; + +import loan.LoanApplication.BuyerBrokerSupplier.BuyerBrokerSupplier; +import loan.LoanApplication.BuyerBrokerSupplier.roles.Applicant; +import loan.LoanApplication.BuyerBrokerSupplier.statechans.Applicant.BuyerBrokerSupplier_Applicant_1; +import loan.LoanApplication.BuyerBrokerSupplier.statechans.Applicant.BuyerBrokerSupplier_Applicant_2_Cases; + +public class LoanApplicant +{ + public static void main(String[] args) throws Exception + { + BuyerBrokerSupplier sess = new BuyerBrokerSupplier(); + try (MPSTEndpoint se + = new MPSTEndpoint<>(sess, Applicant, new ObjectStreamFormatter())) + { + se.request(ApplicationPortal, SocketChannelEndpoint::new, "localhost", 8888); + + BuyerBrokerSupplier_Applicant_2_Cases branch + = new BuyerBrokerSupplier_Applicant_1(se) + .send(ApplicationPortal, applyForLoan, "Name", "DoB", 123, 456) + .branch(ApplicationPortal); + switch (branch.getOp()) + { + case reject: + { + branch.receive(reject); + break; + } + case requestConfirmation: + { + Buf b = new Buf<>(); + branch.receive(requestConfirmation, b); + break; + } + } + } + } +} diff --git a/scribble-demos/scrib/loan/src/loan/LoanApplication.scr b/scribble-demos/scrib/loan/src/loan/LoanApplication.scr new file mode 100644 index 000000000..b6beab53c --- /dev/null +++ b/scribble-demos/scrib/loan/src/loan/LoanApplication.scr @@ -0,0 +1,70 @@ +//$ ./scribblec.sh -ip scribble-demos/scrib/loan/src -d scribble-demos/scrib/loan/src scribble-demos/scrib/loan/src/loan/LoanApplication.scr -api BuyerBrokerSupplier Applicant +//$ javadoc -cp scribble-core/target/classes:scribble-runtime/target/classes:scribble-demos/scrib/loan/src scribble-demos/scrib/loan/src/loan/*.java -subpackages loan.LoanApplication.BuyerBrokerSupplier -d scribble-demos/scrib/loan/javadoc + +module loan.LoanApplication; + +/*data "CustomerName" from "CustomerName.xsd" as CustomerName; +data "DateOfBirth" from "DateOfBirth.xsd" as DateOfBirth; +data "AnnualSalary" from "AnnualSalary.xsd" as AnnualSalary; +data "CreditRating" from "CreditRating.xsd" as CreditRating; +data "LoanAmount" from "LoanAmount.xsd" as LoanAmount; +data "Approval" from "Approval.xsd" as Approval;*/ + +data "java.lang.Integer" from "rt.jar" as Int; +data "java.lang.String" from "rt.jar" as String; +data "java.lang.Boolean" from "rt.jar" as Bool; + +global protocol BuyerBrokerSupplier(role Applicant, role ApplicationPortal, role ProcessingDept, role FinanceDept) +{ + /*applyForLoan(CustomerName, DateOfBirth, AnnualSalary, CreditRating) from Applicant to ApplicationPortal; + checkEligibility(CustomerName, DateOfBirth, AnnualSalary, CreditRating) from ApplicationPortal to ProcessingDept; + respond(Approval) from ProcessingDept to ApplicationPortal;*/ + applyForLoan(String, String, Int, Int) from Applicant to ApplicationPortal; + checkEligibility(String, String, Int, Int) from ApplicationPortal to ProcessingDept; + respond(Bool) from ProcessingDept to ApplicationPortal; + + choice at ApplicationPortal + { + // "Approval" scenario + /*getLoanAmount(AnnualSalary) from ApplicationPortal to FinanceDept; + sendLoanAmount(LoanAmount) from FinanceDept to ApplicationPortal; + requestConfirmation(LoanAmount) from ApplicationPortal to Applicant;*/ + getLoanAmount(Int) from ApplicationPortal to FinanceDept; + sendLoanAmount(Int) from FinanceDept to ApplicationPortal; + requestConfirmation(Int) from ApplicationPortal to Applicant; + } + or + { + // "Reject" scenario + reject() from ApplicationPortal to FinanceDept; + reject() from ApplicationPortal to Applicant; + } +} + + +explicit global protocol BBSOriginal +( + role Applicant, role ApplicationPortal, role ProcessingDept, role FinanceDept +) +{ + connect Applicant to ApplicationPortal; + connect ApplicationPortal to ProcessingDept; + + applyForLoan(String, String, Int, Int) from Applicant to ApplicationPortal; + checkEligibility(String, String, Int, Int) from ApplicationPortal to ProcessingDept; + respond(Bool) from ProcessingDept to ApplicationPortal; + + choice at ApplicationPortal + { + // "Approval" scenario + connect ApplicationPortal to FinanceDept; + getLoanAmount(Int) from ApplicationPortal to FinanceDept; + sendLoanAmount(Int) from FinanceDept to ApplicationPortal; + requestConfirmation(Int) from ApplicationPortal to Applicant; + } + or + { + // "Reject" scenario + reject() from ApplicationPortal to Applicant; + } +} diff --git a/scribble-demos/scrib/loan/src/loan/LoanApplicationPortal.java b/scribble-demos/scrib/loan/src/loan/LoanApplicationPortal.java new file mode 100644 index 000000000..0091a12bc --- /dev/null +++ b/scribble-demos/scrib/loan/src/loan/LoanApplicationPortal.java @@ -0,0 +1,81 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package loan; + +import static loan.LoanApplication.BuyerBrokerSupplier.BuyerBrokerSupplier.Applicant; +import static loan.LoanApplication.BuyerBrokerSupplier.BuyerBrokerSupplier.ApplicationPortal; +import static loan.LoanApplication.BuyerBrokerSupplier.BuyerBrokerSupplier.FinanceDept; +import static loan.LoanApplication.BuyerBrokerSupplier.BuyerBrokerSupplier.ProcessingDept; +import static loan.LoanApplication.BuyerBrokerSupplier.BuyerBrokerSupplier.applyForLoan; +import static loan.LoanApplication.BuyerBrokerSupplier.BuyerBrokerSupplier.checkEligibility; +import static loan.LoanApplication.BuyerBrokerSupplier.BuyerBrokerSupplier.getLoanAmount; +import static loan.LoanApplication.BuyerBrokerSupplier.BuyerBrokerSupplier.reject; +import static loan.LoanApplication.BuyerBrokerSupplier.BuyerBrokerSupplier.requestConfirmation; +import static loan.LoanApplication.BuyerBrokerSupplier.BuyerBrokerSupplier.respond; +import static loan.LoanApplication.BuyerBrokerSupplier.BuyerBrokerSupplier.sendLoanAmount; + +import org.scribble.runtime.message.ObjectStreamFormatter; +import org.scribble.runtime.net.ScribServerSocket; +import org.scribble.runtime.net.SocketChannelEndpoint; +import org.scribble.runtime.net.SocketChannelServer; +import org.scribble.runtime.session.MPSTEndpoint; +import org.scribble.runtime.util.Buf; + +import loan.LoanApplication.BuyerBrokerSupplier.BuyerBrokerSupplier; +import loan.LoanApplication.BuyerBrokerSupplier.roles.ApplicationPortal; +import loan.LoanApplication.BuyerBrokerSupplier.statechans.ApplicationPortal.BuyerBrokerSupplier_ApplicationPortal_1; +import loan.LoanApplication.BuyerBrokerSupplier.statechans.ApplicationPortal.BuyerBrokerSupplier_ApplicationPortal_4; + +public class LoanApplicationPortal +{ + public static void main(String[] args) throws Exception + { + BuyerBrokerSupplier sess = new BuyerBrokerSupplier(); + try ( + ScribServerSocket ss = new SocketChannelServer(8888); + MPSTEndpoint se + = new MPSTEndpoint<>(sess, ApplicationPortal, + new ObjectStreamFormatter())) + { + se.accept(ss, Applicant); + se.request(ProcessingDept, SocketChannelEndpoint::new, "localhost", 7777); + se.request(FinanceDept, SocketChannelEndpoint::new, "localhost", 9999); + + Buf customerName = new Buf<>(); + Buf dateOfBirth = new Buf<>(); + Buf annualSalary = new Buf<>(); + Buf creditRating = new Buf<>(); + Buf response = new Buf<>(); + BuyerBrokerSupplier_ApplicationPortal_4 s4 + = new BuyerBrokerSupplier_ApplicationPortal_1(se) + .receive(Applicant, applyForLoan, customerName, dateOfBirth, + annualSalary, creditRating) + .send(ProcessingDept, checkEligibility, customerName.val, + dateOfBirth.val, annualSalary.val, creditRating.val) + .receive(ProcessingDept, respond, response); + if (response.val) + { + Buf loan = new Buf<>(); + s4.send(FinanceDept, getLoanAmount, 789) + .receive(FinanceDept, sendLoanAmount, loan) + .send(Applicant, requestConfirmation, loan.val); + } + else + { + s4.send(FinanceDept, reject) + .send(Applicant, reject); + } + } + } +} diff --git a/scribble-demos/scrib/loan/src/loan/LoanFinanceDept.java b/scribble-demos/scrib/loan/src/loan/LoanFinanceDept.java new file mode 100644 index 000000000..ef5aae496 --- /dev/null +++ b/scribble-demos/scrib/loan/src/loan/LoanFinanceDept.java @@ -0,0 +1,65 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package loan; + +import static loan.LoanApplication.BuyerBrokerSupplier.BuyerBrokerSupplier.ApplicationPortal; +import static loan.LoanApplication.BuyerBrokerSupplier.BuyerBrokerSupplier.FinanceDept; +import static loan.LoanApplication.BuyerBrokerSupplier.BuyerBrokerSupplier.getLoanAmount; +import static loan.LoanApplication.BuyerBrokerSupplier.BuyerBrokerSupplier.reject; +import static loan.LoanApplication.BuyerBrokerSupplier.BuyerBrokerSupplier.sendLoanAmount; + +import org.scribble.runtime.message.ObjectStreamFormatter; +import org.scribble.runtime.net.ScribServerSocket; +import org.scribble.runtime.net.SocketChannelServer; +import org.scribble.runtime.session.MPSTEndpoint; +import org.scribble.runtime.util.Buf; + +import loan.LoanApplication.BuyerBrokerSupplier.BuyerBrokerSupplier; +import loan.LoanApplication.BuyerBrokerSupplier.roles.FinanceDept; +import loan.LoanApplication.BuyerBrokerSupplier.statechans.FinanceDept.BuyerBrokerSupplier_FinanceDept_1; +import loan.LoanApplication.BuyerBrokerSupplier.statechans.FinanceDept.BuyerBrokerSupplier_FinanceDept_1_Cases; + +public class LoanFinanceDept +{ + public static void main(String[] args) throws Exception + { + BuyerBrokerSupplier sess = new BuyerBrokerSupplier(); + try ( + ScribServerSocket ss = new SocketChannelServer(9999); + MPSTEndpoint se + = new MPSTEndpoint<>(sess, FinanceDept, new ObjectStreamFormatter())) + { + se.accept(ss, ApplicationPortal); + + BuyerBrokerSupplier_FinanceDept_1_Cases branch + = new BuyerBrokerSupplier_FinanceDept_1(se).branch(ApplicationPortal); + switch (branch.getOp()) + { + case getLoanAmount: + { + Buf loan = new Buf<>(); + branch + .receive(ApplicationPortal, getLoanAmount, loan) + .send(ApplicationPortal, sendLoanAmount, loan.val); + break; + } + case reject: + { + branch.receive(ApplicationPortal, reject); + break; + } + } + } + } +} diff --git a/scribble-demos/scrib/loan/src/loan/LoanProcessingDept.java b/scribble-demos/scrib/loan/src/loan/LoanProcessingDept.java new file mode 100644 index 000000000..800b613cc --- /dev/null +++ b/scribble-demos/scrib/loan/src/loan/LoanProcessingDept.java @@ -0,0 +1,54 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package loan; + +import static loan.LoanApplication.BuyerBrokerSupplier.BuyerBrokerSupplier.ApplicationPortal; +import static loan.LoanApplication.BuyerBrokerSupplier.BuyerBrokerSupplier.ProcessingDept; +import static loan.LoanApplication.BuyerBrokerSupplier.BuyerBrokerSupplier.checkEligibility; +import static loan.LoanApplication.BuyerBrokerSupplier.BuyerBrokerSupplier.respond; + +import org.scribble.runtime.message.ObjectStreamFormatter; +import org.scribble.runtime.net.ScribServerSocket; +import org.scribble.runtime.net.SocketChannelServer; +import org.scribble.runtime.session.MPSTEndpoint; +import org.scribble.runtime.util.Buf; + +import loan.LoanApplication.BuyerBrokerSupplier.BuyerBrokerSupplier; +import loan.LoanApplication.BuyerBrokerSupplier.roles.ProcessingDept; +import loan.LoanApplication.BuyerBrokerSupplier.statechans.ProcessingDept.BuyerBrokerSupplier_ProcessingDept_1; + +public class LoanProcessingDept +{ + public static void main(String[] args) throws Exception + { + BuyerBrokerSupplier sess = new BuyerBrokerSupplier(); + try ( + ScribServerSocket ss = new SocketChannelServer(7777); + MPSTEndpoint se + = new MPSTEndpoint<>(sess, ProcessingDept, + new ObjectStreamFormatter())) + { + se.accept(ss, ApplicationPortal); + + Buf customerName = new Buf<>(); + Buf dateOfBirth = new Buf<>(); + Buf annualSalary = new Buf<>(); + Buf creditRating = new Buf<>(); + new BuyerBrokerSupplier_ProcessingDept_1(se) + .receive(ApplicationPortal, checkEligibility, customerName, + dateOfBirth, annualSalary, creditRating) + .send(ApplicationPortal, respond, true); + } + } +} diff --git a/scribble-demos/scrib/nego/src/nego/Nego1.scr b/scribble-demos/scrib/nego/src/nego/Nego1.scr new file mode 100644 index 000000000..081ac337c --- /dev/null +++ b/scribble-demos/scrib/nego/src/nego/Nego1.scr @@ -0,0 +1,42 @@ +//$ ./scribblec.sh -ip scribble-demos/scrib/nego/src -d scribble-demos/scrib/nego/src scribble-demos/scrib/nego/src/nego/Nego1.scr + +module nego.Nego1; + +data "test.nego.SAP" from "test/nego/SAP.java" as SAP; + +// C = Consumer, P = Producer +global protocol Negotiate(role C, role P) +{ + propose(SAP) from C to P; + rec X + { + choice at P + { + accpt() from P to C; + confirm() from C to P; + } + or + { + reject() from P to C; + } + or + { + propose(SAP) from P to C; + choice at C + { + accpt() from C to P; + confirm() from P to C; + } + or + { + reject() from C to P; + } + or + { + propose(SAP) from C to P; + continue X; + } + } + } +} + diff --git a/scribble-demos/scrib/nego/src/nego/Nego2.scr b/scribble-demos/scrib/nego/src/nego/Nego2.scr new file mode 100644 index 000000000..132f1c3a8 --- /dev/null +++ b/scribble-demos/scrib/nego/src/nego/Nego2.scr @@ -0,0 +1,30 @@ +//$ ./scribblec.sh -ip scribble-demos/scrib/nego/src -d scribble-demos/scrib/nego/src scribble-demos/scrib/nego/src/nego/Nego2.scr + +module demo.nego.Nego2; + +data "test.nego.SAP" from "test/nego/SAP.java" as SAP; + +// C = Consumer, P = Producer +global protocol Negotiate(role C, role P) +{ + propose(SAP) from C to P; + do NegotiateAux(P, C); +} + +aux global protocol NegotiateAux(role A, role B) +{ + choice at A + { + accpt() from A to B; + confirm() from B to A; + } + or + { + reject() from A to B; + } + or + { + propose(SAP) from A to B; + do NegotiateAux(B, A); + } +} diff --git a/scribble-demos/scrib/nego/src/nego/Nego3.scr b/scribble-demos/scrib/nego/src/nego/Nego3.scr new file mode 100644 index 000000000..83e3e65d8 --- /dev/null +++ b/scribble-demos/scrib/nego/src/nego/Nego3.scr @@ -0,0 +1,24 @@ +//$ ./scribblec.sh -ip scribble-demos/scrib/nego/src -d scribble-demos/scrib/nego/src scribble-demos/scrib/nego/src/nego/Nego3.scr + +module demo.nego.Nego3; + +data "test.nego.SAP" from "test/nego/SAP.java" as SAP; + +// C = Consumer, P = Producer +global protocol Negotiate(role C, role P) +{ + propose(SAP) from C to P; + choice at P + { + accpt() from P to C; + confirm() from C to P; + } + or + { + reject() from P to C; + } + or + { + do Negotiate(P, C); + } +} diff --git a/scribble-demos/scrib/rpc/src/rpc/RPC.scr b/scribble-demos/scrib/rpc/src/rpc/RPC.scr new file mode 100644 index 000000000..8f41ff0a3 --- /dev/null +++ b/scribble-demos/scrib/rpc/src/rpc/RPC.scr @@ -0,0 +1,88 @@ +//$ ./scribblec.sh -ip modules/demos/scrib/rpc/src -d scribble-demos/scrib/src/rpc scribble-demos/scrib/rpc/src/rpc/RPC.scr + +module rpc.RPC; + + +global protocol Proto(role C, role S1, role S2, role S3) +{ + 1() from C to S1; + 2() from S1 to S2; + 2a() from S2 to S1; + 3() from S1 to S3; + 3a() from S3 to S1; + 1a() from S1 to C; +} + + +global protocol RPC(role C, role S) +{ + M1 from C to S; + M2 from S to C; +} + +global protocol RPCComp(role C, role S1, role S2, role S3) +{ + 1() from C to S1; + do RPC<2(), 2a()>(S1, S2); + do RPC<3(), 3a()>(S1, S3); + 1a() from S1 to C; +} + + +global protocol Relay(role R1, role R2, role R3) +{ + M1 from R1 to R2; + M2 from R2 to R3; +} + +global protocol RPCComp2(role C, role S1, role S2, role S3) +{ + do Relay<1(), 2()>(C, S1, S2); + do Relay<2a(), 3()>(S2, S1, S3); + do Relay<3a(), 1a()>(S3, S1, C); +} + +global protocol MyRelay(role A, role B, role C) +{ + do Relay(A, B, C); +} + + +/*global protocol RPC2(role C, role S) +{ + do Relay(C, S, C); // FIXME: +} + +global protocol RPCComp3(role C, role S1, role S2, role S3) +{ + 1() from C to S1; + do RPC2<2(), 2a()>(S1, S2); + do RPC2<3(), 3a()>(S1, S3); + 1a() from S1 to C; +}*/ + + + + + + + +/*global protocol MessageTransfer(role A, role B) +{ + X from A to B; +} + +global protocol Test(role A, role B, role C) +{ + choice at A + { + do MessageTransfer<1()>(A, B); + do MessageTransfer<1()>(B, C); + do Test(A, B, C); + } + or + { + do MessageTransfer<2()>(A, B); + do MessageTransfer<2()>(B, C); + } +}*/ diff --git a/scribble-demos/scrib/smtp/src/smtp/EraserThread.java b/scribble-demos/scrib/smtp/src/smtp/EraserThread.java new file mode 100644 index 000000000..a8d87f980 --- /dev/null +++ b/scribble-demos/scrib/smtp/src/smtp/EraserThread.java @@ -0,0 +1,40 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package smtp; + +public class EraserThread extends Thread +{ + private boolean stop = true; + + public void run() + { + try + { + while (this.stop) + { + System.out.print("\010 "); + Thread.sleep(1); + } + } + catch (InterruptedException e) + { + throw new RuntimeException(e); + } + } + + public void stopMasking() + { + this.stop = false; + } +} diff --git a/scribble-demos/scrib/smtp/src/smtp/SimpleSmtpC.java b/scribble-demos/scrib/smtp/src/smtp/SimpleSmtpC.java new file mode 100644 index 000000000..8fb895f42 --- /dev/null +++ b/scribble-demos/scrib/smtp/src/smtp/SimpleSmtpC.java @@ -0,0 +1,296 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ + +//$ java -cp scribble-runtime/target/classes/:scribble-core/target/classes:scribble-demos/target/classes smtp.SimpleSmtpC + + +package smtp; + +import static smtp.Smtp.Smtp.Smtp.C; +import static smtp.Smtp.Smtp.Smtp.S; +import static smtp.Smtp.Smtp.Smtp._220; +import static smtp.Smtp.Smtp.Smtp._221; +import static smtp.Smtp.Smtp.Smtp._235; +import static smtp.Smtp.Smtp.Smtp._250; +import static smtp.Smtp.Smtp.Smtp._250d; +import static smtp.Smtp.Smtp.Smtp._354; +import static smtp.Smtp.Smtp.Smtp._501; +import static smtp.Smtp.Smtp.Smtp._535; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.Base64; + +import org.scribble.runtime.net.SSLSocketChannelWrapper; +import org.scribble.runtime.net.SocketChannelEndpoint; +import org.scribble.runtime.session.MPSTEndpoint; +import org.scribble.runtime.statechans.LinearSocket; +import org.scribble.runtime.util.Buf; + +import smtp.Smtp.Smtp.Smtp; +import smtp.Smtp.Smtp.statechans.C.Smtp_C_1; +import smtp.Smtp.Smtp.statechans.C.Smtp_C_10; +import smtp.Smtp.Smtp.statechans.C.Smtp_C_11_Cases; +import smtp.Smtp.Smtp.statechans.C.Smtp_C_4; +import smtp.Smtp.Smtp.statechans.C.Smtp_C_6; +import smtp.Smtp.Smtp.statechans.C.Smtp_C_8; +import smtp.Smtp.Smtp.statechans.C.Smtp_C_9_Cases; +import smtp.Smtp.Smtp.statechans.C.ioifaces.Branch_C_S_250__S_250d; +import smtp.Smtp.Smtp.statechans.C.ioifaces.Case_C_S_250__S_250d; +import smtp.Smtp.Smtp.statechans.C.ioifaces.Select_C_S_Ehlo; +import smtp.Smtp.Smtp.statechans.C.ioifaces.Succ_In_S_250; +import smtp.Smtp.Smtp.roles.C; +import smtp.message.SmtpMessageFormatter; +import smtp.message.client.Auth; +import smtp.message.client.Data; +import smtp.message.client.DataLine; +import smtp.message.client.Ehlo; +import smtp.message.client.EndOfData; +import smtp.message.client.Mail; +import smtp.message.client.Quit; +import smtp.message.client.Rcpt; +import smtp.message.client.StartTls; +import smtp.message.client.Subject; + +// NB: needs the -subtypes option in the Endpoint API generation +public class SimpleSmtpC +{ + public SimpleSmtpC() throws Exception + { + run(); + } + + public void run() throws Exception + { + String host = "smtp.cc.ic.ac.uk"; + int port = 25; + + String ehlo = "user.testing.com"; + String mailFrom = "rhu@doc.ic.ac.uk"; // Sender + String rcptTo = mailFrom; + String subj = "test"; + String body = "body"; + + Smtp smtp = new Smtp(); + try (MPSTEndpoint se = new MPSTEndpoint<>(smtp, C, new SmtpMessageFormatter())) + { + se.request(S, SocketChannelEndpoint::new, host, port); + + Smtp_C_11_Cases cases = + doAuth( + doEhlo( + doStartTls( + doEhlo(new Smtp_C_1(se).async(S, _220), ehlo) + ) + , ehlo)) + .send(S, new Mail(mailFrom)) + .branch(S); + switch (cases.getOp()) + { + case _250: + { + cases.receive(_250) + .send(S, new Rcpt(rcptTo)).async(S, _250) + .send(S, new Data()).async(S, _354) + .send(S, new Subject(subj)) + .send(S, new DataLine(body)) + .send(S, new EndOfData()) + .receive(S, _250, new Buf<>()) + .send(S, new Quit()).async(S, _221); + break; + } + case _501: + { + cases.receive(_501).send(S, new Quit()).async(S, _221); + } + } + } + } + + private > + S1 doEhlo(Select_C_S_Ehlo s, String ehlo) throws Exception + { + Branch_C_S_250__S_250d bra = s.send(S, new Ehlo(ehlo)); + while (true) + { + Case_C_S_250__S_250d cases = bra.branch(S); + switch (cases.getOp()) + { + case _250: + { + return cases.receive(_250); + } + case _250d: + { + bra = cases.receive(_250d); + break; + } + } + } + } + + private Smtp_C_6 doStartTls(Smtp_C_4 s4) throws Exception + { + return + LinearSocket.wrapClient( + s4.send(S, new StartTls()) + .async(S, _220) + , S, SSLSocketChannelWrapper::new); + } + + private Smtp_C_10 doAuth(Smtp_C_8 s8) throws Exception + { + Smtp_C_9_Cases s9cases = s8.send(S, new Auth(getAuthPlain())).branch(S); + switch (s9cases.op) + { + case _235: + { + return s9cases.receive(_235); + } + case _535: + { + s9cases.receive(_535).send(S, new Quit()); + System.exit(0); + } + default: // To satisfy Java typing for return + { + throw new RuntimeException("Won't get in here: " + s9cases.op); + } + } + } + + private String getAuthPlain() throws IOException + { + return myGetAuthPlain(); + } + + private static String myGetAuthPlain() throws IOException + { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + + String user; + String pw; + + System.out.println("User: "); + user = br.readLine(); + + System.out.println("Password: "); + EraserThread et = new EraserThread(); + et.start(); + pw = br.readLine(); + et.stopMasking(); + + byte[] u = user.getBytes("utf-8"); + byte[] p = pw.getBytes("utf-8"); + byte[] bs = new byte[u.length + p.length + 2]; + System.arraycopy(u, 0, bs, 1, u.length); + System.arraycopy(p, 0, bs, u.length + 2, p.length); + + return Base64.getEncoder().encodeToString(bs); + } + + public static void main(String[] args) throws Exception + { + new SimpleSmtpC(); + } + + + + + /*public void run() throws Exception + { + String host = "smtp.cc.ic.ac.uk"; + int port = 25; + + String ehlo = "user.testing.com"; + String mail = "rhu@doc.ic.ac.uk"; // Sender + String rcpt = "raymond.hu05@imperial.ac.uk"; + String subj = "test"; + String body = "body"; + + Smtp smtp = new Smtp(); + try (SessionEndpoint se = new SessionEndpoint<>(smtp, C, new SmtpMessageFormatter())) + { + se.connect(S, SocketChannelEndpoint::new, host, port); + + Smtp_C_11_Cases cases = + doAuth( + doEhlo( + doStartTls( + //doEhlo(new Smtp_C_1(se).async(S, _220), ehlo).to(Select_C_S_Quit__S_StartTls.cast).to(Smtp_C_4.cast) + doEhlo(new Smtp_C_1(se).async(S, _220), ehlo) + ) + //, ehlo).to(Select_C_S_Auth__S_Quit.cast).to(Smtp_C_8.cast)) + , ehlo)) + .send(S, new Mail(mail)) + .branch(S); + switch (cases.getOp()) + { + case _250: + { + cases.receive(_250) + .send(S, new Rcpt(rcpt)) + .async(S, _250) + .send(S, new Data()) + .async(S, _354) + .send(S, new Subject(subj)) + .send(S, new DataLine(body)) + .send(S, new EndOfData()) + .receive(S, _250, new Buf<>()) + //.async(S, _250) + .send(S, new Quit()); + break; + } + case _501: + { + cases.receive(_501).send(S, new Quit()); + } + } + } + } + + //private Succ_In_S_250 doEhlo(Select_C_S_Ehlo__S_Quit s, String ehlo) throws Exception + //private S doEhlo(Select_C_S_Ehlo__S_Quit, ?> s, String ehlo) throws Exception + // NOTE: needs the -subtypes option + private > + //S1 doEhlo(Select_C_S_Ehlo__S_Quit, ?> s, String ehlo) throws Exception + //S1 doEhlo(Select_C_S_Ehlo__S_Quit s, String ehlo) throws Exception + S1 doEhlo(Select_C_S_Ehlo s, String ehlo) throws Exception + { + //Branch_C_S_250__S_250d bra = s.send(S, new Ehlo(ehlo)).to(Branch_C_S_250__S_250d.cast); + //Branch_C_S_250__S_250d bra = s.send(S, new Ehlo(ehlo)); + Branch_C_S_250__S_250d bra = s.send(S, new Ehlo(ehlo)); + while (true) + { + //Case_C_S_250__S_250d cases = bra.branch(S); + //Case_C_S_250__S_250d cases = bra.branch(S); + Case_C_S_250__S_250d cases = bra.branch(S); + switch (cases.getOp()) + { + case _250: + { + return cases.receive(_250); + } + case _250d: + { + //bra = cases.receive(_250d).to(Branch_C_S_250__S_250d.cast); + //bra = (Branch_C_S_250__S_250d) cases.receive(_250d); + bra = cases.receive(_250d); + break; + } + } + } + }*/ +} diff --git a/scribble-demos/scrib/smtp/src/smtp/Smtp.scr b/scribble-demos/scrib/smtp/src/smtp/Smtp.scr new file mode 100644 index 000000000..5426ebb34 --- /dev/null +++ b/scribble-demos/scrib/smtp/src/smtp/Smtp.scr @@ -0,0 +1,205 @@ +//$ ./scribblec.sh -ip scribble-demos/scrib/smtp/src -d scribble-demos/scrib/smtp/src scribble-demos/scrib/smtp/src/smtp/Smtp.scr -subtypes -api Smtp C +//$ javadoc -cp scribble-core/target/classes:scribble-runtime/target/classes:scribble-demos/scrib/smtp/src/ scribble-demos/scrib/smtp/src/smtp/*.java -subpackages smtp.Smtp.Smtp -d scribble-demos/scrib/smtp/javadoc + + +module smtp.Smtp; + +sig "smtp.message.server._220" + from "smtp/message/server/_220.java" as 220; +sig "smtp.message.server._221" + from "smtp/message/server/_221.java" as 221; +sig "smtp.message.server._250" + from "smtp/message/server/_250.java" as 250; +sig "smtp.message.server._250d" + from "smtp/message/server/_250d.java" as 250d; +sig "smtp.message.server._235" + from "smtp/message/server/_235.java" as 235; +sig "smtp.message.server._535" + from "smtp/message/server/_535.java" as 535; +sig "smtp.message.server._501" + from "smtp/message/server/_501.java" as 501; +sig "smtp.message.server._354" + from "smtp/message/server/_354.java" as 354; + +sig "smtp.message.client.Ehlo" + from "smtp/message/client/Ehlo.java" as Ehlo; +sig "smtp.message.client.StartTls" + from "smtp/message/client/StartTls.java" as StartTls; +sig "smtp.message.client.Auth" + from "smtp/message/client/Auth.java" as Auth; +sig "smtp.message.client.Mail" + from "smtp/message/client/Mail.java" as Mail; +sig "smtp.message.client.Rcpt" + from "smtp/message/client/Rcpt.java" as Rcpt; +sig "smtp.message.client.Subject" + from "smtp/message/client/Subject.java" as Subject; +sig "smtp.message.client.DataLine" + from "smtp/message/client/DataLine.java" as DataLine; +sig "smtp.message.client.Data" + from "smtp/message/client/Data.java" as Data; +sig "smtp.message.client.EndOfData" + from "smtp/message/client/EndOfData.java" as EndOfData; +sig "smtp.message.client.Quit" + from "smtp/message/client/Quit.java" as Quit; + +global protocol Smtp(role S, role C) +{ + 220 from S to C; + do Ehlo(S, C); +} + +aux global protocol Ehlo(role S, role C) +{ + choice at C + { + Ehlo from C to S; + rec X + { + choice at S + { + //250 from S to C; + 250d from S to C; + continue X; + } + or + { + 250 from S to C; + do StartTls(S, C); + } + } + } + or + { + Quit from C to S; + } +} + +aux global protocol StartTls(role S, role C) +{ + choice at C + { + StartTls from C to S; + 220 from S to C; + // Do TLS handshake here: level below the application level protocol (like regular TCP handshake) + do SecureEhlo(S, C); + } + or + { + Quit from C to S; + } +} + +aux global protocol SecureEhlo(role S, role C) +{ + choice at C + { + Ehlo from C to S; + rec X + { + choice at S + { + 250d from S to C; + continue X; + } + or + { + 250 from S to C; + do Auth(S, C); + } + } + } + or + { + Quit from C to S; + } +} + +aux global protocol Auth(role S, role C) +{ + rec Y + { + choice at C + { + Auth from C to S; + choice at S + { + 235 from S to C; + do Mail(S, C); + } + or + { + 535 from S to C; + continue Y; + } + //.. 501 Invalid base64 Data + } + or + { + Quit from C to S; + } + } +} + +aux global protocol Mail(role S, role C) +{ + rec Z1 + { + choice at C + { + Mail from C to S; //Mail from: + choice at S + { + 501 from S to C; + continue Z1; + } + or + { + 250 from S to C; + + rec Z2 + { + choice at C + { + Rcpt from C to S; //Rcpt to: + choice at S + { + 250 from S to C; + continue Z2; + } + } + or + { + Data from C to S; + 354 from S to C; + //too from C to S; //to: + //froom from C to S; //from: + rec Z3 + { + choice at C + { + DataLine from C to S; + continue Z3; + } + or + { + Subject from C to S; //Subject: + continue Z3; + } + or + { + EndOfData from C to S; // CRLF.CRLF + 250 from S to C; + continue Z1; + } + } + } + } + } + } + or + { + Quit from C to S; + 221 from S to C; + } + } +} diff --git a/scribble-demos/scrib/smtp/src/smtp/SmtpC.java b/scribble-demos/scrib/smtp/src/smtp/SmtpC.java new file mode 100644 index 000000000..ff4b1c098 --- /dev/null +++ b/scribble-demos/scrib/smtp/src/smtp/SmtpC.java @@ -0,0 +1,344 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ + +//$ java -cp scribble-core/target/classes:scribble-runtime/target/classes:scribble-demos/target/classes smtp.SmtpC smtp.cc.ic.ac.uk sender@bar.com recipient@foo.com subj body + + +package smtp; + +import static smtp.Smtp.Smtp.Smtp.C; +import static smtp.Smtp.Smtp.Smtp.S; +import static smtp.Smtp.Smtp.Smtp._220; +import static smtp.Smtp.Smtp.Smtp._221; +import static smtp.Smtp.Smtp.Smtp._235; +import static smtp.Smtp.Smtp.Smtp._250; +import static smtp.Smtp.Smtp.Smtp._250d; +import static smtp.Smtp.Smtp.Smtp._354; +import static smtp.Smtp.Smtp.Smtp._501; +import static smtp.Smtp.Smtp.Smtp._535; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.Base64; + +import org.scribble.runtime.net.SSLSocketChannelWrapper; +import org.scribble.runtime.net.SocketChannelEndpoint; +import org.scribble.runtime.session.MPSTEndpoint; +import org.scribble.runtime.util.Buf; + +import smtp.Smtp.Smtp.Smtp; +import smtp.Smtp.Smtp.statechans.C.EndSocket; +import smtp.Smtp.Smtp.statechans.C.Smtp_C_1; +import smtp.Smtp.Smtp.statechans.C.Smtp_C_10; +import smtp.Smtp.Smtp.statechans.C.Smtp_C_11_Cases; +import smtp.Smtp.Smtp.statechans.C.Smtp_C_12; +import smtp.Smtp.Smtp.statechans.C.Smtp_C_2; +import smtp.Smtp.Smtp.statechans.C.Smtp_C_3; +import smtp.Smtp.Smtp.statechans.C.Smtp_C_3_Cases; +import smtp.Smtp.Smtp.statechans.C.Smtp_C_4; +import smtp.Smtp.Smtp.statechans.C.Smtp_C_6; +import smtp.Smtp.Smtp.statechans.C.Smtp_C_7; +import smtp.Smtp.Smtp.statechans.C.Smtp_C_7_Cases; +import smtp.Smtp.Smtp.statechans.C.Smtp_C_8; +import smtp.Smtp.Smtp.statechans.C.Smtp_C_9_Cases; +import smtp.Smtp.Smtp.roles.C; +import smtp.message.SmtpMessageFormatter; +import smtp.message.client.Auth; +import smtp.message.client.Data; +import smtp.message.client.DataLine; +import smtp.message.client.Ehlo; +import smtp.message.client.EndOfData; +import smtp.message.client.Mail; +import smtp.message.client.Quit; +import smtp.message.client.Rcpt; +import smtp.message.client.StartTls; +import smtp.message.client.Subject; + +public class SmtpC +{ + private static final int PORT = 25; + + private final String server; // e.g., smtp.cc.ic.ac.uk; + private final String mailFrom; // sender@bar.com + private final String rcptTo; // recipient@foo.com + private final String subj; + private final String body; + + public SmtpC(String server, String mailFrom, String rcptTo, String subj, String body) throws Exception + { + this.server = server; + this.mailFrom = mailFrom; + this.rcptTo = rcptTo; + this.subj = subj; + this.body = body; + + run(); + } + + public static void main(String[] args) throws Exception + { + new SmtpC(args[0], args[1], args[2], args[3], args[4]); + } + + public void run() throws Exception + { + Smtp smtp = new Smtp(); + try (MPSTEndpoint se = + new MPSTEndpoint<>(smtp, C, new SmtpMessageFormatter())) + { + se.request(S, SocketChannelEndpoint::new, this.server, SmtpC.PORT); + + Smtp_C_1 s1 = new Smtp_C_1(se); + Smtp_C_2 s2 = s1.receive(S, _220, new Buf<>()); + + Smtp_C_10 s10 = + doAuth( + doSecureEhlo( + doStartTls( + doEhlo(s2) + ))); + + Smtp_C_11_Cases s11cases = + s10.send(S, new Mail(this.mailFrom)) + .branch(S); + switch (s11cases.op) + { + case _250: + { + sendMail(s11cases.receive(_250)); + break; + } + case _501: + { + s11cases.receive(_501).send(S, new Quit()); + break; + } + } + } + } + + private Smtp_C_4 doEhlo(Smtp_C_2 s2) throws Exception + { + Smtp_C_3 s3 = s2.send(S, new Ehlo("testing1")); + Buf b = new Buf<>(); + while (true) + { + Smtp_C_3_Cases s3cases = s3.branch(S); + switch (s3cases.op) + { + case _250: + { + Smtp_C_4 s4 = s3cases.receive(_250, b); + System.out.print("Ehlo: " + b.val); + return s4; + } + case _250d: + { + s3 = s3cases.receive(_250d, b); + System.out.print("Ehlo: " + b.val); + break; + } + } + } + } + + private Smtp_C_6 doStartTls(Smtp_C_4 s4) throws Exception + { + Buf b = new Buf<>(); + Smtp_C_6 s6 = s4.send(S, new StartTls()).receive(S, _220, b); + System.out.print("StartTLS: " + b.val); + s6.wrapClient(S, SSLSocketChannelWrapper::new); + return s6; + } + + private Smtp_C_8 doSecureEhlo(Smtp_C_6 s6) throws Exception + { + Smtp_C_7 s7 = s6.send(S, new Ehlo("testing2")); + Buf b = new Buf<>(); + while (true) + { + Smtp_C_7_Cases s7cases = s7.branch(S); + switch(s7cases.op) + { + case _250: + { + Smtp_C_8 s8 = s7cases.receive(_250, b); + System.out.print("Ehlo: " + b.val); + return s8; + } + case _250d: + { + s7 = s7cases.receive(_250d, b); + System.out.print("Ehlo: " + b.val); + break; + } + } + } + } + + private Smtp_C_10 doAuth(Smtp_C_8 s8) throws Exception + { + Smtp_C_9_Cases s9cases = s8.send(S, new Auth(getAuthPlain())).branch(S); + Buf b = new Buf<>(); + switch (s9cases.op) + { + case _235: + { + Smtp_C_10 s10 = s9cases.receive(_235, b); + System.out.print("Auth: " + b.val); + return s10; + } + case _535: + { + s9cases.receive(_535, b).send(S, new Quit()); + System.out.print("Auth: " + b.val); + System.exit(0); + } + default: + { + throw new RuntimeException("Shouldn't get in here: " + s9cases.op); + } + } + } + + private EndSocket sendMail(Smtp_C_12 s12) throws Exception + { + return + s12.send(S, new Rcpt(this.rcptTo)) + .async(S, _250) + .send(S, new Data()) + .async(S, _354) + .send(S, new Subject(this.subj)) + .send(S, new DataLine(this.body)) + .send(S, new EndOfData()) + .receive(S, _250, new Buf<>()) + .send(S, new Quit()) + .receive(S, _221, new Buf<>()); + } + + + /*public void run() throws ScribbleRuntimeException, IOException + { + String host = "smtp.cc.ic.ac.uk"; + int port = 25; + + Smtp smtp = new Smtp(); + try (SessionEndpoint se = new SessionEndpoint<>(smtp, Smtp.C, new SmtpMessageFormatter())) + { + se.connect(Smtp.S, SocketChannelEndpoint::new, host, port); + + Smtp_C_1 s1 = new Smtp_C_1(se); + + Buf f220 = new Buf<>(); + Smtp_C_2 s2 = s1.async(Smtp.S, Smtp._220, f220); + System.out.print("Greeting: " + f220.val.sync().msg); + + Smtp_C_4 s4 = doEhlo(s2); + Smtp_C_6 s6 = doStartTls(s4); + Smtp_C_8 s8 = doEhlo(s6); + Smtp_C_10 s10 = doAuth(s8); + + Smtp_C_11_Cases s11cases = s10.send(Smtp.S, new Mail("rhu@doc.ic.ac.uk")).branch(Smtp.S); + Smtp_C_12 s12 = null; + switch (s11cases.op) + { + case _250: + { + s12 = s11cases.receive(Smtp._250); + break; + } + case _501: // FIXME: "functional interface" for quit states + { + s11cases.receive(Smtp._501).send(Smtp.S, new Quit()); + System.exit(0); + } + } + s12.send(Smtp.S, new Rcpt("rhu@doc.ic.ac.uk")) + .async(Smtp.S, Smtp._250) + .send(Smtp.S, new Data()) + .async(Smtp.S, Smtp._354) + .send(Smtp.S, new Subject("hello ARVI")) + .send(Smtp.S, new DataLine("body")) + .send(Smtp.S, new EndOfData()) + .receive(Smtp.S, Smtp._250, new Buf<>()) // Final sync needed for session to be successful? + .send(Smtp.S, new Quit()); + + /*Case_C_S_501__S_250 mailResponse = + doAuth( + doEhlo( + doStartTls( + doEhlo(new Smtp_C_1(se).async(Smtp.S, Smtp._220), ehlo)) + , ehlo)) + .send(Smtp.S, new Mail(mail)) + .branch(Smtp.S); + switch (mailResponse.getOp()) + { + case _250: + { + mailResponse.receive(Smtp._250) + .to(Select_C_S_Rcpt__S_Data.cast).send(Smtp.S, new Rcpt(rcpt)) + .to(Receive_C_S_250.cast).async(Smtp.S, Smtp._250) + .to(Select_C_S_Rcpt__S_Data.cast).send(Smtp.S, new Data()) + .to(Receive_C_S_354.cast).async(Smtp.S, Smtp._354) + .to(Select_C_S_DataLine__S_Subject__S_EndOfDate.cast).send(Smtp.S, new Subject(subj)) + .to(Select_C_S_DataLine__S_Subject__S_EndOfDate.cast).send(Smtp.S, new DataLine(body)) + .to(Select_C_S_DataLine__S_Subject__S_EndOfDate.cast).send(Smtp.S, new EndOfData()) + .to(Receive_C_S_250.cast) + //.async(Smtp.S, Smtp._250) + .receive(Smtp.S, Smtp._250, new Buf<>()) // Final sync needed for session to be successful? + .to(Select_C_S_Mail__S_Quit.cast).send(Smtp.S, new Quit()); + break; + } + case _501: + { + mailResponse.receive(Smtp._501).to(Select_C_S_Mail__S_Quit.cast).send(Smtp.S, new Quit()); + } + }* / + } + catch (Exception e) + { + if (e instanceof ScribbleRuntimeException) + { + throw (ScribbleRuntimeException) e; + } + throw new ScribbleRuntimeException(e); + } + }*/ + + protected static String getAuthPlain() throws IOException + { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + + String user; + String pw; + + System.out.println("User: "); + user = br.readLine(); + + System.out.println("Password: "); + EraserThread et = new EraserThread(); + et.start(); + pw = br.readLine(); + et.stopMasking(); + + byte[] u = user.getBytes("utf-8"); + byte[] p = pw.getBytes("utf-8"); + byte[] bs = new byte[u.length + p.length + 2]; + System.arraycopy(u, 0, bs, 1, u.length); + System.arraycopy(p, 0, bs, u.length + 2, p.length); + + return Base64.getEncoder().encodeToString(bs); + } +} diff --git a/scribble-demos/scrib/smtp/src/smtp/message/SmtpMessage.java b/scribble-demos/scrib/smtp/src/smtp/message/SmtpMessage.java new file mode 100644 index 000000000..e3860c471 --- /dev/null +++ b/scribble-demos/scrib/smtp/src/smtp/message/SmtpMessage.java @@ -0,0 +1,98 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package smtp.message; + +import org.scribble.runtime.message.ScribMessage; +import org.scribble.core.type.name.Op; +import org.scribble.util.Caller; + +import smtp.Smtp.Smtp.Smtp; + +public abstract class SmtpMessage extends ScribMessage +{ + public static final String _220 = "220"; + public static final String _250 = "250"; + public static final String _250_ = "250-"; + public static final String _235 = "235"; + public static final String _535 = "535"; + public static final String _501 = "501"; + public static final String _354 = "354"; + + public static final String EHLO = "ehlo"; + public static final String STARTTLS = "starttls"; + public static final String AUTH = "auth plain"; + public static final String MAIL = "mail from:"; + public static final String RCPT = "rcpt to:"; + public static final String SUBJECT = "subject:"; + public static final String DATA = "data"; + public static final String QUIT = "quit"; + + public static final String DATA_LINE = ""; + public static final String END_OF_DATA = ""; + + private static final long serialVersionUID = 1L; + + protected static final String CRLF = "\r\n"; + + public SmtpMessage(Op op) + { + super(op); + } + + public SmtpMessage(Op op, String body) + { + super(op, body); + } + + public String getBody() + { + return (this.payload.length == 0) ? "" : (String) this.payload[0]; + } + + public byte[] toBytes() + { + // FIXME: " " after op should depend on op (OK for client, no "-" ops) + byte[] bs = (getOpString(this.op) + " " + getBody() + SmtpMessage.CRLF).getBytes(SmtpMessageFormatter.cs); // Can give "utf-8" as arg directly + return bs; + } + + @Override + public String toString() + { + return new String(toBytes()); + } + + protected static String getOpString(Op op) + { + return + (op.equals(Smtp._220)) ? SmtpMessage._220 + : (op.equals(Smtp._250)) ? SmtpMessage._250 + : (op.equals(Smtp._250d)) ? SmtpMessage._250_ + : (op.equals(Smtp._235)) ? SmtpMessage._235 + : (op.equals(Smtp._535)) ? SmtpMessage._535 + : (op.equals(Smtp._501)) ? SmtpMessage._501 + : (op.equals(Smtp._354)) ? SmtpMessage._354 + : (op.equals(Smtp.Ehlo)) ? SmtpMessage.EHLO + : (op.equals(Smtp.StartTls)) ? SmtpMessage.STARTTLS + : (op.equals(Smtp.Auth)) ? SmtpMessage.AUTH + : (op.equals(Smtp.Mail)) ? SmtpMessage.MAIL + : (op.equals(Smtp.Rcpt)) ? SmtpMessage.RCPT + : (op.equals(Smtp.Subject)) ? SmtpMessage.SUBJECT + : (op.equals(Smtp.Data)) ? SmtpMessage.DATA + : (op.equals(Smtp.Quit)) ? SmtpMessage.QUIT + : (op.equals(Smtp.DataLine)) ? SmtpMessage.DATA_LINE + : (op.equals(Smtp.EndOfData)) ? SmtpMessage.END_OF_DATA + : new Caller().call(() -> { throw new RuntimeException("TODO: " + op); }); + } +} diff --git a/scribble-demos/scrib/smtp/src/smtp/message/SmtpMessageFormatter.java b/scribble-demos/scrib/smtp/src/smtp/message/SmtpMessageFormatter.java new file mode 100644 index 000000000..c28f36091 --- /dev/null +++ b/scribble-demos/scrib/smtp/src/smtp/message/SmtpMessageFormatter.java @@ -0,0 +1,454 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package smtp.message; + +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.Charset; + +import org.scribble.runtime.message.ScribMessage; +import org.scribble.runtime.message.ScribMessageFormatter; + +import smtp.message.server._220; +import smtp.message.server._221; +import smtp.message.server._235; +import smtp.message.server._250; +import smtp.message.server._250d; +import smtp.message.server._354; +import smtp.message.server._501; +import smtp.message.server._535; + +// Currently supports only client-side reading, not server-side +public class SmtpMessageFormatter implements ScribMessageFormatter +{ + //.. fix formatting + //.. try ssl wrapper + //.. add connection (transport) actions + + public static Charset cs = Charset.forName("UTF8"); + //private static CharsetDecoder cd = cs.newDecoder(); + + public SmtpMessageFormatter() + { + + } + + @Override + public byte[] toBytes(ScribMessage m) throws IOException + { + return ((SmtpMessage) m).toBytes(); + } + + @Override + public ScribMessage fromBytes(ByteBuffer bb) throws IOException, ClassNotFoundException + { + bb.flip(); + //byte[] bs = new byte[2]; + int rem = bb.remaining(); + if (rem < 2) + { + bb.compact(); + return null; + } + + int pos = bb.position(); + String front = new String(new byte[] { bb.get(pos), bb.get(pos + 1) }, SmtpMessageFormatter.cs); + if (front.equals(SmtpMessage.CRLF)) + { + throw new RuntimeException("TODO: "); + } + + if (rem < pos + 4) + { + bb.compact(); + return null; + } + front += new String(new byte[] { bb.get(pos + 2), bb.get(pos + 3) }, SmtpMessageFormatter.cs); + int code = isStatusCode(front); + if (code > -1) + { + String body = readLine(bb, pos + 4).trim(); // Whitespace already built into the message classes + bb.compact(); + if (body == null) + { + return null; + } + switch (code) + { + case 220: return new _220(body); + case 250: + { + if (front.charAt(3) == '-') + { + return new _250d(body); + } + return new _250(body); + } + case 235: return new _235(body); + case 535: return new _535(body); + case 501: return new _501(body); + case 354: return new _354(body); + case 221: return new _221(body); + default: throw new RuntimeException("Unknown status code " + code + ": " + body); + } + } + /*else if (front.startsWith(HttpMessage.GET)) // TODO: server-side (EHLO, STARTTLS, etc) + { + }*/ + else + { + // TODO: server-side (MAIL FROM:, RCPT TO:, etc) + String line = front + readLine(bb, pos + 4); + bb.compact(); + /*if (line == null) // deadcode + { + return null; + }*/ + throw new RuntimeException("Cannot parse message: " + line); + } + } + + private static String readLine(ByteBuffer bb, int i) throws IOException + { + StringBuilder sb = new StringBuilder(); + for (int limit = bb.limit(); i <= limit; ) + { + char c = (char) bb.get(i++); + sb.append(c); + if (c == '\r') + { + c = (char) bb.get(i++); + sb.append(c); + if (c == '\n') + { + bb.position(i); + return sb.substring(0, sb.length() - 2).toString(); + } + } + } + return null; + } + + // Duplicated from HttpMessageFormatter // FIXME: factor out + private int isStatusCode(String front) + { + String code = ""; + for (int i = 0; i < 4; i++) + { + //char c = (char) bs[i]; + char c = front.charAt(i); + if (i < 3) + { + if (c < '0' || c > '9') + { + return -1; + } + code += c; + } + else + { + if (c != ' ' && c != '-') // HACK: hypen + { + return -1; + } + } + } + return Integer.parseInt(code); + } + + /*private static String readWord(ByteBuffer bb, int i) throws IOException + { + StringBuilder sb = new StringBuilder(); + for (int limit = bb.limit(); i <= limit; ) + { + char c = (char) bb.get(i); + if (c == ' ') + { + bb.position(i); + return sb.toString(); + } + sb.append(c); + } + return null; + }*/ + + /* // Pre: flipped ready for reading + @Override + public SmtpMessage readMessage(DataInputStream dis) throws IOException + { + String header = getHeader(dis); + switch (header) + { + // FIXME: factor out text constants with Session constants? + case "220 ": + { + return new _220(getBody(dis)); + } + case "235 ": + { + return new _235(getBody(dis)); + } + case "250-": + { + return new _250_(getBody(dis)); + } + case "250 ": + { + return new _250(getBody(dis)); + } + case "354 ": + { + return new _354(getBody(dis)); + } + case "501 ": + { + return new _501(getBody(dis)); + } + case "535 ": + { + return new _535(getBody(dis)); + } + default: + { + throw new RuntimeException("Unknown header: " + header); + } + } + } + + // *4* char headers (3 digits, dash or space) + private String getHeader(DataInputStream dis) throws IOException + { + readMinimumBytes(dis, 4); + + int limit = bb.limit(); + bb.limit(4); + String header = cd.decode(bb).toString(); // updates bb position + bb.limit(limit); + bb.compact(); + bb.flip(); + return header; + } + + // Reads up to \r\n inclusive; doesn't return the \r\n + private String getBody(DataInputStream dis) throws IOException + { + int min = 2; + readMinimumBytes(dis, min); // Min should be more? + while (true) + { + String all = cd.decode(bb).toString(); // updates bb position + if (all.contains("\n")) // FIXME: didn't check exactly \r\n + { + int i = all.indexOf("\n"); + String body = all.substring(0, i - 1); + bb.position(i + 1); // \r\n -- ASCII 1-to-1 byte-char index + bb.compact(); + bb.flip(); + return body; + } + bb.rewind(); + readMinimumBytes(dis, ++min); // FIXME: buffered readLine would be more efficient + } + } + + // FIXME: min should mean min fresh (i.e. not including bb cached -- there currently is no cache: is.available doesn't work for SSLSocket, always returns 0) + private void readMinimumBytes(DataInputStream dis, int min) throws IOException + { + for (int remaining = bb.remaining(); remaining < min; remaining = bb.remaining()) + { + bb.compact(); + bb.put((byte) dis.read()); // FIXME: check for buffer overflow + bb.flip(); + } + }*/ + + @Deprecated + @Override + public void writeMessage(DataOutputStream dos, ScribMessage m) throws IOException + { + dos.write(((SmtpMessage) m).toBytes()); + dos.flush(); + } + + @Deprecated + @Override + public SmtpMessage readMessage(DataInputStream dis) throws IOException + { + byte[] bs = new byte[2]; + dis.readFully(bs); + String front = new String(bs, SmtpMessageFormatter.cs); + if (front.equals(SmtpMessage.CRLF)) + { + throw new RuntimeException("TODO: "); + } + bs = new byte[2]; + dis.readFully(bs); + front += new String(bs, SmtpMessageFormatter.cs); + int code = isStatusCode(front); + if (code > -1) + { + String body = readLine(dis).trim(); // Whitespace already built into the message classes + switch (code) + { + case 220: return new _220(body); + case 250: + { + if (front.charAt(3) == '-') + { + return new _250d(body); + } + return new _250(body); + } + case 235: return new _235(body); + case 535: return new _535(body); + case 501: return new _501(body); + case 354: return new _354(body); + default: throw new RuntimeException("Unknown status code: " + code); + } + } + /*else if (front.startsWith(HttpMessage.GET)) + { + }*/ + else + { + String line = front + readLine(dis); + throw new RuntimeException("Cannot parse message: " + line); + } + } + + private static String readLine(DataInputStream dis) throws IOException + { + StringBuilder sb = new StringBuilder(); + for (; true; ) + { + char c = (char) dis.read(); // readChar is not the same + sb.append(c); + if (c == '\r') + { + c = (char) dis.read(); + sb.append(c); + if (c == '\n') + { + return sb.substring(0, sb.length() - 2).toString(); + } + } + } + } + + /*private static String readWord(DataInputStream dis) throws IOException + { + StringBuilder sb = new StringBuilder(); + for (; true; ) + { + char c = (char) dis.read(); + if (c == ' ') + { + return sb.toString(); + } + sb.append(c); + } + }*/ + + /* // Pre: flipped ready for reading + @Override + public SmtpMessage readMessage(DataInputStream dis) throws IOException + { + String header = getHeader(dis); + switch (header) + { + // FIXME: factor out text constants with Session constants? + case "220 ": + { + return new _220(getBody(dis)); + } + case "235 ": + { + return new _235(getBody(dis)); + } + case "250-": + { + return new _250_(getBody(dis)); + } + case "250 ": + { + return new _250(getBody(dis)); + } + case "354 ": + { + return new _354(getBody(dis)); + } + case "501 ": + { + return new _501(getBody(dis)); + } + case "535 ": + { + return new _535(getBody(dis)); + } + default: + { + throw new RuntimeException("Unknown header: " + header); + } + } + } + + // *4* char headers (3 digits, dash or space) + private String getHeader(DataInputStream dis) throws IOException + { + readMinimumBytes(dis, 4); + + int limit = bb.limit(); + bb.limit(4); + String header = cd.decode(bb).toString(); // updates bb position + bb.limit(limit); + bb.compact(); + bb.flip(); + return header; + } + + // Reads up to \r\n inclusive; doesn't return the \r\n + private String getBody(DataInputStream dis) throws IOException + { + int min = 2; + readMinimumBytes(dis, min); // Min should be more? + while (true) + { + String all = cd.decode(bb).toString(); // updates bb position + if (all.contains("\n")) // FIXME: didn't check exactly \r\n + { + int i = all.indexOf("\n"); + String body = all.substring(0, i - 1); + bb.position(i + 1); // \r\n -- ASCII 1-to-1 byte-char index + bb.compact(); + bb.flip(); + return body; + } + bb.rewind(); + readMinimumBytes(dis, ++min); // FIXME: buffered readLine would be more efficient + } + } + + // FIXME: min should mean min fresh (i.e. not including bb cached -- there currently is no cache: is.available doesn't work for SSLSocket, always returns 0) + private void readMinimumBytes(DataInputStream dis, int min) throws IOException + { + for (int remaining = bb.remaining(); remaining < min; remaining = bb.remaining()) + { + bb.compact(); + bb.put((byte) dis.read()); // FIXME: check for buffer overflow + bb.flip(); + } + }*/ +} diff --git a/scribble-demos/scrib/smtp/src/smtp/message/client/Auth.java b/scribble-demos/scrib/smtp/src/smtp/message/client/Auth.java new file mode 100644 index 000000000..42467c366 --- /dev/null +++ b/scribble-demos/scrib/smtp/src/smtp/message/client/Auth.java @@ -0,0 +1,39 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package smtp.message.client; + +import smtp.Smtp.Smtp.Smtp; +import smtp.message.SmtpMessage; + +public class Auth extends SmtpMessage +{ + private static final long serialVersionUID = 1L; + + public Auth() + { + super(Smtp.Auth); + } + + // Move base 64 encode into here? (Or override toBytes) + public Auth(String body) + { + super(Smtp.Auth, body); + } + + @Override + public String toString() + { + return this.op + "(***)"; // FIXME + } +} diff --git a/scribble-demos/scrib/smtp/src/smtp/message/client/Data.java b/scribble-demos/scrib/smtp/src/smtp/message/client/Data.java new file mode 100644 index 000000000..04df7f406 --- /dev/null +++ b/scribble-demos/scrib/smtp/src/smtp/message/client/Data.java @@ -0,0 +1,27 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package smtp.message.client; + +import smtp.Smtp.Smtp.Smtp; +import smtp.message.SmtpMessage; + +public class Data extends SmtpMessage +{ + private static final long serialVersionUID = 1L; + + public Data() + { + super(Smtp.Data); + } +} diff --git a/scribble-demos/scrib/smtp/src/smtp/message/client/DataLine.java b/scribble-demos/scrib/smtp/src/smtp/message/client/DataLine.java new file mode 100644 index 000000000..aee5775a8 --- /dev/null +++ b/scribble-demos/scrib/smtp/src/smtp/message/client/DataLine.java @@ -0,0 +1,40 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package smtp.message.client; + +import smtp.Smtp.Smtp.Smtp; +import smtp.message.SmtpMessage; +import smtp.message.SmtpMessageFormatter; + +// FIXME: rename +public class DataLine extends SmtpMessage +{ + private static final long serialVersionUID = 1L; + + public DataLine(String body) + { + super(Smtp.DataLine, body); + if (body.equals(".")) + { + throw new RuntimeException("Illegal body: " + body); + } + } + + @Override + public byte[] toBytes() + { + // No space after op and no implicit CRLF + return (SmtpMessage.getOpString(this.op) + getBody()).getBytes(SmtpMessageFormatter.cs); + } +} diff --git a/scribble-demos/scrib/smtp/src/smtp/message/client/Ehlo.java b/scribble-demos/scrib/smtp/src/smtp/message/client/Ehlo.java new file mode 100644 index 000000000..829d8fe58 --- /dev/null +++ b/scribble-demos/scrib/smtp/src/smtp/message/client/Ehlo.java @@ -0,0 +1,27 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package smtp.message.client; + +import smtp.Smtp.Smtp.Smtp; +import smtp.message.SmtpMessage; + +public class Ehlo extends SmtpMessage +{ + private static final long serialVersionUID = 1L; + + public Ehlo(String body) + { + super(Smtp.Ehlo, body); + } +} diff --git a/scribble-demos/scrib/smtp/src/smtp/message/client/EndOfData.java b/scribble-demos/scrib/smtp/src/smtp/message/client/EndOfData.java new file mode 100644 index 000000000..25efc40d3 --- /dev/null +++ b/scribble-demos/scrib/smtp/src/smtp/message/client/EndOfData.java @@ -0,0 +1,36 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package smtp.message.client; + +import smtp.Smtp.Smtp.Smtp; +import smtp.message.SmtpMessage; +import smtp.message.SmtpMessageFormatter; + +public class EndOfData extends SmtpMessage +{ + private static final long serialVersionUID = 1L; + + public EndOfData() + { + super(Smtp.EndOfData, SmtpMessage.CRLF + "." + SmtpMessage.CRLF); + } + + // Drop operator used for Scribble + @Override + public byte[] toBytes() + { + // No space after op and no implicit CRLF + return (SmtpMessage.getOpString(this.op) + getBody()).getBytes(SmtpMessageFormatter.cs); + } +} diff --git a/scribble-demos/scrib/smtp/src/smtp/message/client/Mail.java b/scribble-demos/scrib/smtp/src/smtp/message/client/Mail.java new file mode 100644 index 000000000..3be5fce98 --- /dev/null +++ b/scribble-demos/scrib/smtp/src/smtp/message/client/Mail.java @@ -0,0 +1,27 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package smtp.message.client; + +import smtp.Smtp.Smtp.Smtp; +import smtp.message.SmtpMessage; + +public class Mail extends SmtpMessage +{ + private static final long serialVersionUID = 1L; + + public Mail(String sender) + { + super(Smtp.Mail, "<" + sender + ">"); + } +} diff --git a/scribble-demos/scrib/smtp/src/smtp/message/client/Quit.java b/scribble-demos/scrib/smtp/src/smtp/message/client/Quit.java new file mode 100644 index 000000000..fc82d9688 --- /dev/null +++ b/scribble-demos/scrib/smtp/src/smtp/message/client/Quit.java @@ -0,0 +1,27 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package smtp.message.client; + +import smtp.Smtp.Smtp.Smtp; +import smtp.message.SmtpMessage; + +public class Quit extends SmtpMessage +{ + private static final long serialVersionUID = 1L; + + public Quit() + { + super(Smtp.Quit); + } +} diff --git a/scribble-demos/scrib/smtp/src/smtp/message/client/Rcpt.java b/scribble-demos/scrib/smtp/src/smtp/message/client/Rcpt.java new file mode 100644 index 000000000..599c17866 --- /dev/null +++ b/scribble-demos/scrib/smtp/src/smtp/message/client/Rcpt.java @@ -0,0 +1,32 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package smtp.message.client; + +import smtp.Smtp.Smtp.Smtp; +import smtp.message.SmtpMessage; + +public class Rcpt extends SmtpMessage +{ + private static final long serialVersionUID = 1L; + + /*public Rcpt() + { + super(SMTP.RCPT); + }*/ + + public Rcpt(String receiver) + { + super(Smtp.Rcpt, "<" + receiver + ">"); + } +} diff --git a/scribble-demos/scrib/smtp/src/smtp/message/client/StartTls.java b/scribble-demos/scrib/smtp/src/smtp/message/client/StartTls.java new file mode 100644 index 000000000..0ddbec349 --- /dev/null +++ b/scribble-demos/scrib/smtp/src/smtp/message/client/StartTls.java @@ -0,0 +1,27 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package smtp.message.client; + +import smtp.Smtp.Smtp.Smtp; +import smtp.message.SmtpMessage; + +public class StartTls extends SmtpMessage +{ + private static final long serialVersionUID = 1L; + + public StartTls() + { + super(Smtp.StartTls); + } +} diff --git a/scribble-demos/scrib/smtp/src/smtp/message/client/Subject.java b/scribble-demos/scrib/smtp/src/smtp/message/client/Subject.java new file mode 100644 index 000000000..c93da3607 --- /dev/null +++ b/scribble-demos/scrib/smtp/src/smtp/message/client/Subject.java @@ -0,0 +1,27 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package smtp.message.client; + +import smtp.Smtp.Smtp.Smtp; +import smtp.message.SmtpMessage; + +public class Subject extends SmtpMessage +{ + private static final long serialVersionUID = 1L; + + public Subject(String subject) + { + super(Smtp.Subject, subject); + } +} diff --git a/scribble-demos/scrib/smtp/src/smtp/message/server/_220.java b/scribble-demos/scrib/smtp/src/smtp/message/server/_220.java new file mode 100644 index 000000000..d7e1581bd --- /dev/null +++ b/scribble-demos/scrib/smtp/src/smtp/message/server/_220.java @@ -0,0 +1,38 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package smtp.message.server; + +import smtp.Smtp.Smtp.Smtp; +import smtp.message.SmtpMessage; + +public class _220 extends SmtpMessage +{ + private static final long serialVersionUID = 1L; + + public _220() + { + super(Smtp._220); + } + + public _220(String body) + { + super(Smtp._220, body); + } + + /*@Override + public Operator getOperator() + { + return Smtp._220; + }*/ +} diff --git a/scribble-demos/scrib/smtp/src/smtp/message/server/_221.java b/scribble-demos/scrib/smtp/src/smtp/message/server/_221.java new file mode 100644 index 000000000..11026f488 --- /dev/null +++ b/scribble-demos/scrib/smtp/src/smtp/message/server/_221.java @@ -0,0 +1,38 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package smtp.message.server; + +import smtp.Smtp.Smtp.Smtp; +import smtp.message.SmtpMessage; + +public class _221 extends SmtpMessage +{ + private static final long serialVersionUID = 1L; + + public _221() + { + super(Smtp._220); + } + + public _221(String body) + { + super(Smtp._220, body); + } + + /*@Override + public Operator getOperator() + { + return Smtp._220; + }*/ +} diff --git a/scribble-demos/scrib/smtp/src/smtp/message/server/_235.java b/scribble-demos/scrib/smtp/src/smtp/message/server/_235.java new file mode 100644 index 000000000..baf91639a --- /dev/null +++ b/scribble-demos/scrib/smtp/src/smtp/message/server/_235.java @@ -0,0 +1,38 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package smtp.message.server; + +import smtp.Smtp.Smtp.Smtp; +import smtp.message.SmtpMessage; + +public class _235 extends SmtpMessage +{ + private static final long serialVersionUID = 1L; + + public _235() + { + super(Smtp._235); + } + + public _235(String body) + { + super(Smtp._235, body); + } + + /*@Override + public Operator getOperator() + { + return Smtp._235; + }*/ +} diff --git a/scribble-demos/scrib/smtp/src/smtp/message/server/_250.java b/scribble-demos/scrib/smtp/src/smtp/message/server/_250.java new file mode 100644 index 000000000..fec0b318b --- /dev/null +++ b/scribble-demos/scrib/smtp/src/smtp/message/server/_250.java @@ -0,0 +1,32 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package smtp.message.server; + +import smtp.Smtp.Smtp.Smtp; +import smtp.message.SmtpMessage; + +public class _250 extends SmtpMessage +{ + private static final long serialVersionUID = 1L; + + public _250() + { + super(Smtp._250); + } + + public _250(String body) + { + super(Smtp._250, body); + } +} diff --git a/scribble-demos/scrib/smtp/src/smtp/message/server/_250d.java b/scribble-demos/scrib/smtp/src/smtp/message/server/_250d.java new file mode 100644 index 000000000..c5dd2b478 --- /dev/null +++ b/scribble-demos/scrib/smtp/src/smtp/message/server/_250d.java @@ -0,0 +1,40 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package smtp.message.server; + +import smtp.Smtp.Smtp.Smtp; +import smtp.message.SmtpMessage; +import smtp.message.SmtpMessageFormatter; + +public class _250d extends SmtpMessage +{ + private static final long serialVersionUID = 1L; + + public _250d() + { + super(Smtp._250d); + } + + public _250d(String body) + { + super(Smtp._250d, body); + } + + @Override + public byte[] toBytes() + { + // No space after op + return (getOpString(this.op) + getBody() + SmtpMessage.CRLF).getBytes(SmtpMessageFormatter.cs); + } +} diff --git a/scribble-demos/scrib/smtp/src/smtp/message/server/_354.java b/scribble-demos/scrib/smtp/src/smtp/message/server/_354.java new file mode 100644 index 000000000..65a8a261a --- /dev/null +++ b/scribble-demos/scrib/smtp/src/smtp/message/server/_354.java @@ -0,0 +1,38 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package smtp.message.server; + +import smtp.Smtp.Smtp.Smtp; +import smtp.message.SmtpMessage; + +public class _354 extends SmtpMessage +{ + private static final long serialVersionUID = 1L; + + public _354() + { + super(Smtp._354); + } + + public _354(String body) + { + super(Smtp._354, body); + } + + /*@Override + public Operator getOperator() + { + return Smtp._354; + }*/ +} diff --git a/scribble-demos/scrib/smtp/src/smtp/message/server/_501.java b/scribble-demos/scrib/smtp/src/smtp/message/server/_501.java new file mode 100644 index 000000000..22823e42c --- /dev/null +++ b/scribble-demos/scrib/smtp/src/smtp/message/server/_501.java @@ -0,0 +1,38 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package smtp.message.server; + +import smtp.Smtp.Smtp.Smtp; +import smtp.message.SmtpMessage; + +public class _501 extends SmtpMessage +{ + private static final long serialVersionUID = 1L; + + public _501() + { + super(Smtp._501); + } + + public _501(String body) + { + super(Smtp._501, body); + } + + /*@Override + public Operator getOperator() + { + return Smtp._354; + }*/ +} diff --git a/scribble-demos/scrib/smtp/src/smtp/message/server/_535.java b/scribble-demos/scrib/smtp/src/smtp/message/server/_535.java new file mode 100644 index 000000000..b90db084a --- /dev/null +++ b/scribble-demos/scrib/smtp/src/smtp/message/server/_535.java @@ -0,0 +1,38 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package smtp.message.server; + +import smtp.Smtp.Smtp.Smtp; +import smtp.message.SmtpMessage; + +public class _535 extends SmtpMessage +{ + private static final long serialVersionUID = 1L; + + public _535() + { + super(Smtp._535); + } + + public _535(String body) + { + super(Smtp._535, body); + } + + /*@Override + public Operator getOperator() + { + return Smtp._354; + }*/ +} diff --git a/scribble-demos/scrib/threebuyer/src/threebuyer/ThreeBuyer.scr b/scribble-demos/scrib/threebuyer/src/threebuyer/ThreeBuyer.scr new file mode 100644 index 000000000..6e691d748 --- /dev/null +++ b/scribble-demos/scrib/threebuyer/src/threebuyer/ThreeBuyer.scr @@ -0,0 +1,53 @@ +/** + * Taken from [MSCS16] Global Progress for Dynamically Interleaved Sessions + */ + +module threebuyer.ThreeBuyer; + + +data "java.lang.Integer" from "rt.jar" as Int; +data "java.lang.String" from "rt.jar" as String; +data "test.twobuyer.Date" from "test/twobuyer/Date.java" as Date; + + +// 1 = B, 2 = A, 3 = S +global protocol TwoBuyer(role A, role B, role S) +{ + (String) from A to S; + (Int) from S to A; + (Int) from S to B; + (Int) from A to B; + do TwoBuyerChoice(A, B, S); +} + +aux global protocol TwoBuyerChoice(role A, role B, role S) +{ + choice at B + { + ok(String) from B to A; + ok(String) from B to S; + (Date) from S to B; + } + or + { + quit() from B to A; + quit() from B to S; + } +} + + +// 1 = C, 2 = B +//global protocol ThreeBuyer(role C, role B) +global protocol Proto(role C, role B) +{ + (Int) from B to C; // Should be same value as the Int on line 19 + (TwoBuyerChoice@B) from B to C; + choice at C + { + ok() from C to B; // Not enforced: consistency of "ok" choice here and in the delegated session + } + or + { + quit() from C to B; + } +} diff --git a/scribble-demos/scrib/threebuyer/src/threebuyer/ThreeBuyer2.scr b/scribble-demos/scrib/threebuyer/src/threebuyer/ThreeBuyer2.scr new file mode 100644 index 000000000..ab1eef33f --- /dev/null +++ b/scribble-demos/scrib/threebuyer/src/threebuyer/ThreeBuyer2.scr @@ -0,0 +1,61 @@ +module threebuyer.ThreeBuyer2; + + +data "java.lang.Integer" from "rt.jar" as Int; +data "java.lang.String" from "rt.jar" as String; +data "test.twobuyer.Date" from "test/twobuyer/Date.java" as Date; + + +// 1 = B, 2 = A, 3 = S +explicit global protocol Proto(role A, role B, role S, role C) +{ + connect A to B; + connect A to S; + connect B to S; + (String) from A to S; + (Int) from S to A; + (Int) from S to B; + (Int) from A to B; + do ThreeBuyerChoice(A, B, S, C); +} + +aux global protocol ThreeBuyerChoice(role A, role B, role S, role C) +{ + choice at B + { + do TwoBuyerChoice(A, B, S); + } + or + { + dummy() from B to A; + dummy() from B to S; + connect B to C; + (Int) from B to C; + connect C to A; + connect C to S; + do TwoBuyerChoice(A, C, S); + choice at C + { + ok() from C to B; + } + or + { + quit() from C to B; + } + } +} + +aux global protocol TwoBuyerChoice(role A, role B, role S) +{ + choice at B + { + ok(String) from B to A; + ok(String) from B to S; + (Date) from S to B; + } + or + { + quit() from B to A; + quit() from B to S; + } +} diff --git a/scribble-demos/scrib/travel/src/travel/BookingA.java b/scribble-demos/scrib/travel/src/travel/BookingA.java new file mode 100644 index 000000000..26391c76b --- /dev/null +++ b/scribble-demos/scrib/travel/src/travel/BookingA.java @@ -0,0 +1,87 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package travel; + +import java.io.IOException; +import java.util.concurrent.ExecutionException; + +import org.scribble.main.ScribRuntimeException; +import org.scribble.runtime.message.ObjectStreamFormatter; +import org.scribble.runtime.net.ScribServerSocket; +import org.scribble.runtime.net.SocketChannelEndpoint; +import org.scribble.runtime.net.SocketChannelServer; +import org.scribble.runtime.session.MPSTEndpoint; + +import travel.Travel.Booking.Booking; +import travel.Travel.Booking.roles.A; +import travel.Travel.Booking.statechans.A.Booking_A_1; +import travel.Travel.Booking.statechans.A.Booking_A_1_Cases; + +public class BookingA +{ + public static void main(String[] args) throws IOException, + ScribRuntimeException, ExecutionException, InterruptedException + { + try (ScribServerSocket ss_C = new SocketChannelServer(7777)) + { + while (true) + { + int quote = 1000; + + Booking booking = new Booking(); + try (MPSTEndpoint se = new MPSTEndpoint<>(booking, + Booking.A, new ObjectStreamFormatter())) + { + se.accept(ss_C, Booking.C); + + //Thread.sleep(1000); // CHECKME: ensure S is ready + + se.request(Booking.S, SocketChannelEndpoint::new, "localhost", 9999); + + Booking_A_1 s1 = new Booking_A_1(se); + Booking_A_1_Cases s1cases; + X: while (true) + { + s1cases = s1.branch(Booking.C); + switch (s1cases.op) + { + case Query: + s1 = s1cases.receive(Booking.Query) + .send(Booking.C, Booking.Quote, quote -= 100) + .send(Booking.S, Booking.Dummy); + break; + case No: + s1cases.receive(Booking.No) + .send(Booking.S, Booking.No) + .receive(Booking.C, Booking.Bye); + break X; + case Yes: + System.out.println("Yes: "); + s1cases.receive(Booking.Yes) + .send(Booking.S, Booking.Yes) + .receive(Booking.C, Booking.Bye); + break X; + } + } + + System.out.println("Done:"); + } + catch (Exception e) + { + e.printStackTrace(); + } + } + } + } +} diff --git a/scribble-demos/scrib/travel/src/travel/BookingC.java b/scribble-demos/scrib/travel/src/travel/BookingC.java new file mode 100644 index 000000000..b9574c376 --- /dev/null +++ b/scribble-demos/scrib/travel/src/travel/BookingC.java @@ -0,0 +1,149 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package travel; + +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +import org.scribble.runtime.message.ObjectStreamFormatter; +import org.scribble.runtime.net.SocketChannelEndpoint; +import org.scribble.runtime.session.MPSTEndpoint; +import org.scribble.runtime.util.Buf; + +import travel.Travel.Booking.Booking; +import travel.Travel.Booking.roles.C; +import travel.Travel.Booking.statechans.C.Booking_C_1; +import travel.Travel.Booking.statechans.C.Booking_C_5; + + +public class BookingC +{ + static int MAX = 500; + static List QUERIES = IntStream.range(97, 122) + .mapToObj(i -> new Character((char) i).toString()) + .collect(Collectors.toList()); + + public static void main(String[] args) throws Exception + { + Booking booking = new Booking(); + try (MPSTEndpoint se = new MPSTEndpoint<>(booking, Booking.C, + new ObjectStreamFormatter())) + { + se.request(Booking.A, SocketChannelEndpoint::new, "localhost", 7777); + se.request(Booking.S, SocketChannelEndpoint::new, "localhost", 8888); + Booking_C_1 s1 = new Booking_C_1(se); + + Buf quote = new Buf<>(); + Booking_C_5 s3; + for (int i = 0; ; i++) + { + if (i >= QUERIES.size()) + { + s3 = s1.send(Booking.A, Booking.No); + break; + } + System.out.println("Querying: " + QUERIES.get(i)); + s1 = s1.send(Booking.A, Booking.Query, QUERIES.get(i)) + .receive(Booking.A, Booking.Quote, quote); + System.out.println("Quoted: " + quote.val); + if (quote.val <= MAX) + { + System.out.println("Yes: "); + s3 = s1.send(Booking.A, Booking.Yes) + .send(Booking.S, Booking.Payment, "...") + .receive(Booking.S, Booking.Ack); + break; + } + } + s3.send(Booking.A, Booking.Bye); + + //foo(s1, quote); + //doQuery(s1, 0, quote).send(Booking.A, Booking.Bye); + + System.out.println("End: "); + } + } + + /*private static void foo(Booking_C_1 s1, Buf buf) throws Exception + { + for (int i = 0; i < QUERIES.size(); i++) // Stream.forEach not suitable due to Exceptions + { + System.out.println("Querying: " + QUERIES.get(i)); + s1 = s1.send(Booking.A, Booking.Query, QUERIES.get(i)) + .receive(Booking.A, Booking.Quote, buf); + System.out.println("Quoted: " + buf.val); + if (buf.val <= MAX) + { + System.out.println("Yes: "); + s1.send(Booking.A, Booking.Yes) + .send(Booking.S, Booking.Payment, "...") + .receive(Booking.S, Booking.Ack) + .send(Booking.A, Booking.Bye); + return; + } + } + s1.send(Booking.A, Booking.No).send(Booking.A, Booking.Bye); + }*/ + + private static Booking_C_5 doQuery(Booking_C_1 s1, int i, Buf buf) throws Exception + { + return (i >= QUERIES.size()) + ? s1.send(Booking.A, Booking.No) + //: foo3(s1.send(Booking.A, Booking.Query, println(QUERIES.get(i), QUERIES.get(i))).receive(Booking.Quote, QUOTE), i, println(QUOTE.val, Integer.toString(QUOTE.val))); + : checkMax(s1.send(Booking.A, Booking.Query, QUERIES.get(i)) + .receive(Booking.A, Booking.Quote, buf) + , i, buf); + } + + private static Booking_C_5 checkMax(Booking_C_1 s1, int i, Buf buf) throws Exception + { + return (buf.val <= MAX) + ? s1.send(Booking.A, Booking.Yes) + .send(Booking.S, Booking.Payment, "...") + .receive(Booking.S, Booking.Ack) + : doQuery(s1, i + 1, buf); + } + + /*private static T println(T t, String m) + { + System.out.println(m); + return t; + }*/ + + /*static Optional opt; + private static Booking_C_1 foo2(Booking_C_1 s1, int i) throws Exception + { + return (i >= QUERIES.size()) + ? ((opt = foo3(s1.send(Booking.A, Booking.Query, QUERIES.get(i)).receive(Booking.Quote, QUOTE), QUOTE.val)).isPresent()) + ? null + : null + : s1.send(, op);; + /*if (QUOTE.val <= MAX) + { + s1.send(Booking.A, Booking.Yes).send(Booking.S, Booking.Payment, "...").receive(Booking.Ack); + } + else + { + if () + }* / + } + + private static Optional foo3(Booking_C_1 s1, int quote) throws Exception + { + return (quote <= MAX) + ? Optional.of(quote) + : Optional.empty(); + }*/ +} diff --git a/scribble-demos/scrib/travel/src/travel/BookingS.java b/scribble-demos/scrib/travel/src/travel/BookingS.java new file mode 100644 index 000000000..6d59298fa --- /dev/null +++ b/scribble-demos/scrib/travel/src/travel/BookingS.java @@ -0,0 +1,82 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package travel; + +import java.io.IOException; +import java.util.concurrent.ExecutionException; + +import org.scribble.main.ScribRuntimeException; +import org.scribble.runtime.message.ObjectStreamFormatter; +import org.scribble.runtime.net.ScribServerSocket; +import org.scribble.runtime.net.SocketChannelServer; +import org.scribble.runtime.session.MPSTEndpoint; +import org.scribble.runtime.util.Buf; + +import travel.Travel.Booking.Booking; +import travel.Travel.Booking.roles.S; +import travel.Travel.Booking.statechans.S.Booking_S_1; +import travel.Travel.Booking.statechans.S.Booking_S_1_Cases; + +public class BookingS +{ + public static void main(String[] args) throws IOException, + ScribRuntimeException, ExecutionException, InterruptedException + { + try (ScribServerSocket ss_C = new SocketChannelServer(8888); + ScribServerSocket ss_A = new SocketChannelServer(9999)) + { + while (true) + { + Booking booking = new Booking(); + try (MPSTEndpoint se = new MPSTEndpoint<>(booking, + Booking.S, new ObjectStreamFormatter())) + { + //S.register(Booking.A, ss_A); + + se.accept(ss_C, Booking.C); + se.accept(ss_A, Booking.A); + Buf payment = new Buf<>(); + + Booking_S_1 s1 = new Booking_S_1(se); + Booking_S_1_Cases s1cases; + X: while (true) + { + s1cases = s1.branch(Booking.A); + switch (s1cases.op) + { + case Dummy: + s1 = s1cases.receive(Booking.Dummy); + break; + case No: + s1cases.receive(Booking.No); + break X; + case Yes: + System.out.println("Yes: "); + s1cases.receive(Booking.Yes) + .receive(Booking.C, Booking.Payment, payment) + .send(Booking.C, Booking.Ack); + break X; + } + } + + System.out.println("Done:"); + } + catch (Exception e) + { + e.printStackTrace(); + } + } + } + } +} diff --git a/scribble-demos/scrib/travel/src/travel/Travel.scr b/scribble-demos/scrib/travel/src/travel/Travel.scr new file mode 100644 index 000000000..e7444b514 --- /dev/null +++ b/scribble-demos/scrib/travel/src/travel/Travel.scr @@ -0,0 +1,78 @@ +//$ ./scribblec.sh -ip scribble-demos/scrib/travel/src -d scribble-demos/scrib/travel/src scribble-demos/scrib/travel/src/travel/Travel.scr -api Booking C +//$ javadoc -cp scribble-core/target/classes:scribble-runtime/target/classes:scribble-demos/scrib/travel/src -subpackages travel.Travel.Booking -d scribble-demos/scrib/travel/javadoc + +module travel.Travel; + +data "java.lang.Integer" from "rt.jar" as Int; +data "java.lang.String" from "rt.jar" as String; + + +//* +global protocol Booking(role C, role A, role S) +{ + choice at C + { + Query(String) from C to A; + Quote(Int) from A to C; + Dummy() from A to S; // Dummy + do Booking(C, A, S); + } + or + { + choice at C + { + Yes() from C to A; + Yes() from A to S; + Payment(String) from C to S; + Ack() from S to C; + } + or + { + No() from C to A; + No() from A to S; + } + Bye() from C to A; + } +} +//*/ + + +/* +explicit global protocol BookingExp(role C, role A, role S) +{ + connect C to A; + do BookingExpAux(C, A, S); +} + +aux global protocol BookingExpAux(role C, role A, role S) +{ + choice at C + { + Query(String) from C to A; + Quote(Int) from A to C; + //continue X; + do BookingExpAux(C, A, S); + } + or + { + choice at C + { + Yes() from C to A; + connect A to S; + Yes() from A to S; + //disconnect A and S; // Disconnects not needed in non-recursive flows + + connect S to C; // Needs session id to correlate connections -- ideally fresh "shared channels" + Payment(String) from C to S; + Ack() from S to C; + + //disconnect S and C; + } + or + { + No() from C to A; + } + Bye() from C to A; + } +} +//*/ diff --git a/scribble-demos/scrib/tutorial/src/tutorial/adder/Adder.scr b/scribble-demos/scrib/tutorial/src/tutorial/adder/Adder.scr new file mode 100644 index 000000000..15359f537 --- /dev/null +++ b/scribble-demos/scrib/tutorial/src/tutorial/adder/Adder.scr @@ -0,0 +1,30 @@ +/** + * Assuming scribblec.sh in the scribble-java root directory: + * + * Check Adder protocol: + * $ ./scribblec.sh scribble-demos/scrib/tutorial/src/tutorial/adder/Adder.scr + * + * Generate Endpoint API for C: + * $ ./scribblec.sh scribble-demos/scrib/tutorial/src/tutorial/adder/Adder.scr -d scribble-demos/scrib/tutorial/src/ -api Adder C + * + * [Java] Generate javadoc from Endpoint API(s): + * $ javadoc -cp scribble-core/target/classes:scribble-runtime/target/classes:scribble-demos/scrib/tutorial/src -subpackages tutorial.adder.Adder.Adder -d scribble-demos/scrib/tutorial/javadoc/adder + * + */ + + +module tutorial.adder.Adder; + + +data "java.lang.Integer" from "rt.jar" as Int; + + +global protocol Adder(role C, role S) { + choice at C { + Add(Int, Int) from C to S; + Res(Int) from S to C; + do Adder(C, S); + } or { + Bye() from C to S; + } +} diff --git a/scribble-demos/scrib/tutorial/src/tutorial/adder/AdderC.java b/scribble-demos/scrib/tutorial/src/tutorial/adder/AdderC.java new file mode 100644 index 000000000..2c2c1c3a4 --- /dev/null +++ b/scribble-demos/scrib/tutorial/src/tutorial/adder/AdderC.java @@ -0,0 +1,62 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package tutorial.adder; + +import static tutorial.adder.Adder.Adder.Adder.Add; +import static tutorial.adder.Adder.Adder.Adder.Bye; +import static tutorial.adder.Adder.Adder.Adder.C; +import static tutorial.adder.Adder.Adder.Adder.Res; +import static tutorial.adder.Adder.Adder.Adder.S; + +import org.scribble.runtime.message.ObjectStreamFormatter; +import org.scribble.runtime.net.SocketChannelEndpoint; +import org.scribble.runtime.session.MPSTEndpoint; +import org.scribble.runtime.util.Buf; + +import tutorial.adder.Adder.Adder.Adder; +import tutorial.adder.Adder.Adder.roles.C; +import tutorial.adder.Adder.Adder.statechans.C.Adder_C_1; +import tutorial.adder.Adder.Adder.statechans.C.Adder_C_2; + +public class AdderC { + + public static void main(String[] args) throws Exception { + Adder adder = new Adder(); + try (MPSTEndpoint client = + new MPSTEndpoint<>(adder, C, new ObjectStreamFormatter())) { + client.request(S, SocketChannelEndpoint::new, "localhost", 8888); + int n = 10; + System.out.println(n + "th Fibonacci number: " + + fibo(new Adder_C_1(client), n)); + } + } + + private static int fibo(Adder_C_1 c1, int n) throws Exception { + Buf x = new Buf<>(0); + Buf y = new Buf<>(1); + Buf i = new Buf<>(1); + while (i.val < n) { + Adder_C_2 c2 = c1.send(S, Add, x.val, y.val); + x.val = y.val; + c1 = c2.receive(S, Res, y); + c1 = add1(c1, i); + } + c1.send(S, Bye); // EndSocket + return x.val; + } + + private static Adder_C_1 add1(Adder_C_1 c1, Buf i) throws Exception { + return c1.send(S, Add, i.val, 1).receive(S, Res, i); + } +} diff --git a/scribble-demos/scrib/tutorial/src/tutorial/adder/AdderS.java b/scribble-demos/scrib/tutorial/src/tutorial/adder/AdderS.java new file mode 100644 index 000000000..be7359d94 --- /dev/null +++ b/scribble-demos/scrib/tutorial/src/tutorial/adder/AdderS.java @@ -0,0 +1,65 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package tutorial.adder; + +import static tutorial.adder.Adder.Adder.Adder.Add; +import static tutorial.adder.Adder.Adder.Adder.Bye; +import static tutorial.adder.Adder.Adder.Adder.C; +import static tutorial.adder.Adder.Adder.Adder.Res; +import static tutorial.adder.Adder.Adder.Adder.S; + +import java.io.IOException; + +import org.scribble.main.ScribRuntimeException; +import org.scribble.runtime.message.ObjectStreamFormatter; +import org.scribble.runtime.net.ScribServerSocket; +import org.scribble.runtime.net.SocketChannelServer; +import org.scribble.runtime.session.MPSTEndpoint; +import org.scribble.runtime.util.Buf; + +import tutorial.adder.Adder.Adder.Adder; +import tutorial.adder.Adder.Adder.roles.S; +import tutorial.adder.Adder.Adder.statechans.S.Adder_S_1; +import tutorial.adder.Adder.Adder.statechans.S.Adder_S_1_Cases; + +public class AdderS { + + public static void main(String[] args) throws Exception { + try (ScribServerSocket ss = new SocketChannelServer(8888)) { + while (true) { + Adder adder = new Adder(); + try (MPSTEndpoint server + = new MPSTEndpoint<>(adder, S, new ObjectStreamFormatter())) { + server.accept(ss, C); + new AdderS().run(new Adder_S_1(server)); + } catch (ScribRuntimeException | IOException | ClassNotFoundException e) { + e.printStackTrace(); + } + } + } + } + + private void run(Adder_S_1 s1) throws Exception { + Buf x = new Buf<>(); + Buf y = new Buf<>(); + while (true) { + Adder_S_1_Cases cases = s1.branch(C); + switch (cases.op) { + case Add: s1 = cases.receive(Add, x, y) + .send(C, Res, x.val+y.val); break; + case Bye: cases.receive(Bye); return; + } + } + } +} diff --git a/scribble-demos/scrib/twobuyer/src/twobuyer/TwoBuyer.scr b/scribble-demos/scrib/twobuyer/src/twobuyer/TwoBuyer.scr new file mode 100644 index 000000000..c9565fc2b --- /dev/null +++ b/scribble-demos/scrib/twobuyer/src/twobuyer/TwoBuyer.scr @@ -0,0 +1,61 @@ +module twobuyer.TwoBuyer; + + +data "java.lang.Integer" from "rt.jar" as int; +data "java.lang.String" from "rt.jar" as String; +data "test.twobuyer.Address" from "test/twobuyer/Address.java" as Address; +data "test.twobuyer.Date" from "test/twobuyer/Date.java" as Date; + + +global protocol TwoBuyer(role A, role B, role S) +{ + title(String) from A to S; + //quote(int) from S to A, B; // EFSM building for multicast not currently supported + quote(int) from S to A; + quote(int) from S to B; + quoteByTwo(int) from A to B; + choice at B + { + ok(Address) from B to S; + (Date) from S to B; + } + or + { + quit() from B to S; + } +} + + +global protocol TwoBuyerAlt(role A, role B, role S) +{ + title(String) from A to S; + choice at S // Not expressible by "directed" choice + { + quote1(int) from S to A; + //(int) from A to B; // Not supported (inconsistent local choice subject) + (int) from A to S; + quote2(int) from S to B; + do TwoBuyerAltAux(B, S); + } + or + { + quote1(int) from S to B; + //(int) from B to A; + (int) from B to S; + quote2(int) from S to A; + do TwoBuyerAltAux(A, S); + } +} + +aux global protocol TwoBuyerAltAux(role C, role S) +{ + choice at C + { + ok(Address) from C to S; + (Date) from S to C; + } + or + { + quit() from C to S; + } +} diff --git a/scribble-dist/pom.xml b/scribble-dist/pom.xml new file mode 100644 index 000000000..87a484261 --- /dev/null +++ b/scribble-dist/pom.xml @@ -0,0 +1,81 @@ + + + + 4.0.0 + + + scribble-dist + pom + + + + org.scribble + scribble-core + + + org.scribble + scribble-ast + + + org.scribble + scribble-parser + + + org.scribble + scribble-cli + + + org.scribble + scribble-codegen + + + + org.scribble + scribble-runtime + + + + + org.scribble + parent + 0.5.1-SNAPSHOT + ../pom.xml + + + + + + + maven-assembly-plugin + + + src/main/scripts/distro-assembly.xml + + false + + + + distro-assembly + package + + single + + + + + + + + + scribble-dist + Scribble distribution. + + diff --git a/scribble-dist/src/main/resources/scribblec.sh b/scribble-dist/src/main/resources/scribblec.sh new file mode 100644 index 000000000..6de535a89 --- /dev/null +++ b/scribble-dist/src/main/resources/scribblec.sh @@ -0,0 +1,199 @@ +#!/bin/sh +# +# Copyright 2008 The Scribble 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 +# +# http://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. +# + + +## +# Config: +# +# $SCRIBBLE_HOME +# Set this to the `scribble-java` root directory. +# i.e., the directory of the `parent` mvn module (that contains the +# `scribble-ast`, `scribble-cli`, etc. mvn submodules), +# or the directory that contains the `lib` directory containing the generated +# distribution jars. +if [ -z "${SCRIBBLE_HOME}" ]; then + SCRIBHOME=$(dirname "$0") +else + SCRIBHOME=${SCRIBBLE_HOME} +fi + +# ANTLR 3 runtime jar location. +# Set this to the location of the ANTLR 3 runtime jar, or place the jar in: +# `$SCRIBHOME/lib`. (This script looks for the ANTLR jar in those locations.) +ANTLR_RUNTIME_JAR=$SCRIBHOME'/scribble-parser/lib/antlr-3.5.2-complete.jar' + # e.g., '~/.m2/repository/org/antlr/antlr-runtime/3.4/antlr-runtime-3.4.jar' + # or '/cygdrive/c/Users/[User]/.m2/repository/org/antlr/antlr-runtime/3.4/antlr-runtime-3.4.jar' + # (i.e., the Maven install location) + +# Local env. +JAVA='java' # Java executable +WSL=0 # Set to 1 for ';' classpath separator and wslpath formatting +CYGWIN=0 # Set to 1 for ';' classpath separator and cygpath formatting + +#if [ "$(uname | grep -c CYGWIN)" -ne 0 ]; then +# CYGWIN=1 +#fi +# +## + + +usage() { + echo 'Set $SCRIBBLE_HOME to the scribble-java root directory (default: current dir).' + cat < [option]...' + + Source Scribble module (.scr file) + +Options: + -h, --help Show this info and exit + -v Scribble debug info + --verbose Echo the java command + + -ip Scribble module import path + + -project Project protocol + + -fsm Generate default Endpoint FSM + -aut Output as aut (instead of dot) + -fsmpng + Draw default Endpoint FSM as png (via dot) + -vfsm, -ufsm + -vfsmpng, -ufsmpng + Output the EFSM used in validation (or the "unfair" variant) + -minlts + Minimise EFSMs for dot output and API generation (but not validation) + (Requires ltsconvert) + + + -model Generate global model + -modelpng + Draw global model as png (requires dot) + -fair Assume fair output choices + -umodel, -umodelpng (with appropriate args) "Unfair" variant + + + -api Generate Java Endpoint API + -d API output directory + -sessapi Generate Session API only + -chanapi Generate State Channel API only + -subtypes Enable subtypes for -chanapi +EOF +} + + +SEP=':' # Classpath separator +if [ "$WSL" = 1 ] || [ "$CYGWIN" = 1 ]; then + SEP=';' +fi + +fixpath() { + p="$1" + if [ "$WSL" = 1 ]; then + p=$(wslpath -w "$p" | sed 's/\\/\\\\/g') + elif [ "$CYGWIN" = 1 ]; then + p=$(cygpath -pw "$p") + fi + printf "%s" "$p" +} + +CLASSPATH= +# If first module dir present, assume all are... +if [ -d "$SCRIBHOME"'/scribble-ast/target/classes' ]; then + CLASSPATH=$(fixpath "$SCRIBHOME"'/scribble-ast/target/classes') + CLASSPATH="$CLASSPATH$SEP"$(fixpath "$SCRIBHOME"'/scribble-cli/target/classes') + CLASSPATH="$CLASSPATH$SEP"$(fixpath "$SCRIBHOME"'/scribble-codegen/target/classes') + CLASSPATH="$CLASSPATH$SEP"$(fixpath "$SCRIBHOME"'/scribble-core/target/classes') + CLASSPATH="$CLASSPATH$SEP"$(fixpath "$SCRIBHOME"'/scribble-main/target/classes') + CLASSPATH="$CLASSPATH$SEP"$(fixpath "$SCRIBHOME"'/scribble-parser/target/classes') +fi +# If first module jar present, assume all are... +if [ -f "$SCRIBHOME"'/lib/scribble-ast.jar' ]; then + if [ ! -z "$CLASSPATH" ]; then + CLASSPATH="$CLASSPATH$SEP" + fi + CLASSPATH="$CLASSPATH"$(fixpath "$SCRIBHOME"'/lib/scribble-ast.jar') + CLASSPATH="$CLASSPATH$SEP"$(fixpath "$SCRIBHOME"'/lib/scribble-cli.jar') + CLASSPATH="$CLASSPATH$SEP"$(fixpath "$SCRIBHOME"'/lib/scribble-codegen.jar') + CLASSPATH="$CLASSPATH$SEP"$(fixpath "$SCRIBHOME"'/lib/scribble-core.jar') + CLASSPATH="$CLASSPATH$SEP"$(fixpath "$SCRIBHOME"'/lib/scribble-main.jar') + CLASSPATH="$CLASSPATH$SEP"$(fixpath "$SCRIBHOME"'/lib/scribble-parser.jar') +fi +# Below assumes CLASSPATH non-empty +if [ -f "$ANTLR_RUNTIME_JAR" ]; then + CLASSPATH="$CLASSPATH$SEP"$(fixpath "$ANTLR_RUNTIME_JAR") +fi +if [ -f "$SCRIBHOME"'/lib/antlr.jar' ]; then + CLASSPATH="$CLASSPATH$SEP"$(fixpath "$SCRIBHOME"'/lib/antlr.jar') +fi +if [ -f "$SCRIBHOME"'/lib/antlr-runtime.jar' ]; then + CLASSPATH="$CLASSPATH$SEP"$(fixpath "$SCRIBHOME"'/lib/antlr-runtime.jar') +fi +#if [ -f '/lib/commons-io.jar' ]; then +# CLASSPATH=$CLASSPATH$SEP$(fixpath $SCRIBHOME'/lib/commons-io.jar') +#fi +#CLASSPATH=$CLASSPATH':'$SCRIBHOME'/lib/stringtemplate.jar' +##CLASSPATH=\'"$(fixpath "$CLASSPATH")"\' + + +usage=0 +verbose=0 +ARGS= + +while true; do + case "$1" in + "") + break + ;; + -h) + usage=1 + break + ;; + --help) + usage=1 + break + ;; + --verbose) + verbose=1 + shift + ;; + *) + ARGS="$ARGS '$1'" + shift + ;; + esac +done + +if [ "$usage" = 1 ] || [ -z "$ARGS" ]; then + + usage + exit 0 +fi + + +CMD="$JAVA"' -cp '\'"$CLASSPATH"\'' org.scribble.cli.CommandLine' + +scribblec() { + eval "$CMD" "$@" +} + +if [ "$verbose" = 1 ]; then + echo "$CMD" "$ARGS" +fi + +scribblec "$ARGS" + diff --git a/scribble-dist/src/main/scripts/distro-assembly.xml b/scribble-dist/src/main/scripts/distro-assembly.xml new file mode 100644 index 000000000..f23279a45 --- /dev/null +++ b/scribble-dist/src/main/scripts/distro-assembly.xml @@ -0,0 +1,49 @@ + + + + + distribution + + zip + + + false + ${project.build.finalName} + + + + src/main/resources + + + + + + + lib + false + ${artifact.artifactId}.${artifact.extension} + false + 0644 + 0755 + + + + + diff --git a/scribble-main/pom.xml b/scribble-main/pom.xml new file mode 100644 index 000000000..f4ef86985 --- /dev/null +++ b/scribble-main/pom.xml @@ -0,0 +1,40 @@ + + + 4.0.0 + + + scribble-main + + + + org.scribble + scribble-core + + + org.scribble + scribble-parser + + + org.scribble + scribble-ast + + + + junit + junit + test + + + + + org.scribble + parent + 0.5.1-SNAPSHOT + ../pom.xml + + + + scribble-main + + diff --git a/scribble-main/src/main/java/org/scribble/main/Main.java b/scribble-main/src/main/java/org/scribble/main/Main.java new file mode 100644 index 000000000..10e82a04c --- /dev/null +++ b/scribble-main/src/main/java/org/scribble/main/Main.java @@ -0,0 +1,187 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.main; + +import java.nio.file.Path; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; +import java.util.stream.Collectors; + +import org.scribble.ast.AstFactory; +import org.scribble.ast.AstFactoryImpl; +import org.scribble.ast.ImportDecl; +import org.scribble.ast.ImportModule; +import org.scribble.ast.Module; +import org.scribble.core.job.CoreArgs; +import org.scribble.core.type.name.ModuleName; +import org.scribble.del.DelFactory; +import org.scribble.del.DelFactoryImpl; +import org.scribble.job.Job; +import org.scribble.main.resource.Resource; +import org.scribble.main.resource.loader.ScribModuleLoader; +import org.scribble.main.resource.locator.ResourceLocator; +import org.scribble.parser.ScribAntlrWrapper; +import org.scribble.util.Pair; +import org.scribble.util.ScribException; +import org.scribble.util.ScribParserException; + +/** + * Main loads the main module, and then all other (transitively) imported + * modules. Its main purpose is to offer the newJob factory method. + * + * Main takes an abstract ResourceLocator, e.g. DirectoryResourceLocator -- (for + * non-inline main modules)... + * ...but because Resource is primarily based on file paths, it takes mainpath + * (rather than something more abstract, e.g., URI) to identify the "main" + * resource. + * + * TODO: Resource and ResourceLocator should be made more abstract from (file) + * paths (cf. use of modname.toPath in ScribModuleLoader). + */ +public class Main +{ + public final ModuleName main; + public final Map args; + + private final ScribAntlrWrapper antlr; + //private final ResourceLocator locator; // Path -> Resource + private final ScribModuleLoader loader; // ModuleName -> Pair + + // Keys are full names -- parsed are the modules read from file, distinguished from the generated projection modules + // Resource recorded for source path + private final Map> parsed + = new HashMap<>(); + + // Load main module from file system + // Load other modules via locator -- CHECKME: a bit inconsistent w.r.t. main? + // TODO: make Path abstract as e.g. URI -- locator is abstract but Path is coupled to concrete DirectoryResourceLocator + public Main(ResourceLocator locator, Path mainpath, + Map args) throws ScribException, ScribParserException + { + this(new Pair<>(locator, null), mainpath, args); + } + + // Load an inline module arg -- module imports not allowed (currently no ResourceLocator) + public Main(String inline, Map args) + throws ScribException, ScribParserException + { + this(new Pair<>(null, inline), null, args); + } + + // Pre: hack.left == null xor hack.right == null + // Hack to "unify" the constructors (to satisfy final field init more conveniently) + private Main(Pair hack, Path mainpath, + Map args) throws ScribException, ScribParserException + { + this.antlr = newAntlr(); + + // Set this.loader and load main + Pair main; + if (hack.right == null) + { + //this.locator = hack.left; + this.loader = new ScribModuleLoader(hack.left, this.antlr); + main = this.loader.loadMainModule(mainpath); + } + else + { + //this.locator = null; + this.loader = new ScribModuleLoader(null, this.antlr); // CHECKME: null locator OK? + main = this.loader.loadMainModule(hack.right); + if (main.right.getImportDeclChildren().stream() + .anyMatch(x -> x.isImportModule())) + { + throw new ScribException( + "Module imports not permitted in inline main modules."); + // Because (currently) null locator + } + } + + this.main = main.right.getFullModuleName(); + this.args = Collections.unmodifiableMap(args); + loadAllModuleImports(main); + } + + // A Scribble extension should override newAntlr/Job as appropriate + protected ScribAntlrWrapper newAntlr() + { + DelFactory df = newDelFactory(); + return new ScribAntlrWrapper(df); + } + + // N.B. not used by antlr generated parser itself (cf. ScribTreeAdaptor, takes source tokens and sets dels manually) + // Here (cf. Job) because it takes antlr for token creation (and lives in scribble-parser) + protected AstFactory newAstFactory(ScribAntlrWrapper antlr) + { + return new AstFactoryImpl(antlr); + } + + // Here (cf. Job) because df used by this.antlr and this.af (and lives in scribble-parser) + protected DelFactory newDelFactory() + { + return new DelFactoryImpl(); + } + + // For a Scribble extension, override newJob(parsed, args, mainFullname, AstFactory) + public final Job newJob() throws ScribException + { + AstFactory af = newAstFactory(this.antlr); + return newJob(getParsedModules(), this.args, this.main, af, this.antlr.df); + } + + // A Scribble extension should override newAntlr/Job as appropriate + protected Job newJob(Map parsed, + Map args, ModuleName mainFullname, AstFactory af, + DelFactory df) throws ScribException + { + // Was previously made inside Job, but AstFactoryImpl now lives in scribble-parser, to access ScribbleParser constants + return new Job(mainFullname, args, parsed, af, df); + } + + // Pre: main Module loaded by this.loader + // Given the already loaded main, populates this.parsed and this.modcs + // Does so by transitively loading all module imports + private void loadAllModuleImports(Pair main) + throws ScribParserException, ScribException + { + loadAllAux(main); // Populates this.parsed + } + + // Recursively records m in this.parsed and loads all module imports of m + private void loadAllAux(Pair m) + throws ScribParserException, ScribException + { + this.parsed.put(m.right.getFullModuleName(), m); + for (ImportDecl id : m.right.getImportDeclChildren()) + { + if (id.isImportModule()) + { + ModuleName fullname = + ((ImportModule) id).getModuleNameNodeChild().toName(); + if (!this.parsed.containsKey(fullname)) + { + loadAllAux(this.loader.loadModule(fullname)); + } + } + } + } + + public Map getParsedModules() + { + return this.parsed.entrySet().stream() + .collect(Collectors.toMap(Entry::getKey, e -> e.getValue().right)); + } +} diff --git a/scribble-main/src/main/java/org/scribble/main/resource/AbstractResource.java b/scribble-main/src/main/java/org/scribble/main/resource/AbstractResource.java new file mode 100644 index 000000000..42ed19f4d --- /dev/null +++ b/scribble-main/src/main/java/org/scribble/main/resource/AbstractResource.java @@ -0,0 +1,44 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.main.resource; + + +/** + * This class represents the resource. + * + */ +public abstract class AbstractResource implements Resource +{ + private final String loc; + + /** + * The constructor. + * + * @param path The path to the resource -- the "full" path including import path prefix + */ + public AbstractResource(String loc) + { + this.loc = loc; + } + + + /** + * {@inheritDoc} + */ + @Override + public String getLocation() + { + return this.loc; + } +} diff --git a/scribble-main/src/main/java/org/scribble/main/resource/FileResource.java b/scribble-main/src/main/java/org/scribble/main/resource/FileResource.java new file mode 100644 index 000000000..8aa56668b --- /dev/null +++ b/scribble-main/src/main/java/org/scribble/main/resource/FileResource.java @@ -0,0 +1,58 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.main.resource; + +import java.nio.file.Path; + +/** + * This class represents the resource. + * + */ +public class FileResource extends AbstractResource +{ + private final Path path; + private java.io.InputStream _inputStream = null; + + /** + * The constructor. + * + * @param path The optional resource path + * @param is The input stream + */ + public FileResource(Path path, java.io.InputStream is) + { + super(path.toString()); + this.path = path; + this._inputStream = is; + } + + public Path getPath() + { + return path; + } + + @Override + public boolean isFileResource() + { + return true; + } + + /** + * {@inheritDoc} + */ + public java.io.InputStream getInputStream() + { + return (this._inputStream); + } +} diff --git a/scribble-main/src/main/java/org/scribble/main/resource/InlineResource.java b/scribble-main/src/main/java/org/scribble/main/resource/InlineResource.java new file mode 100644 index 000000000..b1ced5837 --- /dev/null +++ b/scribble-main/src/main/java/org/scribble/main/resource/InlineResource.java @@ -0,0 +1,53 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.main.resource; + +import java.io.ByteArrayInputStream; +import java.nio.charset.StandardCharsets; + + +// Module supplied directly as a String arg. +public class InlineResource extends AbstractResource +{ + //private final String res; + private java.io.InputStream _inputStream = null; + + /** + * The constructor. + * + * @param path The optional resource path + * @param is The input stream + */ + public InlineResource(String res) + { + super(Resource.INLINE_LOCATION); + //this.res = res; + this._inputStream = new ByteArrayInputStream( + res.getBytes(StandardCharsets.UTF_8)); + } + + @Override + public boolean isInlineResource() + { + return true; + } + + /** + * {@inheritDoc} + */ + public java.io.InputStream getInputStream() + { + return (this._inputStream); + } +} diff --git a/scribble-main/src/main/java/org/scribble/main/resource/Resource.java b/scribble-main/src/main/java/org/scribble/main/resource/Resource.java new file mode 100644 index 000000000..ccb388d6a --- /dev/null +++ b/scribble-main/src/main/java/org/scribble/main/resource/Resource.java @@ -0,0 +1,51 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.main.resource; + +import java.io.InputStream; + +/** + * This class represents the resource. + * + * CHECKME: maybe refactor core Resource classes out of cli package (generalise) + * + */ +public interface Resource +{ + public static final String INLINE_LOCATION = "-"; + + /** + * This method returns the resource path. + * + * @return The resource path -- the "full" path including import path prefix + */ + String getLocation(); + + default boolean isInlineResource() + { + return false; + } + + default boolean isFileResource() + { + return false; + } + + /** + * This method returns an input stream containing the resource content. -- FIXME: a "fresh" stream? + * + * @return The input stream + */ + InputStream getInputStream(); +} diff --git a/scribble-main/src/main/java/org/scribble/main/resource/loader/DefaultModuleLoader.java b/scribble-main/src/main/java/org/scribble/main/resource/loader/DefaultModuleLoader.java new file mode 100644 index 000000000..4959bd17c --- /dev/null +++ b/scribble-main/src/main/java/org/scribble/main/resource/loader/DefaultModuleLoader.java @@ -0,0 +1,53 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.main.resource.loader; + +import org.scribble.ast.Module; +import org.scribble.core.type.name.ModuleName; +import org.scribble.main.resource.Resource; +import org.scribble.util.Pair; +import org.scribble.util.ScribException; +import org.scribble.util.ScribParserException; + + +/** + * This class provides a default implementation of the module loader interface. + * + */ +public abstract class DefaultModuleLoader implements ModuleLoader +{ + // CHECKME: redundant? Modules recorded (and updated) in MainContext + private java.util.Map> _modules=new java.util.HashMap<>(); + + /** + * This method registers the supplied module. + * + * @param m The module + */ + public void registerModule(Resource res, Module m) + { + _modules.put(m.getFullModuleName(), new Pair<>(res, m)); + } + + /** + * {@inheritDoc} + * @throws ScribParserException + */ + @Override + public Pair loadModule(ModuleName fullname) + throws ScribParserException, ScribException + { + return (_modules.get(fullname)); + } +} diff --git a/scribble-main/src/main/java/org/scribble/main/resource/loader/ModuleLoader.java b/scribble-main/src/main/java/org/scribble/main/resource/loader/ModuleLoader.java new file mode 100644 index 000000000..77be9862c --- /dev/null +++ b/scribble-main/src/main/java/org/scribble/main/resource/loader/ModuleLoader.java @@ -0,0 +1,44 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.main.resource.loader; + +import org.scribble.ast.Module; +import org.scribble.core.type.name.ModuleName; +import org.scribble.main.resource.Resource; +import org.scribble.util.Pair; +import org.scribble.util.ScribException; +import org.scribble.util.ScribParserException; + + +/** + * This interface is responsible for loading modules. + * + * loading = sesstype.ModuleName -> Pair + * ModuleName --> Path --ResourceLocator--> Resource --AntlrParser--> ANTLR --ScribParser--> ScribNode + * + * FIXME: Path should be abstracted, e.g. URI (Path is tied to DirectoryResourceLocator) + */ +public interface ModuleLoader +{ + /** + * This method loads the module associated with the specified name. + * + * @param module The module name + * @return The module, or null if not found + * @throws ScribParserException + */ + public Pair loadModule(ModuleName fullname) + throws ScribParserException, ScribException; +} + diff --git a/scribble-main/src/main/java/org/scribble/main/resource/loader/ScribModuleLoader.java b/scribble-main/src/main/java/org/scribble/main/resource/loader/ScribModuleLoader.java new file mode 100644 index 000000000..50499f6fa --- /dev/null +++ b/scribble-main/src/main/java/org/scribble/main/resource/loader/ScribModuleLoader.java @@ -0,0 +1,120 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.main.resource.loader; + +import java.io.File; +import java.nio.file.Path; + +import org.antlr.runtime.tree.CommonTree; +import org.scribble.ast.Module; +import org.scribble.core.type.name.ModuleName; +import org.scribble.main.resource.InlineResource; +import org.scribble.main.resource.Resource; +import org.scribble.main.resource.locator.DirectoryResourceLocator; +import org.scribble.main.resource.locator.ResourceLocator; +import org.scribble.parser.ScribAntlrWrapper; +import org.scribble.util.Pair; +import org.scribble.util.ScribException; +import org.scribble.util.ScribParserException; + +// loading: ModuleName -> Module +// ModuleName --> Path --ResourceLocator--> Resource --ScribAntlrWrapper--> Module +public class ScribModuleLoader extends DefaultModuleLoader +{ + private ResourceLocator locator; + private ScribAntlrWrapper antlr; + + public ScribModuleLoader(ResourceLocator locator, ScribAntlrWrapper antlr) + { + this.locator = locator; + this.antlr = antlr; + } + + // CHECKME: check only called once? at start? + public Pair loadMainModule(Path mainpath) + throws ScribException, ScribParserException + { + Resource res = DirectoryResourceLocator.getResourceByFullPath(mainpath); + // Hardcoded to DirectoryResourceLocator + Module m = this.antlr.parse(res.getInputStream()); // Does del decoration + ScribModuleLoader.checkMainModuleName(mainpath, m); + ModuleName fullname = m.getFullModuleName(); + Pair cached = super.loadModule(fullname); + if (cached != null) + { + return cached; // CHECKME: compare loaded against cached? + } + registerModule(res, m); + return new Pair<>(res, m); + } + + // CHECKME: check only called once? at start? + public Pair loadMainModule(String inline) + throws ScribException, ScribParserException + { + Resource res = new InlineResource(inline); + Module m = (Module) this.antlr.parse(res.getInputStream()); // Does del decoration + registerModule(res, m); + return new Pair<>(res, m); + } + + // Used to load import modules (not the main module) + @Override + public Pair loadModule(ModuleName fullname) + throws ScribException, ScribParserException + { + Pair cached = super.loadModule(fullname); + if (cached != null) + { + return cached; + } + Resource res = this.locator.getResource(fullname.toPath()); + Module m = this.antlr.parse(res.getInputStream()); // Does del decoration + ScribModuleLoader.checkModuleName(fullname, res, m); + registerModule(res, m); + return new Pair<>(res, m); + } + + // Check module loaded from fullname.toPath has the expected mod decl + private static void checkModuleName(ModuleName fullname, Resource res, + Module m) + { + if (!fullname.equals(m.getFullModuleName())) + { + throw new RuntimeException("Invalid module name " + + m.getFullModuleName() + " at location: " + res.getLocation()); + } + } + + // For main module loaded from a path, check only the simple module name against the last path element + // Not Scribble's job to check nested directory location of module fully corresponds to the full name of module, cf. Java classes + private static void checkMainModuleName(Path mainpath, Module main) + throws ScribException + { + String path = mainpath.toString(); // FIXME: hack + // FileSystems.getDefault().getSeparator() ? + int last = path.lastIndexOf(File.separator); + String tmp = path.substring((last == -1) + ? 0 + : last + 1, path.lastIndexOf('.')); + if (!tmp.equals(main.getFullModuleName().getSimpleName().toString())) + // ModuleName.toString hack? + { + CommonTree source = main.getModuleDeclChild().getNameNodeChild() + .getSource(); + throw new ScribException(source, "Simple module name at path " + path + + " mismatch: " + main.getFullModuleName()); + } + } +} diff --git a/scribble-main/src/main/java/org/scribble/main/resource/locator/DirectoryResourceLocator.java b/scribble-main/src/main/java/org/scribble/main/resource/locator/DirectoryResourceLocator.java new file mode 100644 index 000000000..5d5d47fe4 --- /dev/null +++ b/scribble-main/src/main/java/org/scribble/main/resource/locator/DirectoryResourceLocator.java @@ -0,0 +1,87 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.main.resource.locator; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.LinkedList; +import java.util.List; + +import org.scribble.main.resource.FileResource; +import org.scribble.util.ScribException; + +/** + * This class provides a directory based resource locator. + * + */ +// TODO: rename exceptions +public class DirectoryResourceLocator extends ResourceLocator +{ + //private static final Logger LOG = Logger.getLogger(DirectoryResourceLocator.class.getName()); // TODO: + + private List impaths; + + /** + * This is the constructor for the directory resource + * locator, initialised with a ':' separated list + * of root directories. + * + * @param paths The ':' separated list of directory paths + */ + public DirectoryResourceLocator(List paths) + { + this.impaths = new LinkedList<>(paths); + } + + // TODO: need to sort out what "getResource" should mean at level of ResourceLocator abstraction... + // ...e.g. if arg is specifically a Path or more abstract, whether it is the complete location or partial, etc + @Override + public FileResource getResource(Path path) throws ScribException + { + for (Path impath : this.impaths) + { + Path prefixedpath = impath.resolve(path); + if (Files.exists(prefixedpath)) + { + return openFileInputStreamResource(prefixedpath); + } + } + throw new ScribException("Couldn't open resource: " + path); + } + + // "full" path from working directory, as opposed to "relative" paths from import prefixes + public static FileResource getResourceByFullPath(Path path) + throws ScribException // TODO: should be abstracted out as front-end functionality, e.g. DirectoryResourceLocator, to find/load main module; then MainContext uses abstract ResourceLocator to load rest + { + if (!Files.exists(path)) + { + throw new ScribException("File couldn't be opened: " + path); + } + return openFileInputStreamResource(path); + } + + private static FileResource openFileInputStreamResource(Path path) + throws ScribException + { + try + { + return new FileResource(path, Files.newInputStream(path)); + } + catch (IOException e) + { + throw new ScribException(e); + } + } +} diff --git a/scribble-main/src/main/java/org/scribble/main/resource/locator/IResourceLocator.java b/scribble-main/src/main/java/org/scribble/main/resource/locator/IResourceLocator.java new file mode 100644 index 000000000..06b845038 --- /dev/null +++ b/scribble-main/src/main/java/org/scribble/main/resource/locator/IResourceLocator.java @@ -0,0 +1,38 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.main.resource.locator; + +import java.nio.file.Path; + +import org.scribble.main.resource.Resource; +import org.scribble.util.ScribException; + + +/** + * This interface provides the resource location capability. + * + */ +public interface IResourceLocator +{ + /** + * This method obtains the resource associated with the + * supplied path. + * + * @param path The resource path -- "relative" path from import path prefixes + * @return The resource, or null if not found + */ + + Resource getResource(Path path) throws ScribException; + // TODO: Path should be made more abstract, e.g. some kind of URI (cf., Resource.getLocation) +} diff --git a/scribble-main/src/main/java/org/scribble/main/resource/locator/ResourceLocator.java b/scribble-main/src/main/java/org/scribble/main/resource/locator/ResourceLocator.java new file mode 100644 index 000000000..86f2c69af --- /dev/null +++ b/scribble-main/src/main/java/org/scribble/main/resource/locator/ResourceLocator.java @@ -0,0 +1,20 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.main.resource.locator; + + +public abstract class ResourceLocator implements IResourceLocator +{ + +} diff --git a/bundles/org.scribble.protocol.conformance/LICENSE.txt b/scribble-parser/LICENSE.txt similarity index 100% rename from bundles/org.scribble.protocol.conformance/LICENSE.txt rename to scribble-parser/LICENSE.txt diff --git a/scribble-parser/build.properties b/scribble-parser/build.properties new file mode 100644 index 000000000..c987bb752 --- /dev/null +++ b/scribble-parser/build.properties @@ -0,0 +1,33 @@ +# +# Copyright 2008 The Scribble 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 +# +# http://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. +# + +source.. = src/main/java/,\ + target/generated-sources/antlr3/ +output.. = bin/ +bin.includes = META-INF/,\ + .,\ + src/main/resources/lib/antlr-3.2.jar,\ + OSGI-INF/,\ + LICENSE.txt +src.includes = target/generated-sources/,\ + src/,\ + pom.xml,\ + build.properties,\ + META-INF/,\ + .project,\ + .classpath,\ + OSGI-INF/,\ + LICENSE.txt +jars.compile.order = .,\ + lib/antlr-3.2.jar diff --git a/scribble-parser/lib/antlr-3.5.2-complete.jar b/scribble-parser/lib/antlr-3.5.2-complete.jar new file mode 100644 index 000000000..260de7634 Binary files /dev/null and b/scribble-parser/lib/antlr-3.5.2-complete.jar differ diff --git a/scribble-parser/pom.xml b/scribble-parser/pom.xml new file mode 100644 index 000000000..3f0617c98 --- /dev/null +++ b/scribble-parser/pom.xml @@ -0,0 +1,54 @@ + + 4.0.0 + + + scribble-parser + jar + + + org.scribble + parent + 0.5.1-SNAPSHOT + ../pom.xml + + + + + org.scribble + scribble-core + + + + org.scribble + scribble-ast + + + + org.antlr + antlr-runtime + + + + + + + + org.antlr + antlr3-maven-plugin + ${antlr.version} + + + + antlr + + + + + + + + + scribble-parser + + diff --git a/scribble-parser/src/main/antlr3/org/scribble/parser/antlr/Scribble-0.3.original b/scribble-parser/src/main/antlr3/org/scribble/parser/antlr/Scribble-0.3.original new file mode 100644 index 000000000..e7f87c72b --- /dev/null +++ b/scribble-parser/src/main/antlr3/org/scribble/parser/antlr/Scribble-0.3.original @@ -0,0 +1,864 @@ +/* + * Raymond@HZHL2 ~/code/python/scribble-tools + * $ java -cp lib/antlr-3.1.3.jar org.antlr.Tool -o bin src/scribble/Scribble.g +*/ + +// Use language actions to directly create lists etc.? but ties the grammar source to that language? + +// Garbage at the end of input file seems to just get ignored, no error raised. but also for e.g. two package declarations -- check if this is still the case? + + +grammar Scribble; + +options +{ + language = Python; + output = AST; + ASTLabelType = CommonTree; + backtrack = true; // backtracking disabled by default? Is it bad to rely on this option? + //memoize = true; +} + +tokens +{ + /* + * Parser input constants (lexer output; keywords, Section 2.4) + */ + MODULEKW = 'module'; + IMPORTKW = 'import'; + TYPEKW = 'type'; + PROTOCOLKW = 'protocol'; + GLOBALKW = 'global'; + LOCALKW = 'local'; + ROLEKW = 'role'; + SIGKW = 'sig'; + INSTANTIATESKW = 'instantiates'; + ASKW = 'as'; + + FROMKW = 'from'; + TOKW = 'to'; + CHOICEKW = 'choice'; + ATKW = 'at'; + ORKW = 'or'; + RECKW = 'rec'; + CONTINUEKW = 'continue'; + PARKW = 'par'; + ANDKW = 'and'; + INTERRUPTIBLEKW = 'interruptible'; + WITHKW = 'with'; + BYKW = 'by'; /* from for interrupts is more expected, but from is + not good for multiple roles (generally, the comma + in interrupt message list and role list looks like + "and" rather than "or") */ + THROWSKW = 'throws'; + CATCHESKW = 'catches'; + DOKW = 'do'; + //SPAWNKW = 'spawn'; + + + /* + * Parser output node types (corresponding to the various syntactic + * categories) i.e. the labels used to distinguish resulting AST nodes. + * The value of these token variables doesn't matter, only the token + * (i.e. variable) names themselves are used (for AST node root text + * field) + */ + //MODULE = 'module'; + MODULE = 'modul'; + //PACKAGEDECL = 'package-decl'; + MODULEDECL = 'module-decl'; + //IMPORTDECL = 'import-decl'; + //FROMIMPORTDECL = 'from-import-decl'; + IMPORTMODULE = 'import-module'; + IMPORTMEMBER = 'import-member'; + PAYLOADTYPEDECL = 'payload-type-decl'; + PARAMETERDECLLIST = 'parameter-decl-list'; + PARAMETERDECL = 'parameter-decl'; + MESSAGESIGNATURE = 'message-signature'; + ROLEDECLLIST = 'role-decl-list'; + ROLEDECL = 'role-decl'; + ARGUMENTLIST = 'argument-list'; + ARGUMENT = 'argument'; + PAYLOAD = 'payload'; + PAYLOADELEMENT = 'payloadelement'; + ROLEINSTANTIATIONLIST = 'role-instantiation-list'; + ROLEINSTANTIATION = 'role-instantiation'; + + GLOBALPROTOCOLDECL = 'global-protocol-decl'; + GLOBALPROTOCOLDEF = 'global-protocol-def'; + GLOBALPROTOCOLINSTANCE = 'global-protocol-instance'; + //GLOBALPROTOCOLBODY = 'global-protocol-body'; + GLOBALPROTOCOLBLOCK = 'global-protocol-block'; + GLOBALINTERACTIONSEQUENCE = 'global-interaction-sequence'; + GLOBALMESSAGETRANSFER = 'global-message-transfer'; + GLOBALCHOICE = 'global-choice'; + GLOBALRECURSION = 'global-recursion'; + GLOBALCONTINUE = 'global-continue'; + GLOBALPARALLEL = 'global-parallel'; + GLOBALINTERRUPTIBLE = 'global-interruptible'; + GLOBALINTERRUPT = 'global-interrupt'; + GLOBALDO = 'global-do'; + //GLOBALSPAWN = 'global-spawn'; + + LOCALPROTOCOLDECL = 'local-protocol-decl'; + LOCALPROTOCOLDEF = 'local-protocol-def'; + LOCALPROTOCOLINSTANCE = 'local-protocol-instance'; + LOCALPROTOCOLBLOCK = 'local-protocol-block'; + LOCALINTERACTIONSEQUENCE = 'local-interaction-sequence'; + LOCALMESSAGETRANSFER = 'local-message-transfer'; + LOCALCHOICE = 'local-choice'; + LOCALRECURSION = 'local-recursion'; + LOCALCONTINUE = 'local-continue'; + LOCALPARALLEL = 'local-parallel'; + LOCALINTERRUPTIBLE = 'local-interruptible'; + LOCALINTERRUPT = 'local-interrupt'; + LOCALDO = 'local-do'; + LOCALTHROW = 'local-throw'; + LOCALCATCH = 'local-catch'; + LOCALSEND = 'local-send'; + LOCALRECEIVE = 'local-receive'; + + + /* + * Some utility constants; AST token values are the variable names (not + * the variable values). + * (N.B. Some grammar rules use dummy placeholder values, but others do not) + */ + EMPTY_MESSAGE_OP = '__empty_message_op'; + EMPTY_ANNOTATION = '__empty_annotation'; + EMPTY_PARAMETER_DECL_LIST = '__empty_parameter_decl_list'; + EMPTY_ARGUMENT_LIST = '__empty_argument_list'; + EMPTY_MODULE_NAME = '__empty_module_name'; + EMPTY_SCOPE_NAME = '__empty_scope_name'; + EMPTY_LOCAL_THROW = '__empty_local_throw'; + EMPTY_LOCAL_CATCHES = '__empty_local_catch'; + + KIND_MESSAGE_SIGNATURE = 'KIND_MESSAGE_SIGNATURE'; + KIND_PAYLOAD_TYPE = 'KIND_PAYLOAD_TYPE'; +} + + +/**************************************************************************** + * Chapter 2 Lexical Strucure (Lexer rules) + ***************************************************************************/ + +/* + * Section 2.1 White space (Section 2.1) + */ +WHITESPACE: + ('\t' | ' ' | '\r' | '\n'| '\u000C')+ + { + $channel = HIDDEN; + } +; + +/** + * Section 2.2 Comments + */ +COMMENT: + '/*' .* '*/' + { + $channel=HIDDEN; + } +; + +LINE_COMMENT: + '//' ~('\n'|'\r')* '\r'? '\n' + { + $channel=HIDDEN; + } +; + +/** + * Section 2.3 Identifiers + */ +IDENTIFIER: + (LETTER | UNDERSCORE) (LETTER | DIGIT | UNDERSCORE)* +; + +fragment SYMBOL: + '{' | '}' | '(' | ')' | '[' | ']' | ':' | '/' | '\\' | '.' | '\#' +| + '&' | '?' | '!' | UNDERSCORE +; + +// Comes after SYMBOL due to an ANTLR syntax highlighting issue +// involving quotes +EXTIDENTIFIER: + '\"' (LETTER | UNDERSCORE) (LETTER | DIGIT | SYMBOL)* '\"' +; + +fragment LETTER: + 'a'..'z' | 'A'..'Z' +; + +fragment DIGIT: + '0'..'9' +; + +fragment UNDERSCORE: + '_' +; + + +/**************************************************************************** + * Chapter 3 Syntax (Parser rules) + ***************************************************************************/ + +/* + * Section 3.1 Primitive Names + */ +rolename: IDENTIFIER; +payloadtypename: IDENTIFIER; +protocolname: IDENTIFIER; +parametername: IDENTIFIER; +annotationname: IDENTIFIER; +recursionlabelname: IDENTIFIER; +scopename: IDENTIFIER; + + +/** + * Section 3.2.1 Package, Module and Module Member Names + */ +/*packagename: + IDENTIFIER ('.' IDENTIFIER)* + -> + (IDENTIFIER)+ +;*/ + +modulename: + //packagename '.' IDENTIFIER // Not working + IDENTIFIER ('.' IDENTIFIER)* '.' IDENTIFIER + -> + (IDENTIFIER)+ +| + IDENTIFIER + -> + (IDENTIFIER)+ +; + +membername: + simplemembername +| + fullmembername +; + +simplemembername: + payloadtypename +| + protocolname /* Generates an ANTLR warning since both are IDENTIFIER + if no backtrack (makes ANTLR think this alternative + is reachable, but actually it isn't) */ +; + +fullmembername: + modulename '.' simplemembername /* Needs backtrack=true + since the simplemembername can/will + be eagerly consumed by modulename */ + -> + modulename simplemembername +; + + +/** + * Section 3.2.2 Top-level Module Structure + */ +module: + moduledecl (importdecl)* (payloadtypedecl)* (protocoldecl)* + -> + /* "Root value" seems to be stored as a string (the token name, not + value), other parts stored as subtrees */ + ^(MODULE moduledecl (importdecl)* (payloadtypedecl)* (protocoldecl)*) + /* Looks for a token called "MODULE", but uses the token name, not the + value of the token... */ +; + + +/** + * Section 3.2.3 Module Declarations + */ +moduledecl: + MODULEKW modulename ';' + -> + ^(MODULEDECL modulename) +; + + +/** + * Section 3.3 Import Declarations + */ +importdecl: + importmodule +| + importmember +; + +importmodule: + IMPORTKW modulename ';' + -> + ^(IMPORTMODULE modulename) /* Dummy empty values not used consistently + across categories */ +| + IMPORTKW modulename ASKW IDENTIFIER ';' + -> + ^(IMPORTMODULE ASKW IDENTIFIER modulename) // Ordered to make AST node + // getters easier +; + +importmember: + FROMKW modulename IMPORTKW simplemembername ';' + -> + ^(IMPORTMEMBER simplemembername modulename) // Ordered to make AST node + // getters easier +| + FROMKW modulename IMPORTKW simplemembername ASKW IDENTIFIER ';' + -> + ^(IMPORTMEMBER ASKW IDENTIFIER simplemembername modulename) + // IDENTIFIER used (instead of simplemembername) to swap element order +; + + +/** + * Section 3.4 Payload Type Declarations + */ +payloadtypedecl: + TYPEKW '<' IDENTIFIER '>' EXTIDENTIFIER FROMKW EXTIDENTIFIER ASKW payloadtypename ';' + -> + ^(PAYLOADTYPEDECL IDENTIFIER EXTIDENTIFIER EXTIDENTIFIER payloadtypename) + /* Seems to go off "element order" in the output references, + no way to label/index the elements */ +; + + +/** + * Section 3.5 Message Signatures + */ +messageoperator: + (LETTER | DIGIT | UNDERSCORE)+ +; + +messagesignature: + '(' payload ')' + -> + ^(MESSAGESIGNATURE EMPTY_MESSAGE_OP payload) +| + //messageoperator '(' payload ')' // Doesn't work (conflict with IDENTIFIER?) + IDENTIFIER '(' payload ')' + -> + //^(MESSAGESIGNATURE messageoperator payload) + ^(MESSAGESIGNATURE IDENTIFIER payload) +; + +payload: + -> + ^(PAYLOAD) +| + payloadelement (',' payloadelement)* + -> + ^(PAYLOAD (payloadelement)+) +; + +payloadelement: + payloadtypename + -> + ^(PAYLOADELEMENT EMPTY_ANNOTATION payloadtypename) +| + parametername /* An IDENTIFIER, like payloadtypename, so generates warnings + (unless backtrack=true) */ + -> + ^(PAYLOADELEMENT EMPTY_ANNOTATION parametername) +| + annotationname ':' payloadtypename + -> + ^(PAYLOADELEMENT annotationname payloadtypename) +| + annotationname ':' parametername + -> + ^(PAYLOADELEMENT annotationname parametername) +; + + +/** + * Section 3.6 Protocol Declarations + */ +protocoldecl: + globalprotocoldecl +| + localprotocoldecl +; + + +/** + * Section 3.7 Global Protocol Declarations + */ +globalprotocoldecl: + globalprotocolheader globalprotocoldefinition + -> + ^(GLOBALPROTOCOLDECL globalprotocolheader globalprotocoldefinition) +| + globalprotocolheader globalprotocolinstance + -> + ^(GLOBALPROTOCOLDECL globalprotocolheader globalprotocolinstance) +; + +globalprotocolheader: // Currently, header is not an explicit category + GLOBALKW PROTOCOLKW protocolname roledecllist + -> + protocolname EMPTY_PARAMETER_DECL_LIST roledecllist +| + GLOBALKW PROTOCOLKW protocolname parameterdecllist roledecllist + -> + protocolname parameterdecllist roledecllist +; + +roledecllist: + '(' roledecl (',' roledecl)* ')' + -> + ^(ROLEDECLLIST (roledecl)+) +; + +roledecl: + ROLEKW rolename + -> + ^(ROLEDECL rolename) +| + ROLEKW rolename ASKW rolename + -> + ^(ROLEDECL rolename rolename) +; + +parameterdecllist: + '<' parameterdecl (',' parameterdecl)* '>' + -> + ^(PARAMETERDECLLIST (parameterdecl)+) +; + +parameterdecl: + TYPEKW parametername + -> + ^(PARAMETERDECL KIND_PAYLOAD_TYPE parametername) +| + TYPEKW parametername ASKW parametername + -> + ^(PARAMETERDECL KIND_PAYLOAD_TYPE parametername parametername) +| + SIGKW parametername + -> + ^(PARAMETERDECL KIND_MESSAGE_SIGNATURE parametername) +| + SIGKW parametername ASKW parametername + -> + ^(PARAMETERDECL KIND_MESSAGE_SIGNATURE parametername parametername) +; + + +/** + * Section 3.7.1 Global Protocol Definitions + */ +globalprotocoldefinition: + globalprotocolblock + -> + ^(GLOBALPROTOCOLDEF globalprotocolblock) +; + + +/** + * Section 3.7.2 Global Protocol Instantiation + */ +globalprotocolinstance: + INSTANTIATESKW membername roleinstantiationlist ';' + -> + ^(GLOBALPROTOCOLINSTANCE EMPTY_ARGUMENT_LIST roleinstantiationlist membername) + // membername at end to make indexing easier (could make proper name nodes) +| + INSTANTIATESKW membername argumentlist roleinstantiationlist ';' + -> + ^(GLOBALPROTOCOLINSTANCE argumentlist roleinstantiationlist membername) +; + +roleinstantiationlist: + '(' roleinstantiation (',' roleinstantiation)* ')' + -> + ^(ROLEINSTANTIATIONLIST (roleinstantiation)+) +; + +roleinstantiation: + rolename + -> + ^(ROLEINSTANTIATION rolename) +| + rolename ASKW rolename + -> + ^(ROLEINSTANTIATION rolename rolename) +; + +argumentlist: + '<' argument (',' argument)* '>' + -> + ^(ARGUMENTLIST (argument)+) +; + +argument: + messagesignature + -> + ^(ARGUMENT messagesignature) +| + messagesignature ASKW parametername + -> + ^(ARGUMENT messagesignature parametername) +| + payloadtypename + -> + ^(ARGUMENT payloadtypename) +| + payloadtypename ASKW parametername + -> + ^(ARGUMENT payloadtypename parametername) +| + parametername // generates warnings unless backtrack=true + -> + ^(ARGUMENT parametername) +| + parametername ASKW parametername + -> + ^(ARGUMENT parametername ASKW parametername) +; + + +/** + * Section 3.7.3 Global Interaction Sequences and Blocks + */ +globalprotocolblock: + '{' globalinteractionsequence '}' + -> + ^(GLOBALPROTOCOLBLOCK globalinteractionsequence) +; + +globalinteractionsequence: + (globalinteraction)* + -> + ^(GLOBALINTERACTIONSEQUENCE (globalinteraction)*) +; + +globalinteraction: + globalmessagetransfer +| + globalchoice +| + globalrecursion +| + globalcontinue +| + globalparallel +| + globalinterruptible +| + globaldo +/*| + globalspawn*/ +; + + +/** + * Section 3.7.4 Global Message Transfer + */ +globalmessagetransfer: + message FROMKW rolename TOKW rolename (',' rolename )* ';' + -> + ^(GLOBALMESSAGETRANSFER message rolename (rolename)+) +; + +message: + messagesignature +| + parametername +; + + +/** + * Section 3.7.5 Global Choice + */ +globalchoice: + CHOICEKW ATKW rolename globalprotocolblock (ORKW globalprotocolblock)* + -> + ^(GLOBALCHOICE rolename globalprotocolblock+) +; + + +/** + * Section 3.7.6 Global Recursion + */ +globalrecursion: + RECKW recursionlabelname globalprotocolblock + -> + ^(GLOBALRECURSION recursionlabelname globalprotocolblock) +; + +globalcontinue: + CONTINUEKW recursionlabelname ';' + -> + ^(GLOBALCONTINUE recursionlabelname) +; + + +/** + * Section 3.7.7 Global Parallel + */ +globalparallel: + PARKW globalprotocolblock (ANDKW globalprotocolblock)* + -> + ^(GLOBALPARALLEL globalprotocolblock+) +; + + +/** + * Section 3.7.8 Global Interruptible + */ +globalinterruptible: + INTERRUPTIBLEKW globalprotocolblock WITHKW '{' (globalinterrupt)* '}' + -> + ^(GLOBALINTERRUPTIBLE EMPTY_SCOPE_NAME globalprotocolblock (globalinterrupt)*) +| + INTERRUPTIBLEKW scopename ':' globalprotocolblock WITHKW '{' (globalinterrupt)* '}' + -> + ^(GLOBALINTERRUPTIBLE scopename globalprotocolblock (globalinterrupt)*) +; + +globalinterrupt: + message (',' message)* BYKW rolename ';' + -> + ^(GLOBALINTERRUPT rolename (message)+) +; + + +/** + * Section 3.7.9 Global Do + */ +globaldo: + DOKW membername roleinstantiationlist ';' + -> + ^(GLOBALDO EMPTY_SCOPE_NAME EMPTY_ARGUMENT_LIST roleinstantiationlist membername) + // membername at end to make indexing easier (like instantiation) +| + DOKW membername argumentlist roleinstantiationlist ';' + -> + ^(GLOBALDO EMPTY_SCOPE_NAME argumentlist roleinstantiationlist membername) +| + DOKW scopename ':' membername roleinstantiationlist ';' + -> + ^(GLOBALDO scopename EMPTY_ARGUMENT_LIST roleinstantiationlist membername) +| + DOKW scopename ':' membername argumentlist roleinstantiationlist ';' + -> + ^(GLOBALDO scopename argumentlist roleinstantiationlist membername) +; + + +/** + * TODO: Global Spawn + */ +/*globalspawn: + SPAWNKW membername '(' roleinstantiationlist ')' ';' + -> + ^(GLOBALSPAWN membername EMPTY_ARGUMENT_LIST roleinstantiationlist) +| + SPAWNKW membername '<' argumentlist '>' '(' roleinstantiationlist ')' ';' + -> + ^(GLOBALSPAWN membername argumentlist roleinstantiationlist) +;*/ + + +/* + * Section 3.8 Local Protocol Declarations + */ +localprotocoldecl: + localprotocolheader localprotocoldefinition + -> + ^(LOCALPROTOCOLDECL localprotocolheader localprotocoldefinition) +| + localprotocolheader localprotocolinstance + -> + ^(LOCALPROTOCOLDECL localprotocolheader localprotocolinstance) +; + +localprotocolheader: + LOCALKW PROTOCOLKW protocolname ATKW rolename roledecllist + -> + protocolname rolename EMPTY_PARAMETER_DECL_LIST roledecllist +| + LOCALKW PROTOCOLKW protocolname ATKW rolename parameterdecllist roledecllist + -> + protocolname rolename parameterdecllist roledecllist +; + + +/** + * Section 3.8.1 Local Protocol Definitions + */ +localprotocoldefinition: + localprotocolblock + -> + ^(LOCALPROTOCOLDEF localprotocolblock) +; + + +/** + * Section 3.8.2 Local Protocol Instantiation + */ +localprotocolinstance: + INSTANTIATESKW membername roledecllist ';' + -> + ^(LOCALPROTOCOLINSTANCE EMPTY_ARGUMENT_LIST roledecllist membername) +| + INSTANTIATESKW membername argumentlist roledecllist ';' + -> + ^(LOCALPROTOCOLINSTANCE argumentlist roledecllist membername) +; + + +/** + * Section 3.8.3 Local Interaction Blocks and Sequences + */ +localprotocolblock: + '{' localinteractionsequence '}' + -> + ^(LOCALPROTOCOLBLOCK localinteractionsequence) +; + +localinteractionsequence: + (localinteraction)* + -> + ^(LOCALINTERACTIONSEQUENCE (localinteraction)*) +; + +localinteraction: + localsend +| + localreceive +| + localchoice +| + localparallel +| + localrecursion +| + localcontinue +| + localinterruptible +| + localdo +/*| + localspawn*/ +; + + +/** + * Section 3.8.4 Local Send and Receive + */ +localsend: + message TOKW rolename (',' rolename)* ';' + -> + ^(LOCALSEND message (rolename)+) +; + +localreceive: + message FROMKW IDENTIFIER ';' + -> + ^(LOCALRECEIVE message IDENTIFIER) +; + + +/** + * Section 3.8.5 Local Choice + */ +localchoice: + CHOICEKW ATKW rolename localprotocolblock (ORKW localprotocolblock)* + -> + ^(LOCALCHOICE rolename localprotocolblock+) +; + + +/** + * Section 3.8.6 Local Recursion + */ +localrecursion: + RECKW recursionlabelname localprotocolblock + -> + ^(LOCALRECURSION recursionlabelname localprotocolblock) +; + +localcontinue: + CONTINUEKW recursionlabelname ';' + -> + ^(LOCALCONTINUE recursionlabelname) +; + + +/** + * Section 3.8.7 Local Parallel + */ +localparallel: + PARKW localprotocolblock (ANDKW localprotocolblock)* + -> + ^(LOCALPARALLEL localprotocolblock+) +; + + +/** + * Section 3.8.8 Local Interruptible + */ +localinterruptible: + /*INTERRUPTIBLEKW scopename ':' localprotocolblock WITHKW '{' localthrowandorcatch '}' + -> + ^(LOCALINTERRUPTIBLE scopename localprotocolblock localthrowandorcatch) +|*/ + INTERRUPTIBLEKW scopename ':' localprotocolblock WITHKW '{' (localcatch)* '}' + -> + ^(LOCALINTERRUPTIBLE scopename localprotocolblock EMPTY_LOCAL_THROW (localcatch)*) +| + INTERRUPTIBLEKW scopename ':' localprotocolblock WITHKW '{' localthrow (localcatch)* '}' + -> + ^(LOCALINTERRUPTIBLE scopename localprotocolblock localthrow (localcatch)*) +; + +/*localthrowandorcatch: + localthrow (localcatch)* +| + (localcatch)+ +;*/ + +localthrow: + THROWSKW message (',' message)* TOKW rolename (',' rolename)* ';' + -> + ^(LOCALTHROW (message)+ (rolename)+) +; + +localcatch: + CATCHESKW message (',' message)* FROMKW rolename ';' + -> + ^(LOCALCATCH (message)+ rolename) +; + + +/** + * Section 3.8.9 Local Do + */ +localdo: + DOKW membername roleinstantiationlist ';' + -> + ^(LOCALDO EMPTY_SCOPE_NAME EMPTY_ARGUMENT_LIST roleinstantiationlist membername) + // membername at end to make indexing easier (like Global) +| + DOKW membername argumentlist roleinstantiationlist ';' + -> + ^(LOCALDO EMPTY_SCOPE_NAME argumentlist roleinstantiationlist membername) +| + DOKW scopename ':' membername roleinstantiationlist ';' + -> + ^(LOCALDO scopename EMPTY_ARGUMENT_LIST roleinstantiationlist membername) +| + DOKW scopename ':' membername argumentlist roleinstantiationlist ';' + -> + ^(LOCALDO scopename argumentlist roleinstantiationlist membername) +; + diff --git a/scribble-parser/src/main/antlr3/org/scribble/parser/antlr/Scribble.g b/scribble-parser/src/main/antlr3/org/scribble/parser/antlr/Scribble.g new file mode 100644 index 000000000..303606541 --- /dev/null +++ b/scribble-parser/src/main/antlr3/org/scribble/parser/antlr/Scribble.g @@ -0,0 +1,693 @@ +/** + * N.B. in Eclipse do Package Explorer, right click -> Open With -> Java Editor at least once for .g file association and syntax highlighting to work properly + * + * > scribble-java + * $ java -cp scribble-parser/lib/antlr-3.5.2-complete.jar org.antlr.Tool -o scribble-parser/target/generated-sources/antlr3 scribble-parser/src/main/antlr3/org/scribble/parser/antlr/Scribble.g + * + * Cygwin/Windows + * > scribble-java + * $ java -cp scribble-parser/lib/antlr-3.5.2-complete.jar org.antlr.Tool -o scribble-parser/target/generated-sources/antlr3/org/scribble/parser/antlr scribble-parser/src/main/antlr3/org/scribble/parser/antlr/Scribble.g + * $ mv scribble-parser/target/generated-sources/antlr3/org/scribble/parser/antlr/Scribble.tokens scribble-parser/target/generated-sources/antlr3/ + */ + +/* * -- ** not allowed here..... + * Pattern: most nodes have "imaginary token types". + * Where token attributes are not "inherited" from a concrete token, the default is to use textual name of the token type field as its text + * e.g., gprotodecl: ... -> ^(GPROTODECL ...). I.e., each token will be equivalent to, e.g., new CommonToken(ScribbleParser.GPROTODECL, "GPROTODECL"). + * The actual info of every imaginary node is in its children (i.e., its token text can be disregarded). + * The exceptions are for ID/EXTID, where the text is the ID value, i.e., new CommonToken(ScribbleParser.ID, "..."). + */ + +grammar Scribble; + + +options +{ + language = Java; + output = AST; + ASTLabelType = ScribNodeBase; +} + + +tokens +{ + /* Parser "input" constants (lexer output; keywords, Section 2.4) + */ + MODULE_KW = 'module'; + IMPORT_KW = 'import'; + DATA_KW = 'data'; + SIG_KW = 'sig'; + TYPE_KW = 'type'; + PROTOCOL_KW = 'protocol'; + AS_KW = 'as'; + + GLOBAL_KW = 'global'; + LOCAL_KW = 'local'; // Currently not parsed, but may be generated + EXPLICIT_KW = 'explicit'; + AUX_KW = 'aux'; + + ROLE_KW = 'role'; + SELF_KW = 'self'; // Currently not parsed, but may be generated + + FROM_KW = 'from'; + TO_KW = 'to'; + CONNECT_KW = 'connect'; + WRAP_KW = 'wrap'; + + DISCONNECT_KW = 'disconnect'; + AND_KW = 'and'; + + CHOICE_KW = 'choice'; + AT_KW = 'at'; + OR_KW = 'or'; + + REC_KW = 'rec'; + CONTINUE_KW = 'continue'; + DO_KW = 'do'; + + + /* Scribble AST token types (corresponding to the Scribble BNF). + * These token types are used by ScribTreeAdaptor to create the output nodes + * using the org.scribble.ast classes. + * (Trying to construct those classes directly from here doesn't seem to work + * well for most cases.) + * These tokens are ANTLR "imaginary tokens": they are derived by the ANTLR + * "rewrite rules" on the actual source tokens. + * The specific value of these tokens aren't important (the constants are + * accessed via fields of ScribbleParser). + * As a naming convention, we use a few "_" suffixes: _KW, _NAME, _LIT and + * _LIST. + */ + + // Special cases + EMPTY_OP = '__EMPTY_OP'; + + // Simple names "constructed directly", e.g., t=ID -> ID<...Node>[$t] + + // Compound names + GPROTO_NAME = 'GPROTO_NAME'; // Parse specifically as GProto, for ScribTreeAdaptor.create + LPROTO_NAME = 'LPROTO_NAME'; + MODULE_NAME = 'MODULE_NAME'; + DATA_NAME = 'DATA_NAME'; // N.B. distinct from DATAPARAM_NAME + SIG_NAME = 'SIG_NAME'; // N.B. distinct from SIGPARAM_NAME + + // Sig literals + SIG_LIT = 'SIG_LIT'; + PAYELEM_LIST = 'PAYELEM_LIST'; + UNARY_PAYELEM = 'UNARY_PAYELEM'; + GDELEG_PAYELEM = 'GDELEG_PAYELEM'; + + // Scribble "language" nodes, i.e., the nodes that are not "session nodes" (see below) + MODULE = 'MODULE'; + MODULEDECL = 'MODULEDECL'; + IMPORTMODULE = 'IMPORTMODULE'; + + DATADECL = 'DATADECL'; + SIGDECL = 'SIGDECL'; + GPROTODECL = 'GPROTODECL'; + PROTOMOD_LIST = 'PROTOMOD_LIST'; + + GPROTOHEADER = 'GPROTOHEADER'; + ROLEDECL_LIST = 'ROLEDECL_LIST'; + ROLEDECL = 'ROLEDECL'; + PARAMDECL_LIST = 'PARAMDECL_LIST'; + DATAPARAMDECL = 'DATAPARAMDECL'; + SIGPARAMDECL = 'SIGPARAMDECL'; + + GPROTODEF = 'GPROTODEF'; + GPROTOBLOCK = 'GPROTOBLOCK'; + + // Scribble "session nodes" -- cf. org.scribble.core.type.session vs. org.scribble.core.lang + GINTERSEQ = 'GINTERSEQ'; + + GMSGTRANSFER = 'GMSGTRANSFER'; + GCONNECT = 'GCONNECT'; + GDCONN = 'GDCONN'; // TODO: rename GDISCONN + GWRAP = 'GWRAP'; + + GCONTINUE = 'GCONTINUE'; + GDO = 'GDO'; + + ROLEARG_LIST = 'ROLEARG_LIST'; // Cf. ROLEDECL + ROLEARG = 'ROLEARG'; + NONROLEARG_LIST = 'NONROLEARG_LIST'; // Cf. ...PARAMDECL + NONROLEARG = 'NONROLEARG'; + + GCHOICE = 'GCHOICE'; + GRECURSION = 'GRECURSION'; + + // Locals: currently not directly parsed, but needed for, e.g., projection + LPROTODECL = 'LPROTODECL'; + + LPROTOHEADER = 'LPROTOHEADER'; + LSELFROLEDECL = 'LSELFROLEDECL'; + + LPROTODEF = 'LPROTODEF'; + LPROTOBLOCK = 'LPROTOBLOCK'; + + LINTERSEQ = 'LINTERSEQ'; + + LSEND = 'LSEND'; + LRECV = 'LRECV'; + LACC = 'LACC'; + LREQ = 'LREQ'; + LDCONN = 'LDCONN'; + LCLIENTWRAP = 'LCLIENTWRAP'; + LSERVERWRAP = 'LSERVERWRAP'; + + LCONTINUE = 'LCONTINUE'; + LDO = 'LDO'; + + LCHOICE = 'LCHOICE'; + LRECURSION = 'LRECURSION'; +} + + +@lexer::header +{ + package org.scribble.parser.antlr; +} + + +@lexer::members +{ + @Override + public void displayRecognitionError(String[] tokenNames, + RecognitionException e) + { + super.displayRecognitionError(tokenNames, e); + System.exit(1); + } +} + + +// Must come after tokens? +@parser::header +{ + package org.scribble.parser.antlr; + + import org.scribble.ast.NonRoleArg; + import org.scribble.ast.ScribNodeBase; + import org.scribble.ast.UnaryPayElem; + import org.scribble.ast.name.simple.AmbigNameNode; + import org.scribble.ast.name.simple.IdNode; + import org.scribble.ast.name.simple.OpNode; + import org.scribble.ast.name.simple.RecVarNode; + import org.scribble.ast.name.simple.RoleNode; + import org.scribble.ast.name.simple.SigParamNode; + import org.scribble.ast.name.simple.DataParamNode; + import org.scribble.ast.name.qualified.DataNameNode; +} + + +@parser::members +{ + // Abort tool run on parsing errors (and display user-friendly message) -- obsoletes CommonErrorNode check? + @Override + public void displayRecognitionError(String[] tokenNames, + RecognitionException e) + { + super.displayRecognitionError(tokenNames, e); + System.exit(1); + } + + // Currently unused -- TODO: check later in intermed translation, instead of parsing + public static CommonTree checkId(CommonTree id) + { + if (id.getText().contains("__")) + { + System.err.println("Double underscores are reserved: " + id); + System.exit(1); + } + return id; + } +} + + + +/**************************************************************************** + * Chapter 2 Lexical Structure (Lexer rules) + ***************************************************************************/ + +/* * // Double star here not accepted by ANTLR... + * Section 2.1 White space (Section 2.1) + */ +// Not referred to explicitly, deals with whitespace implicitly (don't delete this) +WHITESPACE: + ('\t' | ' ' | '\r' | '\n'| '\u000C')+ + { + $channel = HIDDEN; + } +; + +/** + * Section 2.2 Comments + */ +COMMENT: + '/*' .* '*/' + { + $channel=HIDDEN; + } +; + +LINE_COMMENT: + '//' ~('\n'|'\r')* '\r'? '\n' + { + $channel=HIDDEN; + } +; + + +/** + * Section 2.3 Identifiers + */ +ID: + (LETTER | DIGIT | UNDERSCORE)* + /* Underscore currently can cause ambiguities in the API generation naming + * scheme But maybe only consecutive underscores are the problem -- cannot + * completely disallow underscores as needed for projection naming scheme + * Or disallow underscores only for role/op/messagesig names + */ +; + +fragment SYMBOL: + '{' | '}' | '(' | ')' | '[' | ']' | ':' | '/' | '\\' | '.' | '\#' +| + '&' | '?' | '!' | UNDERSCORE +; + +// Comes after SYMBOL due to an ANTLR syntax highlighting issue involving +// quotes. +// Parser doesn't work without quotes here (e.g. if inlined into parser rules) +EXTID: + '\"' (LETTER | DIGIT | SYMBOL)* '\"' +; + //(LETTER | DIGIT | SYMBOL)* // Not working + +fragment LETTER: + 'a'..'z' | 'A'..'Z' +; + +fragment DIGIT: + '0'..'9' +; + +fragment UNDERSCORE: + '_' +; + + +/**************************************************************************** + * Chapter 3 Syntax (Parser rules) + ***************************************************************************/ + +/* * // Double star here not accepted by ANTLR... + * Section 3.1 Primitive Names + */ +//simplename: id=ID -> { checkId($id.tree) } ; // How to integrate with ID[$t] ? + +// "The TreeAdaptor is not called; instead [the] constructors are invoked directly." +// "Note that parameters are not allowed on token references to the left of ->:" +// "Use imaginary nodes as you normally would, but with the addition of the node type:" // But currently, ID token itself unchanged and ttype int ends up discarded +ambigname: t=ID -> ID[$t] ; +dataparamname: t=ID -> ID[$t] ; +opname: -> ^(EMPTY_OP) | t=ID -> ID[$t] ; +recvarname: t=ID -> ID[$t] ; +rolename: t=ID -> ID[$t] ; +sigparamname: t=ID -> ID[$t] ; + + +/** + * Section 3.2.1 Package, Module and Module Member Names + */ +// May be compound or simple +gprotoname: t=ID ('.' ID)* -> ^(GPROTO_NAME[$t] ID+) ; +modulename: t=ID ('.' ID)* -> ^(MODULE_NAME[$t] ID+) ; + +// Compound only (cf., e.g., gprotoname; cf. simpledataname) +qualifieddataname: t=ID '.' ID ('.' ID)* -> ^(DATA_NAME[$t] ID+) ; + +// Cf. primitive names, above +simpledataname: t=ID -> ^(DATA_NAME[$t] ID) ; +simplegprotoname: t=ID -> ^(GPROTO_NAME[$t] ID) ; +simplemodulename: t=ID -> ^(MODULE_NAME[$t] ID) ; +simplesigname: t=ID -> ^(SIG_NAME[$t] ID) ; + + +/** + * Section 3.2.2 Top-level Module Structure + * Section 3.2.3 Module Declarations + */ +// "References to tokens with rewrite not found on left of -> are imaginary tokens." +// Inlined moduledecl to make token label work +module: + t=MODULE_KW modulename ';' importmodule* nonprotodecl* protodecl* EOF +-> + ^(MODULE[$t] ^(MODULEDECL[$t] modulename) importmodule* nonprotodecl* + protodecl*) +; +// moduledecl: MODULE_KW^ modulename ';' + // "Become root" ^ cannot be on rhs? -- so "manually" rewrite to Scribble AST token types + + +/** + * Section 3.3 Import Declarations + */ +importmodule: + t=IMPORT_KW modulename (AS_KW alias=simplemodulename)? ';' +-> + ^(IMPORTMODULE[$t] modulename $alias?) +; + + +/** + * Section 3.4 "Non Protocol" Declarations + */ +nonprotodecl: + datadecl | sigdecl ; + +datadecl: + // Deprecate TYPE_KW ? + t=TYPE_KW '<' schema=ID '>' extName=EXTID FROM_KW + extSource=EXTID AS_KW alias=simpledataname ';' +-> + // alias first to be uniform with other NameDeclNode (getRawNameNodeChild) + ^(DATADECL[$t] $alias $schema $extName $extSource) +| + // CHECKME: duplicated above, because t=(TYPE_KW | DATA_KW) *sometimes* causes null token NPEs... + t=DATA_KW '<' schema=ID '>' extName=EXTID FROM_KW + extSource=EXTID AS_KW alias=simpledataname ';' +-> + // alias first to be uniform with other NameDeclNode (getRawNameNodeChild) + ^(DATADECL[$t] $alias $schema $extName $extSource) +; + +sigdecl: + t=SIG_KW '<' schema=ID '>' extName=EXTID FROM_KW extSource=EXTID AS_KW + alias=simplesigname ';' +-> + // alias first to be uniform with other NameDeclNode (getRawNameNodeChild) + ^(SIGDECL[$t] $alias $schema $extName $extSource) +; + + +/** + * Section 3.5 Message Signatures + */ +siglit: + opname '(' payelems ')' -> ^(SIG_LIT opname payelems) +; +// CHECKME: how to apply [$t] in such situations? + +payelems: + -> ^(PAYELEM_LIST) +| + payelem (',' payelem)* -> ^(PAYELEM_LIST payelem+) +; + +payelem: + // Payload element must be a data kind, cannot be a sig name + // Qualified name must be a data type name + // Also subsumes simple names, could be a data *param* + gprotoname '@' rolename -> ^(GDELEG_PAYELEM gprotoname rolename) +| + ambigname -> ^(UNARY_PAYELEM ambigname) +| + qualifieddataname -> ^(UNARY_PAYELEM qualifieddataname) +; +// { parsePayloadElem($qualifiedname.tree) } // Use ".text" instead of ".tree" for token String + + + + +/** + * Section 3.6 Protocol Declarations + */ +protodecl: + gprotodecl ; + + +/** + * Section 3.7 Global Protocol Declarations + */ +gprotodecl: + protomods gprotoheader gprotodef +-> + ^(GPROTODECL protomods gprotoheader gprotodef) +; + +// "aux" must come before "explicit" +protomods: + -> ^(PROTOMOD_LIST) +| t=AUX_KW -> ^(PROTOMOD_LIST[$t] AUX_KW) +| t=AUX_KW EXPLICIT_KW -> ^(PROTOMOD_LIST[$t] AUX_KW EXPLICIT_KW) +| t=EXPLICIT_KW -> ^(PROTOMOD_LIST[$t] EXPLICIT_KW) +; + +gprotoheader: + t=GLOBAL_KW PROTOCOL_KW simplegprotoname paramdecls roledecls +-> + ^(GPROTOHEADER[$t] simplegprotoname paramdecls roledecls) +; +// N.B. intermed translation uses full proto name + +roledecls: + t='(' roledecl (',' roledecl)* ')' -> ^(ROLEDECL_LIST[$t] roledecl+) ; + +roledecl: + t=ROLE_KW rolename -> ^(ROLEDECL[$t] rolename) ; + +paramdecls: + -> ^(PARAMDECL_LIST) +| + t='<' (paramdecl (',' paramdecl)*)? '>' -> ^(PARAMDECL_LIST[$t] paramdecl*) +; + +paramdecl: dataparamdecl | sigparamdecl ; + +dataparamdecl: + t=TYPE_KW dataparamname -> ^(DATAPARAMDECL[$t] dataparamname) +| + t=DATA_KW dataparamname -> ^(DATAPARAMDECL[$t] dataparamname) + // TODO: refactor -- cf. datadecl +; + +sigparamdecl: + t=SIG_KW sigparamname -> ^(SIGPARAMDECL[$t] sigparamname) ; + + +/** + * Section 3.7.1 Global Protocol Definitions + */ +gprotodef: + gprotoblock -> ^(GPROTODEF gprotoblock) ; + + +/** + * Section 3.7.3 Global Interaction Sequences and Blocks + */ +gprotoblock: + t='{' gseq '}' -> ^(GPROTOBLOCK[$t] gseq) +; + +gseq: + ginteraction* -> ^(GINTERSEQ ginteraction*) +; + +ginteraction: + // Simple session node: directed interaction + gconnect | gmsgtransfer + + // Simple session node: basic interaction + | gwrap | gdisconnect + + // Simple session node (other) + | gcontinue | gdo + + // Compound session node + | gchoice | grecursion +; + + +/** + * Section 3.7.4 Global Message Transfer + */ +message: + siglit | ambigname // ambigname = sig name or sig param name +; + +// TODO: qualified (messagesig) names -- although qualified signame subsumes parametername case +gmsgtransfer: + message FROM_KW rolename TO_KW rolename (',' rolename )* ';' +-> + ^(GMSGTRANSFER message rolename+) +; +// TODO: multisend + +gconnect: + message CONNECT_KW rolename TO_KW rolename ';' +-> + ^(GCONNECT message rolename rolename) +| + t=CONNECT_KW rolename TO_KW rolename ';' +-> + ^(GCONNECT[$t] ^(SIG_LIT ^(EMPTY_OP) ^(PAYELEM_LIST)) rolename rolename) + // CHECKME: deprecate? i.e., require "()" as for message transfers? i.e., simply delete this rule? +; + +gdisconnect: + t=DISCONNECT_KW rolename AND_KW rolename ';' +-> + ^(GDCONN[$t] rolename rolename) +; + +gwrap: + t=WRAP_KW rolename TO_KW rolename ';' +-> + ^(GWRAP[$t] rolename rolename) +; + + +/** + * Section 3.7.5 Global Choice + */ +gchoice: + t=CHOICE_KW AT_KW rolename gprotoblock (OR_KW gprotoblock)* +-> + ^(GCHOICE[$t] rolename gprotoblock+) +; + + +/** + * Section 3.7.6 Global Recursion + */ +grecursion: + t=REC_KW recvarname gprotoblock +-> + ^(GRECURSION[$t] recvarname gprotoblock) +; + +gcontinue: + t=CONTINUE_KW recvarname ';' +-> + ^(GCONTINUE[$t] recvarname) +; + + +/** + * Section 3.7.9 Global Do + */ +gdo: + DO_KW gprotoname nonroleargs roleargs ';' +-> + ^(GDO gprotoname nonroleargs roleargs) +; + +roleargs: + t='(' rolearg (',' rolearg)* ')' -> ^(ROLEARG_LIST[$t] rolearg+) +; + +rolearg: + rolename -> ^(ROLEARG rolename) ; + +nonroleargs: + -> ^(NONROLEARG_LIST) +| + t='<' (nonrolearg (',' nonrolearg)*)? '>' -> ^(NONROLEARG_LIST[$t] nonrolearg*) +; + +// Grammatically same as message, but qualifiedname case may also be a payload type +nonrolearg: + siglit -> ^(NONROLEARG siglit) +| + ambigname -> ^(NONROLEARG ambigname) +| + qualifieddataname -> ^(NONROLEARG qualifieddataname) // FIXME: sig name -- need an ambig qualified name +; +// { parseNonRoleArg($qualifiedname.tree) } // Like payelem, simple names need disambiguation + + + + + + + + + + + + + + + + + + + + + + + +/* +@parser::members +{ + // qn is an IdNode "holder" for a "qualifiedname" COMPOUND_NAME -- see ScribTreeAdaptor + // CHECKME: do the returns of these "bypass" ScribTreeAdaptor? specifically AmbigNode + // { parsePayloadElem($qualifiedname.tree) } // Use ".text" instead of ".tree" for token String + public static CommonTree parsePayloadElem(CommonTree qn) throws RecognitionException + { + if (qn.getChildCount() > 1) // qn has IdNode children, elements of the qualifiedname + { + // Cf. AstFactoryImpl, token creation + DataNameNode dt = new DataNameNode(new CommonToken(DATA_NAME, "DATA_NAME")); + ((List) qn.getChildren()).forEach(x -> + dt.addChild(new IdNode(new CommonToken(ID, ((CommonTree) x).getText())))); + UnaryPayElem pe = + new UnaryPayElem(new CommonToken(UNARY_PAYELEM, "UNARYPAYLOADELEM")); + pe.addChild(dt); + return pe; + } + else //if (qn.getChildCount() == 1) + { + // Similar to NonRoleArg: cannot syntactically distinguish right now between a simple data name and a param name + // Cf. AstFactoryImpl, token creation + String text = qn.getChild(0).getText(); + AmbigNameNode an = + new AmbigNameNode(AMBIG_NAME, new CommonToken(ID, text)); + UnaryPayElem e = new UnaryPayElem( + new CommonToken(UNARY_PAYELEM, "UNARYPAYLOADELEM")); + e.addChild(an); + return e; + } + } + + // qn is an IdNode "holder" for a "qualifiedname" COMPOUND_NAME -- see ScribTreeAdaptor + // Only for "qualifiedName" (DataNameNode or AmbigNameNode), not sig literals + // Use by: { parseNonRoleArg($qualifiedname.tree) } + public static CommonTree parseNonRoleArg(CommonTree qn) throws RecognitionException + { + if (qn.getChildCount() > 1) // qn has IdNode children, elements of the qualifiedname + { + // Cf. AstFactoryImpl, token creation + DataNameNode dt = + new DataNameNode(new CommonToken(DATA_NAME, "DATA_NAME")); // FIXME: could be a sig name arg... + ((List) qn.getChildren()).forEach(x -> + dt.addChild(new IdNode(new CommonToken(ID, ((CommonTree) x).getText())))); + NonRoleArg a = + new NonRoleArg(new CommonToken(ARG, "ARG")); + a.addChild(dt); + return a; + } + else //if (qn.getChildCount() == 1) + { + // Cf. AstFactoryImpl, token creation + String text = qn.getChild(0).getText(); + AmbigNameNode an = + new AmbigNameNode(AMBIG_NAME, new CommonToken(ID, text)); + NonRoleArg a = new NonRoleArg(new CommonToken(ARG, "ARG")); + a.addChild(an); + return a; + } + } +} +//*/ \ No newline at end of file diff --git a/scribble-parser/src/main/java/org/scribble/ast/AstFactoryImpl.java b/scribble-parser/src/main/java/org/scribble/ast/AstFactoryImpl.java new file mode 100644 index 000000000..b11dc9840 --- /dev/null +++ b/scribble-parser/src/main/java/org/scribble/ast/AstFactoryImpl.java @@ -0,0 +1,1027 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.ast; + +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.antlr.runtime.CommonToken; +import org.antlr.runtime.Token; +import org.scribble.ast.global.GChoice; +import org.scribble.ast.global.GConnect; +import org.scribble.ast.global.GContinue; +import org.scribble.ast.global.GDelegPayElem; +import org.scribble.ast.global.GDisconnect; +import org.scribble.ast.global.GDo; +import org.scribble.ast.global.GInteractionSeq; +import org.scribble.ast.global.GMsgTransfer; +import org.scribble.ast.global.GProtoBlock; +import org.scribble.ast.global.GProtoDecl; +import org.scribble.ast.global.GProtoDef; +import org.scribble.ast.global.GProtoHeader; +import org.scribble.ast.global.GRecursion; +import org.scribble.ast.global.GSessionNode; +import org.scribble.ast.global.GWrap; +import org.scribble.ast.local.LAcc; +import org.scribble.ast.local.LChoice; +import org.scribble.ast.local.LClientWrap; +import org.scribble.ast.local.LContinue; +import org.scribble.ast.local.LDisconnect; +import org.scribble.ast.local.LDo; +import org.scribble.ast.local.LInteractionSeq; +import org.scribble.ast.local.LProjectionDecl; +import org.scribble.ast.local.LProtoBlock; +import org.scribble.ast.local.LProtoDef; +import org.scribble.ast.local.LProtoHeader; +import org.scribble.ast.local.LRecursion; +import org.scribble.ast.local.LRecv; +import org.scribble.ast.local.LReq; +import org.scribble.ast.local.LSelfDecl; +import org.scribble.ast.local.LSend; +import org.scribble.ast.local.LServerWrap; +import org.scribble.ast.local.LSessionNode; +import org.scribble.ast.name.PayElemNameNode; +import org.scribble.ast.name.qualified.DataNameNode; +import org.scribble.ast.name.qualified.GProtoNameNode; +import org.scribble.ast.name.qualified.LProtoNameNode; +import org.scribble.ast.name.qualified.ModuleNameNode; +import org.scribble.ast.name.qualified.SigNameNode; +import org.scribble.ast.name.simple.AmbigNameNode; +import org.scribble.ast.name.simple.DataParamNode; +import org.scribble.ast.name.simple.ExtIdNode; +import org.scribble.ast.name.simple.IdNode; +import org.scribble.ast.name.simple.OpNode; +import org.scribble.ast.name.simple.RecVarNode; +import org.scribble.ast.name.simple.RoleNode; +import org.scribble.ast.name.simple.SigParamNode; +import org.scribble.core.type.kind.NonRoleParamKind; +import org.scribble.core.type.kind.PayElemKind; +import org.scribble.del.DefaultDel; +import org.scribble.del.DelFactory; +import org.scribble.del.ScribDel; +import org.scribble.parser.ScribAntlrWrapper; +import org.scribble.parser.antlr.ScribbleParser; + + +public class AstFactoryImpl implements AstFactory +{ + // Purely for the convenience of newToken(Token, type), parser instance used to access token int constants + protected final ScribbleParser parser; + protected final Map tokens; + + protected final DelFactory df; + + public AstFactoryImpl(ScribAntlrWrapper antlr) + { + try + { + Class parserC = + org.scribble.parser.antlr.ScribbleParser.class; + this.parser = antlr.newScribbleParser(null); + Map tokens = new HashMap<>(); + for (String t : ScribbleParser.tokenNames) + { + char c = t.charAt(0); + if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')) + { + tokens.put(parserC.getField(t).getInt(this.parser), t); + } + } + this.tokens = Collections.unmodifiableMap(tokens); + this.df = antlr.df; + } + catch (IllegalArgumentException | IllegalAccessException + | NoSuchFieldException | SecurityException e) + { + throw new RuntimeException(e); + } + } + + // type comes from the int constants in ScribbleParser, which come from the tokens in Scribble.g + // Pre: type is an "imaginary token" type from ScribbleParser -- (not ID) + protected CommonToken newToken(Token old, int type) + { + // As a default, token text is set to the textual name of the token type int field (also the Scribble.g default) + String text = this.tokens.get(type); + if (old == null) + { + return new CommonToken(type, text); + } + CommonToken t = new CommonToken(old); + t.setType(type); + t.setText(text); + return t; + } + + protected CommonToken newIdToken(Token old, String text) + { + if (old == null) + { + return new CommonToken(ScribbleParser.ID, text); + } + CommonToken t = new CommonToken(old); // Type and text set below, but "inherit" some other additional info + t.setType(ScribbleParser.ID); + t.setText(text); + return t; + } + + protected ScribDel createDefaultDelegate() + { + return new DefaultDel(); + } + + // public for DelDecoratorImpl (used from there; not here directly) + // Mutating setter + public static void setDel(ScribNodeBase n, ScribDel del) + { + //ScribNodeBase.del(n, del); // Defensive setter -- unnecessary ? + n.setDel(del); // Mutating setter + } + + + /** + * NameNodes + */ + + @Override + public IdNode IdNode(Token t, String text) + { + t = newIdToken(t, text); + // (Ext)IdNode is the only token with a "different" text to its node type -- info stored directly as its the text, no children + IdNode n = new IdNode(t); + n.decorateDel(this.df); + return n; + } + + @Override + public ExtIdNode ExtIdNode(Token t, String text) + { + t = newIdToken(t, text); + // (Ext)IdNode is the only token with a "different" text to its node type -- info stored directly as its the text, no children + ExtIdNode n = new ExtIdNode(t); + n.decorateDel(this.df); + return n; + } + + // Deprecate? Never need to make ambigname "manually" via af? (only constructed by ScribbleParser) + @Override + public AmbigNameNode AmbigNameNode(Token t, String text) + { + int ttype = ScribbleParser.ID; + t = newIdToken(t, text); + AmbigNameNode n = new AmbigNameNode(ttype, t); // Cf. Scribble.g, ID<...Node>[$ID] + n.decorateDel(this.df); + return n; + } + + @Override + public DataParamNode DataParamNode(Token t, String text) + { + int ttype = ScribbleParser.ID; // N.B. cf. ScribbleParser.DATA_NAME + t = newIdToken(t, text); + DataParamNode n = new DataParamNode(ttype, t); // Cf. Scribble.g, ID<...Node>[$ID] + n.decorateDel(this.df); + return n; + } + + @Override + public OpNode OpNode(Token t, String text) + { + int ttype = ScribbleParser.ID; + t = newIdToken(t, text); + OpNode n = new OpNode(ttype, t); // Cf. Scribble.g, ID<...Node>[$ID] + n.decorateDel(this.df); + return n; + } + + @Override + public RecVarNode RecVarNode(Token t, String text) + { + int ttype = ScribbleParser.ID; + t = newIdToken(t, text); + RecVarNode n = new RecVarNode(ttype, t); // Cf. Scribble.g, ID<...Node>[$ID] + n.decorateDel(this.df); + return n; + } + + @Override + public RoleNode RoleNode(Token t, String text) + { + int ttype = ScribbleParser.ID; + t = newIdToken(t, text); + RoleNode n = new RoleNode(ttype, t); // Cf. Scribble.g, ID<...Node>[$ID] + n.decorateDel(this.df); + return n; + } + + @Override + public SigParamNode SigParamNode(Token t, String text) + { + int ttype = ScribbleParser.ID; // N.B. cf. ScribbleParser.SIG_NAME + t = newIdToken(t, text); + SigParamNode n = new SigParamNode(ttype, t); // Cf. Scribble.g, ID<...Node>[$ID] + n.decorateDel(this.df); + return n; + } + + @Override + public DataNameNode DataNameNode(Token t, List elems) + { + t = newToken(t, ScribbleParser.DATA_NAME); + DataNameNode n = new DataNameNode(t); + n.addChildren(elems); + n.decorateDel(this.df); + return n; + } + + @Override + public GProtoNameNode GProtoNameNode(Token t, List elems) + { + t = newToken(t, ScribbleParser.GPROTO_NAME); + GProtoNameNode n = new GProtoNameNode(t); + n.addChildren(elems); + n.decorateDel(this.df); + return n; + } + + @Override + public LProtoNameNode LProtoNameNode(Token t, List elems) + { + t = newToken(t, ScribbleParser.LPROTO_NAME); + LProtoNameNode n = new LProtoNameNode(t); + n.addChildren(elems); + n.decorateDel(this.df); + return n; + } + + @Override + public ModuleNameNode ModuleNameNode(Token t, List elems) + { + t = newToken(t, ScribbleParser.MODULE_NAME); + ModuleNameNode n = new ModuleNameNode(t); + n.addChildren(elems); + n.decorateDel(this.df); + return n; + } + + @Override + public SigNameNode SigNameNode(Token t, List elems) + { + t = newToken(t, ScribbleParser.SIG_NAME); + SigNameNode n = new SigNameNode(t); + n.addChildren(elems); + n.decorateDel(this.df); + return n; + } + + + + /** + * From here, remaining ScribNodes that are not NameNodes -- should use the node specific addChildren1 (TODO: rename) + */ + + @Override + public Module Module(Token t, ModuleDecl moddecl, List> imports, + List> data, List> protos) + { + t = newToken(t, ScribbleParser.MODULE); + Module n = new Module(t); + n.addScribChildren(moddecl, imports, data, protos); + n.decorateDel(this.df); + return n; + } + + @Override + public ModuleDecl ModuleDecl(Token t, ModuleNameNode fullname) + { + t = newToken(t, ScribbleParser.MODULEDECL); + ModuleDecl n = new ModuleDecl(t); + n.addScribChildren(fullname); + n.decorateDel(this.df); + return n; + } + + @Override + public ImportModule ImportModule(Token t, ModuleNameNode modname, + ModuleNameNode alias) + { + t = newToken(t, ScribbleParser.IMPORTMODULE); + ImportModule n = new ImportModule(t); + n.addScribChildren(modname, alias); + n.decorateDel(this.df); + return n; + } + + @Override + public DataDecl DataDecl(Token t, IdNode schema, ExtIdNode extName, + ExtIdNode extSource, DataNameNode alias) + { + t = newToken(t, ScribbleParser.DATADECL); + DataDecl n = new DataDecl(t); + n.addScribChildren(alias, schema, extName, extSource); + n.decorateDel(this.df); + return n; + } + + @Override + public SigDecl SigDecl(Token t, IdNode schema, ExtIdNode extName, + ExtIdNode extSource, SigNameNode alias) + { + t = newToken(t, ScribbleParser.SIGDECL); + SigDecl n = new SigDecl(t); + n.addScribChildren(alias, schema, extName, extSource); + n.decorateDel(this.df); + return n; + } + + @Override + public GProtoDecl GProtoDecl(Token t, ProtoModList mods, GProtoHeader header, + GProtoDef def) + { + t = newToken(t, ScribbleParser.GPROTODECL); + GProtoDecl n = new GProtoDecl(t); + n.addScribChildren(mods, header, def); + n.decorateDel(this.df); + return n; + } + + @Override + public ProtoModList ProtoModList(Token t, List mods) + { + t = newToken(t, ScribbleParser.PROTOMOD_LIST); + ProtoModList n = new ProtoModList(t); + n.addScribChildren(mods); + n.decorateDel(this.df); + return n; + } + + @Override + public AuxMod AuxMod(Token t) + { + t = newToken(t, ScribbleParser.AUX_KW); // N.B. directly using KW + AuxMod n = new AuxMod(t); + n.decorateDel(this.df); + return n; + } + + @Override + public ExplicitMod ExplicitMod(Token t) + { + t = newToken(t, ScribbleParser.EXPLICIT_KW); // N.B. directly using KW + ExplicitMod n = new ExplicitMod(t); + n.decorateDel(this.df); + return n; + } + + @Override + public GProtoHeader GProtocolHeader(Token t, GProtoNameNode name, + RoleDeclList rs, NonRoleParamDeclList ps) + { + t = newToken(t, ScribbleParser.GPROTOHEADER); + GProtoHeader n = new GProtoHeader(t); + n.addScribChildren(name, ps, rs); + n.decorateDel(this.df); + return n; + } + + @Override + public RoleDeclList RoleDeclList(Token t, List ds) + { + t = newToken(t, ScribbleParser.ROLEDECL_LIST); + RoleDeclList n = new RoleDeclList(t); + n.addScribChildren(ds); + n.decorateDel(this.df); + return n; + } + + @Override + public RoleDecl RoleDecl(Token t, RoleNode r) + { + t = newToken(t, ScribbleParser.ROLEDECL); + RoleDecl n = new RoleDecl(t); + n.addScribChildren(r); + n.decorateDel(this.df); + return n; + } + + @Override + public NonRoleParamDeclList NonRoleParamDeclList(Token t, + List> ds) + { + t = newToken(t, ScribbleParser.PARAMDECL_LIST); + NonRoleParamDeclList n = new NonRoleParamDeclList(t); + n.addScribChildren(ds); + n.decorateDel(this.df); + return n; + } + + @Override + public DataParamDecl DataParamDecl(Token t, DataParamNode p) + { + t = newToken(t, ScribbleParser.DATAPARAMDECL); + DataParamDecl n = new DataParamDecl(t); + n.addScribChildren(p); + n.decorateDel(this.df); + return n; + } + + @Override + public SigParamDecl SigParamDecl(Token t, SigParamNode p) + { + t = newToken(t, ScribbleParser.SIGPARAMDECL); + SigParamDecl n = new SigParamDecl(t); + n.addScribChildren(p); + n.decorateDel(this.df); + return n; + } + + @Override + public GProtoDef GProtoDef(Token t, GProtoBlock block) + { + t = newToken(t, ScribbleParser.GPROTODEF); + GProtoDef n = new GProtoDef(t); + n.addScribChildren(block); + return n; + } + + @Override + public GProtoBlock GProtoBlock(Token t, GInteractionSeq seq) + { + t = newToken(t, ScribbleParser.GPROTOBLOCK); + GProtoBlock n = new GProtoBlock(t); + n.addScribChildren(seq); + n.decorateDel(this.df); + return n; + } + + @Override + public GInteractionSeq GInteractionSeq(Token t, List elems) + { + t = newToken(t, ScribbleParser.GINTERSEQ); + GInteractionSeq n = new GInteractionSeq(t); + n.addScribChildren(elems); + n.decorateDel(this.df); + return n; + } + + @Override + public SigLitNode SigLitNode(Token t, OpNode op, PayElemList pay) + { + t = newToken(t, ScribbleParser.SIG_LIT); + SigLitNode n = new SigLitNode(t); + n.addScribChildren(op, pay); + n.decorateDel(this.df); + return n; + } + + @Override + public PayElemList PayElemList(Token t, List> elems) + { + t = newToken(t, ScribbleParser.PAYELEM_LIST); + PayElemList n = new PayElemList(t); + n.addScribChildren(elems); + n.decorateDel(this.df); + return n; + } + + @Override + public UnaryPayElem UnaryPayElem(Token t, + PayElemNameNode name) + { + t = newToken(t, ScribbleParser.UNARY_PAYELEM); + UnaryPayElem n = new UnaryPayElem<>(t); + n.addScribChildren(name); + n.decorateDel(this.df); + return n; + } + + @Override + public GDelegPayElem GDelegPayElem(Token t, GProtoNameNode proto, + RoleNode role) + { + t = newToken(t, ScribbleParser.GDELEG_PAYELEM); + GDelegPayElem n = new GDelegPayElem(t); + n.addScribChildren(proto, role); + n.decorateDel(this.df); + return n; + } + + @Override + public GMsgTransfer GMsgTransfer(Token t, RoleNode src, MsgNode msg, + List dsts) + { + t = newToken(t, ScribbleParser.GMSGTRANSFER); + GMsgTransfer n = new GMsgTransfer(t); + n.addScribChildren(msg, src, dsts); + n.decorateDel(this.df); + return n; + } + + @Override + public GConnect GConnect(Token t, RoleNode src, MsgNode msg, RoleNode dst) + { + t = newToken(t, ScribbleParser.GCONNECT); + GConnect n = new GConnect(t); + n.addScribChildren(msg, src, Arrays.asList(dst)); + n.decorateDel(this.df); + return n; + } + + @Override + public GDisconnect GDisconnect(Token t, RoleNode left, RoleNode right) + { + t = newToken(t, ScribbleParser.GDCONN); + GDisconnect n = new GDisconnect(t); + n.addScribChildren(left, right); + n.decorateDel(this.df); + return n; + } + + @Override + public GWrap GWrap(Token t, RoleNode client, RoleNode server) + { + t = newToken(t, ScribbleParser.GWRAP); + GWrap n = new GWrap(t); + n.addScribChildren(client, server); + n.decorateDel(this.df); + return n; + } + + @Override + public GContinue GContinue(Token t, RecVarNode rv) + { + t = newToken(t, ScribbleParser.GCONTINUE); + GContinue n = new GContinue(t); + n.addScribChildren(rv); + n.decorateDel(this.df); + return n; + } + + @Override + public GDo GDo(Token t, GProtoNameNode proto, NonRoleArgList as, + RoleArgList rs) + { + t = newToken(t, ScribbleParser.GDO); + GDo n = new GDo(t); + n.addScribChildren(proto, as, rs); + n.decorateDel(this.df); + return n; + } + + @Override + public RoleArgList RoleArgList(Token t, List rs) + { + t = newToken(t, ScribbleParser.ROLEARG_LIST); + RoleArgList n = new RoleArgList(t); + n.addScribChildren(rs); + n.decorateDel(this.df); + return n; + } + + @Override + public RoleArg RoleArg(Token t, RoleNode r) + { + t = newToken(t, ScribbleParser.ROLEARG); + RoleArg n = new RoleArg(t); + n.addScribChildren(r); + n.decorateDel(this.df); + return n; + } + + @Override + public NonRoleArgList NonRoleArgList(Token t, List as) + { + t = newToken(t, ScribbleParser.NONROLEARG_LIST); + NonRoleArgList n = new NonRoleArgList(t); + n.addScribChildren(as); + n.decorateDel(this.df); + return n; + } + + @Override + public NonRoleArg NonRoleArg(Token t, NonRoleArgNode arg) + { + t = newToken(t, ScribbleParser.NONROLEARG); + NonRoleArg n = new NonRoleArg(t); + n.addScribChildren(arg); + n.decorateDel(this.df); + return n; + } + + @Override + public GChoice GChoice(Token t, RoleNode subj, List blocks) + { + t = newToken(t, ScribbleParser.GCHOICE); + GChoice n = new GChoice(t); + n.addScribChildren(subj, blocks); + n.decorateDel(this.df); + return n; + } + + @Override + public GRecursion GRecursion(Token t, RecVarNode rv, GProtoBlock block) + { + t = newToken(t, ScribbleParser.GRECURSION); + GRecursion n = new GRecursion(t); + n.addScribChildren(rv, block); + n.decorateDel(this.df); + return n; + } + + @Override + public LProjectionDecl LProjectionDecl(Token t, ProtoModList mods, + LProtoHeader header, LProtoDef def, GProtoNameNode fullname, + RoleNode self) // del extends that of LProtoDecl + { + t = newToken(t, ScribbleParser.LPROTODECL); + LProjectionDecl n = new LProjectionDecl(t); + n.addScribChildren(mods, header, def, fullname, self); + n.decorateDel(this.df); + return n; + } + + @Override + public LProtoHeader LProtoHeader(Token t, LProtoNameNode name, RoleDeclList rs, + NonRoleParamDeclList ps) + { + t = newToken(t, ScribbleParser.LPROTOHEADER); + LProtoHeader n = new LProtoHeader(t); + n.addScribChildren(name, ps, rs); + n.decorateDel(this.df); + return n; + } + + @Override + public LSelfDecl LSelfDecl(Token t, RoleNode r) + { + t = newToken(t, ScribbleParser.LSELFROLEDECL); + LSelfDecl n = new LSelfDecl(t); + n.addScribChildren(r); + n.decorateDel(this.df); + return n; + } + + @Override + public LProtoDef LProtoDef(Token t, LProtoBlock block) + { + t = newToken(t, ScribbleParser.LPROTODEF); + LProtoDef n = new LProtoDef(t); + n.addScribChildren(block); + return n; + } + + @Override + public LProtoBlock LProtoBlock(Token t, LInteractionSeq seq) + { + t = newToken(t, ScribbleParser.LPROTOBLOCK); + LProtoBlock n = new LProtoBlock(t); + n.addScribChildren(seq); + n.decorateDel(this.df); + return n; + } + + @Override + public LInteractionSeq LInteractionSeq(Token t, List elems) + { + t = newToken(t, ScribbleParser.LINTERSEQ); + LInteractionSeq n = new LInteractionSeq(t); + n.addScribChildren(elems); + n.decorateDel(this.df); + return n; + } + + @Override + public LSend LSend(Token t, RoleNode self, MsgNode msg, RoleNode dst) + { + t = newToken(t, ScribbleParser.LSEND); + LSend n = new LSend(t); + n.addScribChildren(msg, self, Arrays.asList(dst)); + n.decorateDel(this.df); + return n; + } + + @Override + public LRecv LRecv(Token t, RoleNode src, MsgNode msg, RoleNode self) + { + t = newToken(t, ScribbleParser.LRECV); + LRecv n = new LRecv(t); + n.addScribChildren(msg, src, Arrays.asList(self)); + n.decorateDel(this.df); + return n; + } + + @Override + public LAcc LAcc(Token t, RoleNode src, MsgNode msg, RoleNode self) + { + t = newToken(t, ScribbleParser.LACC); + LAcc n = new LAcc(t); + n.addScribChildren(msg, src, Arrays.asList(self)); + n.decorateDel(this.df); + return n; + } + + @Override + public LReq LReq(Token t, RoleNode self, MsgNode msg, RoleNode dst) + { + t = newToken(t, ScribbleParser.LREQ); + LReq n = new LReq(t); + n.addScribChildren(msg, self, Arrays.asList(dst)); + n.decorateDel(this.df); + return n; + } + + @Override + public LDisconnect LDisconnect(Token t, RoleNode self, RoleNode peer) + { + t = newToken(t, ScribbleParser.LDCONN); + LDisconnect n = new LDisconnect(t); + n.addScribChildren(self, peer); + n.decorateDel(this.df); + return n; + } + + @Override + public LClientWrap LClientWrap(Token t, RoleNode client, RoleNode server) + { + t = newToken(t, ScribbleParser.LCLIENTWRAP); + LClientWrap n = new LClientWrap(t); + n.addScribChildren(client, server); + n.decorateDel(this.df); + return n; + } + + @Override + public LServerWrap LServerWrap(Token t, RoleNode client, RoleNode server) + { + t = newToken(t, ScribbleParser.LSERVERWRAP); + LServerWrap n = new LServerWrap(t); + n.addScribChildren(client, server); + n.decorateDel(this.df); + return n; + } + + @Override + public LContinue LContinue(Token t, RecVarNode rv) + { + t = newToken(t, ScribbleParser.LCONTINUE); + LContinue n = new LContinue(t); + n.addScribChildren(rv); + n.decorateDel(this.df); + return n; + } + + @Override + public LDo LDo(Token t, LProtoNameNode proto, NonRoleArgList as, + RoleArgList rs) + { + t = newToken(t, ScribbleParser.LDO); + LDo n = new LDo(t); + n.addScribChildren(proto, as, rs); + n.decorateDel(this.df); + return n; + } + + @Override + public LChoice LChoice(Token t, RoleNode subj, List blocks) + { + t = newToken(t, ScribbleParser.LCHOICE); + LChoice n = new LChoice(t); + n.addScribChildren(subj, blocks); + n.decorateDel(this.df); + return n; + } + + @Override + public LRecursion LRecursion(Token t, RecVarNode rv, LProtoBlock block) + { + t = newToken(t, ScribbleParser.LRECURSION); + LRecursion n = new LRecursion(t); + n.addScribChildren(rv, block); + n.decorateDel(this.df); + return n; + } +} + + + + + + + + + + + + + + + + + + + + + + + + + + +/* + @Override + public DummyProjectionRoleNode DummyProjectionRoleNode() + { + DummyProjectionRoleNode dprn = new DummyProjectionRoleNode(); + dprn = (DummyProjectionRoleNode) dprn.del(createDefaultDelegate()); + return dprn; + } + + @Override + public LDelegationElem LDelegationElem(CommonTree source, + LProtocolNameNode proto) + { + LDelegationElem de = new LDelegationElem(source, proto); + de = del(de, createDefaultDelegate()); + return de; + } + + @Override // Called from LProtocolDecl::clone, but currently never used -- local proto decls only projected, not parsed + public LProtocolDecl LProtocolDecl(CommonTree source, List mods, + LProtocolHeader header, LProtocolDef def) + { + LProtocolDecl lpd = new LProtocolDecl(source, mods, header, def); + lpd = del(lpd, new LProtocolDeclDel()); + return lpd; + } + + @Override + public LProjectionDecl LProjectionDecl(CommonTree source, + List mods, GProtocolName fullname, Role self, + LProtocolHeader header, LProtocolDef def) + // del extends that of LProtocolDecl + { + LProjectionDecl lpd = new LProjectionDecl(source, mods, header, def); + lpd = del(lpd, new LProjectionDeclDel());//fullname, self)); + return lpd; + } + + @Override + public LProtocolHeader LProtocolHeader(CommonTree source, + LProtocolNameNode name, RoleDeclList roledecls, + NonRoleParamDeclList paramdecls) + { + LProtocolHeader lph = new LProtocolHeader(source, name, roledecls, + paramdecls); + lph = del(lph, createDefaultDelegate()); + return lph; + } + + @Override + public SelfRoleDecl SelfRoleDecl(CommonTree source, RoleNode namenode) + { + SelfRoleDecl rd = new SelfRoleDecl(source, namenode); + rd = del(rd, new RoleDeclDel()); + return rd; + } + + @Override + public LProtocolDef LProtocolDef(CommonTree source, LProtocolBlock block) + { + LProtocolDef lpd = new LProtocolDef(source, block); + lpd = del(lpd, new LProtocolDefDel()); + return lpd; + } + + @Override + public LProtocolBlock LProtocolBlock(CommonTree source, LInteractionSeq seq) + { + LProtocolBlock lpb = new LProtocolBlock(source, seq); + lpb = del(lpb, new LProtocolBlockDel()); + return lpb; + } + + @Override + public LInteractionSeq LInteractionSeq(CommonTree source, + List actions) + { + LInteractionSeq lis = new LInteractionSeq(source, actions); + lis = del(lis, new LInteractionSeqDel()); + return lis; + } + + @Override + public LSend LSend(CommonTree source, RoleNode src, MessageNode msg, + List dests) + { + LSend ls = new LSend(source, src, msg, dests); + ls = del(ls, new LSendDel()); + return ls; + } + + @Override + public LRecv LReceive(CommonTree source, RoleNode src, MessageNode msg, + List dests) + { + LRecv ls = new LRecv(source, src, msg, dests); + ls = del(ls, new LReceiveDel()); + return ls; + } + + @Override + public LRequest LRequest(CommonTree source, RoleNode src, MessageNode msg, + RoleNode dest) + //public LConnect LConnect(RoleNode src, RoleNode dest) + { + LRequest lc = new LRequest(source, src, msg, dest); + //LConnect lc = new LConnect(src, dest); + lc = del(lc, new LRequestDel()); + return lc; + } + + @Override + public LAccept LAccept(CommonTree source, RoleNode src, MessageNode msg, + RoleNode dest) + //public LAccept LAccept(RoleNode src, RoleNode dest) + { + LAccept la = new LAccept(source, src, msg, dest); + //LAccept la = new LAccept(src, dest); + la = del(la, new LAcceptDel()); + return la; + } + + @Override + public LDisconnect LDisconnect(CommonTree source, RoleNode self, + RoleNode peer) + { + LDisconnect lc = new LDisconnect(source, UnitMessageSigNode(), self, peer); + lc = del(lc, new LDisconnectDel()); + return lc; + } + + @Override + public LWrapClient LWrapClient(CommonTree source, RoleNode self, + RoleNode peer) + { + LWrapClient lwc = new LWrapClient(source, UnitMessageSigNode(), self, peer); + lwc = del(lwc, new LWrapClientDel()); + return lwc; + } + + @Override + public LWrapServer LWrapServer(CommonTree source, RoleNode self, + RoleNode peer) + { + LWrapServer lws = new LWrapServer(source, UnitMessageSigNode(), self, peer); + lws = del(lws, new LWrapServerDel()); + return lws; + } + + @Override + public LChoice LChoice(CommonTree source, RoleNode subj, + List blocks) + { + LChoice lc = new LChoice(source, subj, blocks); + lc = del(lc, new LChoiceDel()); + return lc; + } + + @Override + public LRecursion LRecursion(CommonTree source, RecVarNode recvar, + LProtocolBlock block) + { + LRecursion lr = new LRecursion(source, recvar, block); + lr = del(lr, new LRecursionDel()); + return lr; + } + + @Override + public LContinue LContinue(CommonTree source, RecVarNode recvar) + { + LContinue lc = new LContinue(source, recvar); + lc = del(lc, new LContinueDel()); + return lc; + } + + @Override + public LDo LDo(CommonTree source, RoleArgList roleinstans, + NonRoleArgList arginstans, LProtocolNameNode proto) + { + LDo ld = new LDo(source, roleinstans, arginstans, proto); + ld = del(ld, new LDoDel()); + return ld; + } +*/ diff --git a/scribble-parser/src/main/java/org/scribble/del/DelFactoryImpl.java b/scribble-parser/src/main/java/org/scribble/del/DelFactoryImpl.java new file mode 100644 index 000000000..88c607567 --- /dev/null +++ b/scribble-parser/src/main/java/org/scribble/del/DelFactoryImpl.java @@ -0,0 +1,543 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.del; + +import org.scribble.ast.AstFactoryImpl; +import org.scribble.ast.AuxMod; +import org.scribble.ast.DataDecl; +import org.scribble.ast.DataParamDecl; +import org.scribble.ast.ExplicitMod; +import org.scribble.ast.ImportModule; +import org.scribble.ast.Module; +import org.scribble.ast.ModuleDecl; +import org.scribble.ast.NonRoleArg; +import org.scribble.ast.NonRoleArgList; +import org.scribble.ast.NonRoleParamDeclList; +import org.scribble.ast.PayElemList; +import org.scribble.ast.ProtoModList; +import org.scribble.ast.RoleArg; +import org.scribble.ast.RoleArgList; +import org.scribble.ast.RoleDecl; +import org.scribble.ast.RoleDeclList; +import org.scribble.ast.ScribNodeBase; +import org.scribble.ast.SigDecl; +import org.scribble.ast.SigLitNode; +import org.scribble.ast.SigParamDecl; +import org.scribble.ast.UnaryPayElem; +import org.scribble.ast.global.GChoice; +import org.scribble.ast.global.GConnect; +import org.scribble.ast.global.GContinue; +import org.scribble.ast.global.GDelegPayElem; +import org.scribble.ast.global.GDisconnect; +import org.scribble.ast.global.GDo; +import org.scribble.ast.global.GInteractionSeq; +import org.scribble.ast.global.GMsgTransfer; +import org.scribble.ast.global.GProtoBlock; +import org.scribble.ast.global.GProtoDecl; +import org.scribble.ast.global.GProtoDef; +import org.scribble.ast.global.GProtoHeader; +import org.scribble.ast.global.GRecursion; +import org.scribble.ast.global.GWrap; +import org.scribble.ast.local.LAcc; +import org.scribble.ast.local.LChoice; +import org.scribble.ast.local.LClientWrap; +import org.scribble.ast.local.LContinue; +import org.scribble.ast.local.LDisconnect; +import org.scribble.ast.local.LDo; +import org.scribble.ast.local.LInteractionSeq; +import org.scribble.ast.local.LProjectionDecl; +import org.scribble.ast.local.LProtoBlock; +import org.scribble.ast.local.LProtoDecl; +import org.scribble.ast.local.LProtoDef; +import org.scribble.ast.local.LProtoHeader; +import org.scribble.ast.local.LRecursion; +import org.scribble.ast.local.LRecv; +import org.scribble.ast.local.LReq; +import org.scribble.ast.local.LSelfDecl; +import org.scribble.ast.local.LSend; +import org.scribble.ast.local.LServerWrap; +import org.scribble.ast.name.qualified.DataNameNode; +import org.scribble.ast.name.qualified.GProtoNameNode; +import org.scribble.ast.name.qualified.LProtoNameNode; +import org.scribble.ast.name.qualified.ModuleNameNode; +import org.scribble.ast.name.qualified.SigNameNode; +import org.scribble.ast.name.simple.AmbigNameNode; +import org.scribble.ast.name.simple.DataParamNode; +import org.scribble.ast.name.simple.ExtIdNode; +import org.scribble.ast.name.simple.IdNode; +import org.scribble.ast.name.simple.OpNode; +import org.scribble.ast.name.simple.RecVarNode; +import org.scribble.ast.name.simple.RoleNode; +import org.scribble.ast.name.simple.SigParamNode; +import org.scribble.del.global.GChoiceDel; +import org.scribble.del.global.GConnectDel; +import org.scribble.del.global.GContinueDel; +import org.scribble.del.global.GDelegationElemDel; +import org.scribble.del.global.GDisconnectDel; +import org.scribble.del.global.GDoDel; +import org.scribble.del.global.GInteractionSeqDel; +import org.scribble.del.global.GMessageTransferDel; +import org.scribble.del.global.GProtoBlockDel; +import org.scribble.del.global.GProtoDeclDel; +import org.scribble.del.global.GProtoDefDel; +import org.scribble.del.global.GRecursionDel; +import org.scribble.del.global.GWrapDel; +import org.scribble.del.local.LAccDel; +import org.scribble.del.local.LChoiceDel; +import org.scribble.del.local.LClientWrapDel; +import org.scribble.del.local.LContinueDel; +import org.scribble.del.local.LDisconnectDel; +import org.scribble.del.local.LDoDel; +import org.scribble.del.local.LInteractionSeqDel; +import org.scribble.del.local.LProjectionDeclDel; +import org.scribble.del.local.LProtoBlockDel; +import org.scribble.del.local.LProtoDeclDel; +import org.scribble.del.local.LProtoDefDel; +import org.scribble.del.local.LRecursionDel; +import org.scribble.del.local.LRecvDel; +import org.scribble.del.local.LReqDel; +import org.scribble.del.local.LSendDel; +import org.scribble.del.local.LServerWrapDel; +import org.scribble.del.name.qualified.DataNameNodeDel; +import org.scribble.del.name.qualified.SigNameNodeDel; +import org.scribble.del.name.simple.AmbigNameNodeDel; +import org.scribble.del.name.simple.NonRoleParamNodeDel; +import org.scribble.del.name.simple.RecVarNodeDel; +import org.scribble.del.name.simple.RoleNodeDel; + + +public class DelFactoryImpl implements DelFactory +{ + public DelFactoryImpl() + { + + } + + protected ScribDel createDefaultDel() + { + return new DefaultDel(); + } + + // Mutating setter + protected static void setDel(ScribNodeBase n, ScribDel del) + { + AstFactoryImpl.setDel(n, del); + } + + @Override + public void IdNode(IdNode n) + { + setDel(n, createDefaultDel()); // Necessary? + } + + @Override + public void ExtIdNode(ExtIdNode n) + { + setDel(n, createDefaultDel()); // Necessary? + } + + @Override + public void AmbigNameNode(AmbigNameNode n) + { + setDel(n, new AmbigNameNodeDel()); + } + + @Override + public void DataParamNode(DataParamNode n) + { + setDel(n, new NonRoleParamNodeDel()); + } + + @Override + public void OpNode(OpNode n) + { + setDel(n, createDefaultDel()); + } + + @Override + public void RecVarNode(RecVarNode n) + { + setDel(n, new RecVarNodeDel()); + } + + @Override + public void RoleNode(RoleNode r) + { + setDel(r, new RoleNodeDel()); + } + + @Override + public void SigParamNode(SigParamNode n) + { + setDel(n, new NonRoleParamNodeDel()); + } + + @Override + public void DataNameNode(DataNameNode n) + { + setDel(n, new DataNameNodeDel()); + } + + @Override + public void GProtoNameNode(GProtoNameNode n) + { + setDel(n, createDefaultDel()); + } + + @Override + public void LProtoNameNode(LProtoNameNode n) + { + setDel(n, createDefaultDel()); + } + + @Override + public void ModuleNameNode(ModuleNameNode n) + { + setDel(n, createDefaultDel()); + } + + @Override + public void SigNameNode(SigNameNode n) + { + setDel(n, new SigNameNodeDel()); + } + + @Override + public void Module(Module n) + { + setDel(n, new ModuleDel()); + } + + @Override + public void ModuleDecl(ModuleDecl n) + { + setDel(n, createDefaultDel()); + } + + @Override + public void ImportModule(ImportModule n) + { + setDel(n, new ImportModuleDel()); + } + + @Override + public void DataDecl(DataDecl n) + { + setDel(n, createDefaultDel()); + } + + @Override + public void SigDecl(SigDecl n) + { + setDel(n, createDefaultDel()); + } + + @Override + public void GProtoDecl(GProtoDecl n) + { + setDel(n, new GProtoDeclDel()); + } + + @Override + public void ProtoModList(ProtoModList n) + { + setDel(n, createDefaultDel()); + } + + @Override + public void AuxMod(AuxMod n) + { + setDel(n, createDefaultDel()); + } + + @Override + public void ExplicitMod(ExplicitMod n) + { + setDel(n, createDefaultDel()); + } + + @Override + public void GProtoHeader(GProtoHeader n) + { + setDel(n, createDefaultDel()); + } + + @Override + public void RoleDeclList(RoleDeclList n) + { + setDel(n, new RoleDeclListDel()); + } + + @Override + public void RoleDecl(RoleDecl n) + { + setDel(n, new RoleDeclDel()); + } + + @Override + public void NonRoleParamDeclList(NonRoleParamDeclList n) + { + setDel(n, new NonRoleParamDeclListDel()); + } + + @Override + public void DataParamDecl(DataParamDecl n) + { + setDel(n, new NonRoleParamDeclDel()); + } + + @Override + public void SigParamDecl(SigParamDecl sd) + { + setDel(sd, new NonRoleParamDeclDel()); + } + + @Override + public void GProtoDef(GProtoDef n) + { + setDel(n, new GProtoDefDel()); + } + + @Override + public void GProtoBlock(GProtoBlock n) + { + setDel(n, new GProtoBlockDel()); + } + + @Override + public void GInteractionSeq(GInteractionSeq n) + { + setDel(n, new GInteractionSeqDel()); + } + + @Override + public void SigLitNode(SigLitNode n) + { + setDel(n, createDefaultDel()); + } + + @Override + public void PayElemList(PayElemList n) + { + setDel(n, createDefaultDel()); + //setDel(pay, new PayloadElemListDel()); + } + + @Override + public void UnaryPayElem(UnaryPayElem n) + { + setDel(n, createDefaultDel()); + } + + @Override + public void GDelegPayElem(GDelegPayElem n) + { + //setDel(n, createDefaultDelegate()); + setDel(n, new GDelegationElemDel()); + } + + /*@Override + public LDelegationElem LDelegationElem(CommonTree source, LProtocolNameNode proto) + { + LDelegationElem de = new LDelegationElem(source, proto); + de = setDel(de, createDefaultDelegate()); + return de; + }*/ + + @Override + public void GMsgTransfer(GMsgTransfer n) + { + setDel(n, new GMessageTransferDel()); + } + + @Override + public void GConnect(GConnect n) + { + setDel(n, new GConnectDel()); + } + + @Override + public void GDisconnect(GDisconnect n) + { + setDel(n, new GDisconnectDel()); + } + + @Override + public void GWrap(GWrap n) + { + setDel(n, new GWrapDel()); + } + + @Override + public void GContinue(GContinue n) + { + setDel(n, new GContinueDel()); + } + + @Override + public void GDo(GDo n) + { + setDel(n, new GDoDel()); + } + + @Override + public void RoleArgList(RoleArgList n) + { + setDel(n, new RoleArgListDel()); + } + + @Override + public void RoleArg(RoleArg n) + { + setDel(n, createDefaultDel()); + } + + @Override + public void NonRoleArgList(NonRoleArgList n) + { + setDel(n, new NonRoleArgListDel()); + } + + @Override + public void NonRoleArg(NonRoleArg n) + { + setDel(n, createDefaultDel()); + } + + @Override + public void GChoice(GChoice n) + { + setDel(n, new GChoiceDel()); + } + + @Override + public void GRecursion(GRecursion n) + { + setDel(n, new GRecursionDel()); + } + + @Override + public void LProtoDecl(LProtoDecl n) + { + setDel(n, new LProtoDeclDel()); + } + + @Override + public void LProjectionDecl(LProjectionDecl n) + { + setDel(n, new LProjectionDeclDel()); + } + + @Override + public void LProtoHeader(LProtoHeader n) + { + setDel(n, createDefaultDel()); + } + + @Override + public void LSelfDecl(LSelfDecl n) + { + setDel(n, new RoleDeclDel()); + } + + @Override + public void LProtoDef(LProtoDef n) + { + setDel(n, new LProtoDefDel()); + } + + @Override + public void LProtoBlock(LProtoBlock n) + { + setDel(n, new LProtoBlockDel()); + } + + @Override + public void LInteractionSeq(LInteractionSeq n) + { + setDel(n, new LInteractionSeqDel()); + } + + /*@Override + public void LDelegElem(LDelegElem n) + { + setDel(n, new LDelegElemDel()); + }*/ + + @Override + public void LSend(LSend n) + { + setDel(n, new LSendDel()); + } + + @Override + public void LRecv(LRecv n) + { + setDel(n, new LRecvDel()); + } + + @Override + public void LAcc(LAcc n) + { + setDel(n, new LAccDel()); + } + + @Override + public void LReq(LReq n) + { + setDel(n, new LReqDel()); + } + + @Override + public void LDisconnect(LDisconnect n) + { + setDel(n, new LDisconnectDel()); + } + + @Override + public void LClientWrap(LClientWrap n) + { + setDel(n, new LClientWrapDel()); + } + + @Override + public void LServerWrap(LServerWrap n) + { + setDel(n, new LServerWrapDel()); + } + + @Override + public void LContinue(LContinue n) + { + setDel(n, new LContinueDel()); + } + + @Override + public void LDo(LDo n) + { + setDel(n, new LDoDel()); + } + + @Override + public void LChoice(LChoice n) + { + setDel(n, new LChoiceDel()); + } + + @Override + public void LRecursion(LRecursion n) + { + setDel(n, new LRecursionDel()); + } +} diff --git a/scribble-parser/src/main/java/org/scribble/parser/ScribAntlrWrapper.java b/scribble-parser/src/main/java/org/scribble/parser/ScribAntlrWrapper.java new file mode 100644 index 000000000..3ac6bedb4 --- /dev/null +++ b/scribble-parser/src/main/java/org/scribble/parser/ScribAntlrWrapper.java @@ -0,0 +1,122 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.parser; + +import java.io.IOException; +import java.io.InputStream; +import java.util.List; +import java.util.stream.Collectors; + +import org.antlr.runtime.ANTLRStringStream; +import org.antlr.runtime.CommonTokenStream; +import org.antlr.runtime.Lexer; +import org.antlr.runtime.RecognitionException; +import org.antlr.runtime.tree.CommonErrorNode; +import org.antlr.runtime.tree.CommonTree; +import org.scribble.ast.Module; +import org.scribble.del.DelFactory; +import org.scribble.parser.antlr.ScribbleLexer; +import org.scribble.parser.antlr.ScribbleParser; +import org.scribble.util.ScribParserException; + +// InputStream -> ANTLR CommonTree -- parses Resource.getInputStream() into ANTLR CommonTrees +// Wraps the ScribbleLexer and ScribbleParser generated by ANTLR from Scribble.g +public class ScribAntlrWrapper +{ + public final DelFactory df; // Will be shared with af and Job (by Main) + + public ScribAntlrWrapper(DelFactory df) + { + this.df = df; + } + + // Scribble extensions should override newScribbleLexer/Parser as appropriate + // A fresh Lexer/Parser is needed by each call to parse + public Lexer newScribbleLexer(ANTLRStringStream ss) + { + return new ScribbleLexer(ss); + } + + // Scribble extensions should override newScribbleLexer/Parser as appropriate + // ScribbleParser: a Parser that has a top-level "module" method + // (And has "setTreeAdaptor") + public ScribbleParser newScribbleParser(CommonTokenStream ts) + { + return new ScribbleParser(ts); + } + + // Parse InputStream (from a Resource) into a Module -- N.B. not del decorated (yet) + public Module parse(InputStream is) throws ScribParserException + { + try + { + String input = ScribAntlrWrapper.readInput(is); + Lexer lex = newScribbleLexer(new ANTLRStringStream(input)); + Module mod = runScribbleParser(new CommonTokenStream(lex)); + return mod; + } + catch (IOException e) + { + throw new ScribParserException(e); + } + } + + protected Module runScribbleParser(CommonTokenStream ts) + throws ScribParserException + { + try + { + ScribbleParser p = newScribbleParser(ts); + p.setTreeAdaptor(new ScribTreeAdaptor(this.df)); + return (Module) p.module().getTree(); + // Cast, because no convenient way to expose an interface for all (Scribble)Parsers with top-level "module" method? + } + catch (RecognitionException e) + { + throw new ScribParserException(e); + } + } + + // CHECKME: should this be used somewhere? + public static void checkForAntlrErrors(CommonTree t) + { + if (t.getChildCount() > 0) // getChildren returns null instead of empty list + { + List errors = ((List) t.getChildren()).stream() + .filter(c -> (c instanceof CommonErrorNode)) + .map(c -> (CommonErrorNode) c) + .collect(Collectors.toList()); + if (errors.size() > 0) // Antlr prints errors to System.err by default, but then attempts to carry on + // Should never get here now, Antlr displayRecognitionError overridden to force exit: Antlr error recovery means not all errors produce CommonErrorNode + { + // TODO: improve feedback message + System.err + .println("[ScribParser] Aborting due to parsing errors: " + errors); + System.exit(1); + } + } + } + + protected static String readInput(InputStream is) throws IOException + { + return new String(ScribAntlrWrapper.readResource(is)); + } + + private static byte[] readResource(InputStream is) throws IOException + { + byte[] bs = new byte[is.available()]; + is.read(bs); + return bs; + } +} diff --git a/scribble-parser/src/main/java/org/scribble/parser/ScribTreeAdaptor.java b/scribble-parser/src/main/java/org/scribble/parser/ScribTreeAdaptor.java new file mode 100644 index 000000000..10b18fdff --- /dev/null +++ b/scribble-parser/src/main/java/org/scribble/parser/ScribTreeAdaptor.java @@ -0,0 +1,169 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.parser; + +import org.antlr.runtime.CommonToken; +import org.antlr.runtime.Token; +import org.antlr.runtime.tree.CommonTreeAdaptor; +import org.scribble.ast.AuxMod; +import org.scribble.ast.DataDecl; +import org.scribble.ast.DataParamDecl; +import org.scribble.ast.ExplicitMod; +import org.scribble.ast.ImportModule; +import org.scribble.ast.Module; +import org.scribble.ast.ModuleDecl; +import org.scribble.ast.NonRoleArg; +import org.scribble.ast.NonRoleArgList; +import org.scribble.ast.NonRoleParamDeclList; +import org.scribble.ast.PayElemList; +import org.scribble.ast.ProtoModList; +import org.scribble.ast.RoleArg; +import org.scribble.ast.RoleArgList; +import org.scribble.ast.RoleDecl; +import org.scribble.ast.RoleDeclList; +import org.scribble.ast.ScribNil; +import org.scribble.ast.ScribNode; +import org.scribble.ast.ScribNodeBase; +import org.scribble.ast.SigDecl; +import org.scribble.ast.SigLitNode; +import org.scribble.ast.SigParamDecl; +import org.scribble.ast.UnaryPayElem; +import org.scribble.ast.global.GChoice; +import org.scribble.ast.global.GConnect; +import org.scribble.ast.global.GContinue; +import org.scribble.ast.global.GDelegPayElem; +import org.scribble.ast.global.GDisconnect; +import org.scribble.ast.global.GDo; +import org.scribble.ast.global.GInteractionSeq; +import org.scribble.ast.global.GMsgTransfer; +import org.scribble.ast.global.GProtoBlock; +import org.scribble.ast.global.GProtoDecl; +import org.scribble.ast.global.GProtoDef; +import org.scribble.ast.global.GProtoHeader; +import org.scribble.ast.global.GRecursion; +import org.scribble.ast.global.GWrap; +import org.scribble.ast.name.qualified.DataNameNode; +import org.scribble.ast.name.qualified.GProtoNameNode; +import org.scribble.ast.name.qualified.ModuleNameNode; +import org.scribble.ast.name.qualified.SigNameNode; +import org.scribble.ast.name.simple.ExtIdNode; +import org.scribble.ast.name.simple.IdNode; +import org.scribble.ast.name.simple.OpNode; +import org.scribble.del.DelFactory; +import org.scribble.parser.antlr.ScribbleParser; + +// CHECKME: do del setting directly here (or use af?), instead of DelDecorator +// get/setType don't seem to be really used +public class ScribTreeAdaptor extends CommonTreeAdaptor +{ + protected final DelFactory df; // N.B. not af -- here, create nodes "manually" (with del setting) to preserve original tokens + + public ScribTreeAdaptor(DelFactory df) + { + this.df = df; + } + + // Generated parser seems to use nil to create "blank" nodes and then "fill them in" + @Override + public Object nil() + { + return new ScribNil(); + } + + // Create a Tree (ScribNode) from a Token + @Override + public ScribNode create(Token t) + { + // Switching on ScribbleParser int type constants -- generated from Scribble.g tokens + // Previously: String tname = t.getText(); -- by convention of Scribble.g, type constant name given as node text, e.g., module: ... -> ^(MODULE ...) + ScribNodeBase n; + switch (t.getType()) + { + case ScribbleParser.ID: n = new IdNode(t); break; + case ScribbleParser.EXTID: + t = new CommonToken(t); + String text = t.getText(); + t.setText(text.substring(1, text.length()-1)); // N.B. remove surrounding quotes "..." + n = new ExtIdNode(t); + break; + + // Simple names "constructed directly" by parser, e.g., t=ID -> ID<...Node>[$t] -- N.B. DelDecorator pass needed for them (CHECKME: also do those here instead? to deprecate DelDecorator) + + // Compound names + case ScribbleParser.GPROTO_NAME: n = new GProtoNameNode(t); break; + case ScribbleParser.MODULE_NAME: n = new ModuleNameNode(t); break; + case ScribbleParser.DATA_NAME: n = new DataNameNode(t); break; + case ScribbleParser.SIG_NAME: n = new SigNameNode(t); break; + + // Non-name (i.e., general) AST nodes + case ScribbleParser.MODULE: n = new Module(t); break; + case ScribbleParser.MODULEDECL: n = new ModuleDecl(t); break; + case ScribbleParser.IMPORTMODULE: n = new ImportModule(t); break; + + case ScribbleParser.DATADECL: n = new DataDecl(t); break; + case ScribbleParser.SIGDECL: n = new SigDecl(t); break; + case ScribbleParser.GPROTODECL: n = new GProtoDecl(t); break; + + // CHECKME: refactor into header? + case ScribbleParser.PROTOMOD_LIST: n = new ProtoModList(t); break; + case ScribbleParser.AUX_KW: n = new AuxMod(t); break; // FIXME: KW return by parser directly (cf. other tokens are imaginary) + case ScribbleParser.EXPLICIT_KW: n = new ExplicitMod(t); break; + + case ScribbleParser.GPROTOHEADER: n = new GProtoHeader(t); break; + case ScribbleParser.ROLEDECL_LIST: n = new RoleDeclList(t); break; + case ScribbleParser.ROLEDECL: n = new RoleDecl(t); break; + case ScribbleParser.PARAMDECL_LIST: + n = new NonRoleParamDeclList(t); + break; + case ScribbleParser.DATAPARAMDECL: n = new DataParamDecl(t); break; + case ScribbleParser.SIGPARAMDECL: n = new SigParamDecl(t); break; + + case ScribbleParser.GPROTODEF: n = new GProtoDef(t); break; + case ScribbleParser.GPROTOBLOCK: n = new GProtoBlock(t); break; + case ScribbleParser.GINTERSEQ: n = new GInteractionSeq(t); break; + + case ScribbleParser.SIG_LIT: n = new SigLitNode(t); break; + case ScribbleParser.PAYELEM_LIST: n = new PayElemList(t); break; + case ScribbleParser.UNARY_PAYELEM: n = new UnaryPayElem<>(t); break; + case ScribbleParser.GDELEG_PAYELEM: n = new GDelegPayElem(t); break; + + case ScribbleParser.GMSGTRANSFER: n = new GMsgTransfer(t); break; + case ScribbleParser.GCONNECT: n = new GConnect(t); break; + case ScribbleParser.GDCONN: n = new GDisconnect(t); break; + case ScribbleParser.GWRAP: n = new GWrap(t); break; + + case ScribbleParser.GCONTINUE: n = new GContinue(t); break; + case ScribbleParser.GDO: n = new GDo(t); break; + + case ScribbleParser.ROLEARG_LIST: n = new RoleArgList(t); break; + case ScribbleParser.ROLEARG: n = new RoleArg(t); break; + case ScribbleParser.NONROLEARG_LIST: n = new NonRoleArgList(t); break; + case ScribbleParser.NONROLEARG: n = new NonRoleArg(t); break; + + case ScribbleParser.GCHOICE: n = new GChoice(t); break; + case ScribbleParser.GRECURSION: n = new GRecursion(t); break; + + // Special cases + case ScribbleParser.EMPTY_OP: n = new OpNode(t); break; // From Scribble.g, token (t) text is OpNode.EMPTY_OP_TOKEN_TEXT*/ + + default: + { + throw new RuntimeException("[TODO] Unknown token type (cf. ScribbleParser): " + t); + } + } + n.decorateDel(this.df); + + return n; + } +} diff --git a/scribble-parser/src/test/resources/scribble/examples/GChoice.scr b/scribble-parser/src/test/resources/scribble/examples/GChoice.scr new file mode 100644 index 000000000..131a4e1d1 --- /dev/null +++ b/scribble-parser/src/test/resources/scribble/examples/GChoice.scr @@ -0,0 +1,12 @@ +module scribble.examples.GChoice; + +type "{http://www.acme.com/financial}Order" from "http://www.acme.com/schemas/Order.xsd" as Order; +type "{http://www.acme.com/financial}QuoteRequest" from "http://www.acme.com/schemas/QuoteRequest.xsd" as QuoteRequest; + +global protocol GChoiceTest(role Buyer,role Seller) { + choice at Buyer { + buy(Order) from Buyer to Seller; + } or { + buy(QuoteRequest) from Buyer to Seller; + } +} diff --git a/scribble-parser/src/test/resources/scribble/examples/GDo.scr b/scribble-parser/src/test/resources/scribble/examples/GDo.scr new file mode 100644 index 000000000..8b8e171ec --- /dev/null +++ b/scribble-parser/src/test/resources/scribble/examples/GDo.scr @@ -0,0 +1,20 @@ +module scribble.examples.GDo; + +type "{http://www.acme.com/financial}Order" from "http://www.acme.com/schemas/Order.xsd" as Order; +type "{http://www.acme.com/financial}Receipt" from "http://www.acme.com/schemas/Receipt.xsd" as Receipt; + +global protocol GDoTest(role Buyer, role Seller) { + do OtherProtocol(Buyer, Seller); + do a.b.c.OtherProtocol(Buyer, Seller); + do AnotherProtocol(Buyer, Seller); + do a.b.c.AnotherProtocol(Buyer, Seller); +} + +aux global protocol OtherProtocol(role OtherBuyer, role OtherSeller) { + dummy() from OtherBuyer to OtherSeller; +} + +aux global protocol AnotherProtocol(role OtherBuyer, role OtherSeller) { + Buy from OtherBuyer to OtherSeller; + Confirm from OtherSeller to OtherBuyer; +} diff --git a/scribble-parser/src/test/resources/scribble/examples/GMessage.scr b/scribble-parser/src/test/resources/scribble/examples/GMessage.scr new file mode 100644 index 000000000..ad361a2ba --- /dev/null +++ b/scribble-parser/src/test/resources/scribble/examples/GMessage.scr @@ -0,0 +1,20 @@ +module scribble.examples.GMessage; + +type "{http://www.acme.com/financial}Order" from "http://www.acme.com/schemas/Order.xsd" as Order; +type "{http://www.acme.com/financial}Customer" from "http://www.acme.com/schemas/Customer.xsd" as Customer; + +global protocol GMessageTest(role Buyer, role SellerA, role SellerB) { + buy(Order, Customer) from Buyer to SellerA; + //buy(Order, Customer) from Buyer to SellerA, SellerB; + buy(Order, Customer) from Buyer to SellerA; + //buy(Order) from Buyer to SellerA, SellerB; + buy(Order) from Buyer to SellerA; +} + +aux global protocol PlaceOrder(role Buyer, role Seller) { + +} + +aux global protocol Receipt(role Buyer, role Seller) { + +} diff --git a/scribble-parser/src/test/resources/scribble/examples/GProtocol.scr b/scribble-parser/src/test/resources/scribble/examples/GProtocol.scr new file mode 100644 index 000000000..8065d0916 --- /dev/null +++ b/scribble-parser/src/test/resources/scribble/examples/GProtocol.scr @@ -0,0 +1,16 @@ +module scribble.examples.GProtocol; + +global protocol GMessageTest(role Buyer, role SellerA, role SellerB) { + +} + +global protocol Order(role Buyer, role Seller) { + +} + +global protocol Receipt(role Buyer, role Seller) { + +} + +//global protocol GMessageTest2(role Buyer,role SellerA,role SellerB) instantiates GMessageTest(Buyer,SellerA,SellerB); + diff --git a/scribble-parser/src/test/resources/scribble/examples/GRecursion.scr b/scribble-parser/src/test/resources/scribble/examples/GRecursion.scr new file mode 100644 index 000000000..a4bef2011 --- /dev/null +++ b/scribble-parser/src/test/resources/scribble/examples/GRecursion.scr @@ -0,0 +1,10 @@ +module scribble.examples.GRecursion; + +type "{http://www.acme.com/financial}Order" from "http://www.acme.com/schemas/Order.xsd" as Order; + +global protocol GRecursionTest(role Buyer, role Seller) { + rec MyLabel { + buy(Order) from Buyer to Seller; + continue MyLabel; + } +} diff --git a/scribble-parser/src/test/resources/scribble/examples/Imports.scr b/scribble-parser/src/test/resources/scribble/examples/Imports.scr new file mode 100644 index 000000000..2e7f71069 --- /dev/null +++ b/scribble-parser/src/test/resources/scribble/examples/Imports.scr @@ -0,0 +1,9 @@ +module scribble.examples.Imports; + +import scribble.examples.GMessage; +//from scribble.examples.GMessage import PlaceOrder; +//from scribble.examples.GMessage import Receipt as OrderReceipt; + +global protocol ImportsTest(role Buyer, role Seller) { + +} diff --git a/scribble-parser/src/test/resources/scribble/examples/LChoice.scr b/scribble-parser/src/test/resources/scribble/examples/LChoice.scr new file mode 100644 index 000000000..8cce478d9 --- /dev/null +++ b/scribble-parser/src/test/resources/scribble/examples/LChoice.scr @@ -0,0 +1,12 @@ +module scribble.examples.LChoice; + +type "{http://www.acme.com/financial}Order" from "http://www.acme.com/schemas/Order.xsd" as Order; +type "{http://www.acme.com/financial}QuoteRequest" from "http://www.acme.com/schemas/QuoteRequest.xsd" as QuoteRequest; + +local protocol LChoiceTest(self Buyer, role Seller) { + choice at self { + buy(Order) to Seller; + } or { + buy(QuoteRequest) to Seller; + } +} diff --git a/scribble-parser/src/test/resources/scribble/examples/LDo.scr b/scribble-parser/src/test/resources/scribble/examples/LDo.scr new file mode 100644 index 000000000..e34624fa6 --- /dev/null +++ b/scribble-parser/src/test/resources/scribble/examples/LDo.scr @@ -0,0 +1,8 @@ +module scribble.examples.LDo; + +local protocol LDoTest(self Buyer, role Seller) { + do OtherProtocol(self, Seller); + do a.b.c.OtherProtocol(self, Seller); + do OtherProtocol(self, Seller); + do a.b.c.OtherProtocol(self, Seller); +} diff --git a/scribble-parser/src/test/resources/scribble/examples/LProtocol.scr b/scribble-parser/src/test/resources/scribble/examples/LProtocol.scr new file mode 100644 index 000000000..6bf92ed38 --- /dev/null +++ b/scribble-parser/src/test/resources/scribble/examples/LProtocol.scr @@ -0,0 +1,13 @@ +module scribble.examples.LProtocol; + +local protocol GMessageTest(role Buyer, role SellerA, role SellerB) { +} + +local protocol Order(role Buyer, self Seller) { +} + +local protocol Receipt(self Buyer, role Seller) { +} + +//local protocol GMessageTest2 at SellerB(role Buyer,role SellerA,role SellerB) instantiates GMessageTest(Buyer,SellerA,SellerB); + diff --git a/scribble-parser/src/test/resources/scribble/examples/LReceive_Seller.scr b/scribble-parser/src/test/resources/scribble/examples/LReceive_Seller.scr new file mode 100644 index 000000000..5c5533db6 --- /dev/null +++ b/scribble-parser/src/test/resources/scribble/examples/LReceive_Seller.scr @@ -0,0 +1,9 @@ +module scribble.examples.LReceive_Seller; + +type "{http://www.acme.com/financial}Order" from "http://www.acme.com/schemas/Order.xsd" as Order; +type "{http://www.acme.com/financial}Customer" from "http://www.acme.com/schemas/Customer.xsd" as Customer; + +local protocol LReceiveTest(role Buyer, self Seller) { + buy(Order, Customer) from Buyer; + buy(Order) from Buyer; +} diff --git a/scribble-parser/src/test/resources/scribble/examples/LRecursion.scr b/scribble-parser/src/test/resources/scribble/examples/LRecursion.scr new file mode 100644 index 000000000..dc15df9fa --- /dev/null +++ b/scribble-parser/src/test/resources/scribble/examples/LRecursion.scr @@ -0,0 +1,10 @@ +module scribble.examples.LRecursion; + +type "{http://www.acme.com/financial}Order" from "http://www.acme.com/schemas/Order.xsd" as Order; + +local protocol LRecursionTest(self Buyer, role Seller) { + rec MyLabel { + buy(Order) to Seller; + continue MyLabel; + } +} diff --git a/scribble-parser/src/test/resources/scribble/examples/LSend_Buyer.scr b/scribble-parser/src/test/resources/scribble/examples/LSend_Buyer.scr new file mode 100644 index 000000000..72fa7539d --- /dev/null +++ b/scribble-parser/src/test/resources/scribble/examples/LSend_Buyer.scr @@ -0,0 +1,9 @@ +module scribble.examples.LSend_Buyer; + +type "{http://www.acme.com/financial}Order" from "http://www.acme.com/schemas/Order.xsd" as Order; +type "{http://www.acme.com/financial}Customer" from "http://www.acme.com/schemas/Customer.xsd" as Customer; + +local protocol LSendTest(self Buyer, role Seller) { + buy(Order, Customer) to Seller; + buy(Order) to Seller; +} diff --git a/scribble-parser/src/test/resources/scribble/examples/Types.scr b/scribble-parser/src/test/resources/scribble/examples/Types.scr new file mode 100644 index 000000000..84284f42e --- /dev/null +++ b/scribble-parser/src/test/resources/scribble/examples/Types.scr @@ -0,0 +1,7 @@ +module scribble.examples.Types; + +type "{http://www.acme.com/financial}Trade" from "http://www.acme.com/schemas/Trade.xsd" as Trade; + +global protocol TestTypes(role Buyer, role Seller) { + +} diff --git a/scribble-parser/src/test/resources/scribble/issues/RTGOV406.scr b/scribble-parser/src/test/resources/scribble/issues/RTGOV406.scr new file mode 100644 index 000000000..9333491b3 --- /dev/null +++ b/scribble-parser/src/test/resources/scribble/issues/RTGOV406.scr @@ -0,0 +1,17 @@ +module scribble.issues.RTGOV406; + +type "java.lang.String" from "rt.jar" as String; +type "java.lang.Integer" from "rt.jar" as Int; + +global protocol ProtocolName(role Buyer1,role Buyer2,role Seller) { + book(String) from Buyer1 to Seller; + book(Int) from Seller to Buyer1; + quote(Int) from Buyer1 to Buyer2; + choice at Buyer2 { + agree() from Buyer2 to Buyer1,Seller; + transfer(Int) from Buyer1 to Seller; + transfer(Int) from Buyer2 to Seller; + } or { + quit() from Buyer2 to Buyer1,Seller; + } +} \ No newline at end of file diff --git a/scribble-runtime/pom.xml b/scribble-runtime/pom.xml new file mode 100644 index 000000000..c30f9cec7 --- /dev/null +++ b/scribble-runtime/pom.xml @@ -0,0 +1,26 @@ + + + 4.0.0 + + + scribble-runtime + + + + org.scribble + scribble-core + + + + + org.scribble + parent + 0.5.1-SNAPSHOT + ../pom.xml + + + + scribble-runtime + + diff --git a/scribble-runtime/src/main/java/org/scribble/main/ScribRuntimeException.java b/scribble-runtime/src/main/java/org/scribble/main/ScribRuntimeException.java new file mode 100644 index 000000000..6f7b1e75a --- /dev/null +++ b/scribble-runtime/src/main/java/org/scribble/main/ScribRuntimeException.java @@ -0,0 +1,31 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.main; + +// Note: not a run-time ScribbleException +// CHECKME: relocate? +public class ScribRuntimeException extends Exception +{ + private static final long serialVersionUID = 1L; + + public ScribRuntimeException(String s) + { + super(s); + } + + public ScribRuntimeException(Throwable t) + { + super(t); + } +} diff --git a/scribble-runtime/src/main/java/org/scribble/runtime/handlers/ScribBranch.java b/scribble-runtime/src/main/java/org/scribble/runtime/handlers/ScribBranch.java new file mode 100644 index 000000000..d88130b3d --- /dev/null +++ b/scribble-runtime/src/main/java/org/scribble/runtime/handlers/ScribBranch.java @@ -0,0 +1,22 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.runtime.handlers; + +import org.scribble.runtime.message.ScribMessage; + +// FIXME: integrate with BranchSocket and Handler I/f's +public interface ScribBranch +{ + public void dispatch(D data, ScribMessage m); +} diff --git a/scribble-runtime/src/main/java/org/scribble/runtime/handlers/ScribOutputEvent.java b/scribble-runtime/src/main/java/org/scribble/runtime/handlers/ScribOutputEvent.java new file mode 100644 index 000000000..db2228e9c --- /dev/null +++ b/scribble-runtime/src/main/java/org/scribble/runtime/handlers/ScribOutputEvent.java @@ -0,0 +1,26 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.runtime.handlers; + +import org.scribble.core.type.name.Op; +import org.scribble.core.type.name.Role; + +// FIXME: make interface and add to bounds of output icallback -- cf. CBEndpointApiGenerator +// FIXME: not serializable due to RoleKind (in Role) +public interface ScribOutputEvent +{ + Role getPeer(); + Op getOp(); + Object[] getPayload(); +} diff --git a/scribble-runtime/src/main/java/org/scribble/runtime/handlers/ScribSigMessage.java b/scribble-runtime/src/main/java/org/scribble/runtime/handlers/ScribSigMessage.java new file mode 100644 index 000000000..a71c55856 --- /dev/null +++ b/scribble-runtime/src/main/java/org/scribble/runtime/handlers/ScribSigMessage.java @@ -0,0 +1,21 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.runtime.handlers; + +import org.scribble.runtime.message.ScribMessage; + +public interface ScribSigMessage +{ + ScribMessage getSig(); +} diff --git a/scribble-runtime/src/main/java/org/scribble/runtime/handlers/states/ScribEndState.java b/scribble-runtime/src/main/java/org/scribble/runtime/handlers/states/ScribEndState.java new file mode 100644 index 000000000..5ba3b73e8 --- /dev/null +++ b/scribble-runtime/src/main/java/org/scribble/runtime/handlers/states/ScribEndState.java @@ -0,0 +1,30 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.runtime.handlers.states; + +abstract public class ScribEndState extends ScribState +{ + //public ScribEndState() + public ScribEndState(String name) + { + //super("End"); + super(name); + } + + @Override + protected boolean canEqual(Object o) + { + return o instanceof ScribEndState; + } +} diff --git a/scribble-runtime/src/main/java/org/scribble/runtime/handlers/states/ScribInputState.java b/scribble-runtime/src/main/java/org/scribble/runtime/handlers/states/ScribInputState.java new file mode 100644 index 000000000..82561cc76 --- /dev/null +++ b/scribble-runtime/src/main/java/org/scribble/runtime/handlers/states/ScribInputState.java @@ -0,0 +1,33 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.runtime.handlers.states; + +import org.scribble.core.type.name.Role; + +abstract public class ScribInputState extends ScribState +{ + public final Role peer; + + public ScribInputState(String name, Role peer) + { + super(name); + this.peer = peer; + } + + @Override + protected boolean canEqual(Object o) + { + return o instanceof ScribInputState; + } +} diff --git a/scribble-runtime/src/main/java/org/scribble/runtime/handlers/states/ScribOutputState.java b/scribble-runtime/src/main/java/org/scribble/runtime/handlers/states/ScribOutputState.java new file mode 100644 index 000000000..71db63699 --- /dev/null +++ b/scribble-runtime/src/main/java/org/scribble/runtime/handlers/states/ScribOutputState.java @@ -0,0 +1,28 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.runtime.handlers.states; + +abstract public class ScribOutputState extends ScribState +{ + public ScribOutputState(String name) + { + super(name); + } + + @Override + protected boolean canEqual(Object o) + { + return o instanceof ScribOutputState; + } +} diff --git a/scribble-runtime/src/main/java/org/scribble/runtime/handlers/states/ScribState.java b/scribble-runtime/src/main/java/org/scribble/runtime/handlers/states/ScribState.java new file mode 100644 index 000000000..29f3712be --- /dev/null +++ b/scribble-runtime/src/main/java/org/scribble/runtime/handlers/states/ScribState.java @@ -0,0 +1,63 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.runtime.handlers.states; + +import java.util.HashMap; +import java.util.Map; + +import org.scribble.core.type.name.Op; + +abstract public class ScribState +{ + public final String name; + + //public final Map succs = new HashMap<>(); // FIXME + public final Map succs = new HashMap<>(); + + public ScribState(String name) + { + this.name = name; + } + + @Override + public String toString() + { + return this.name; + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof ScribState)) + { + return false; + } + ScribState n = (ScribState) o; + return n.canEqual(this) && this.name.equals(n.name); + } + + protected abstract boolean canEqual(Object o); + + @Override + public int hashCode() + { + int hash = 7907; + hash = 31 * hash + this.name.hashCode(); + return hash; + } +} diff --git a/scribble-runtime/src/main/java/org/scribble/runtime/message/ObjectStreamFormatter.java b/scribble-runtime/src/main/java/org/scribble/runtime/message/ObjectStreamFormatter.java new file mode 100644 index 000000000..a5d661a60 --- /dev/null +++ b/scribble-runtime/src/main/java/org/scribble/runtime/message/ObjectStreamFormatter.java @@ -0,0 +1,110 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.runtime.message; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.io.ObjectInput; +import java.io.ObjectInputStream; +import java.io.ObjectOutput; +import java.io.ObjectOutputStream; +import java.nio.Buffer; +import java.nio.ByteBuffer; +import java.util.Arrays; + +public class ObjectStreamFormatter implements ScribMessageFormatter { + public ObjectStreamFormatter() { + + } + + @Override + //public byte[] toBytes(ScribMessage m) throws IOException + public void writeMessage(DataOutputStream dos, ScribMessage m) throws IOException { + throw new RuntimeException("Deprecated"); + /*byte[] bs = serialize(m); + dos.writeInt(bs.length); + dos.write(bs); + dos.flush();*/ + } + + @Override + public ScribMessage readMessage(DataInputStream dis) throws IOException { + throw new RuntimeException("Deprecated"); + /*try + { + int len = dis.readInt(); + byte[] bs = new byte[len]; + dis.readFully(bs); + return deserialize(bs); + } + catch (ClassNotFoundException cnfe) + { + throw new IOException(cnfe); + }*/ + } + + @Override + public byte[] toBytes(ScribMessage m) throws IOException { + byte[] body = serialize(m); + byte[] header = ByteBuffer.allocate(4).putInt(body.length).array(); // FIXME: buffer alloc + byte[] bs = new byte[header.length + body.length]; + System.arraycopy(header, 0, bs, 0, header.length); + System.arraycopy(body, 0, bs, 4, body.length); + return bs; + } + + @Override + public ScribMessage fromBytes(ByteBuffer bb) throws IOException, ClassNotFoundException { + // Pre: bb:put + ((Buffer) bb).flip(); // Cast HACK -- cf. https://stackoverflow.com/questions/61267495/exception-in-thread-main-java-lang-nosuchmethoderror-java-nio-bytebuffer-flip + if (bb.remaining() <= 4) { + bb.compact(); + return null; + } + byte[] header = Arrays.copyOf(bb.array(), 4); + int size = ByteBuffer.wrap(header).getInt(); + if (bb.remaining() < (4 + size)) { + bb.compact(); + return null; + } + // Cast HACK -- cf. https://stackoverflow.com/questions/61267495/exception-in-thread-main-java-lang-nosuchmethoderror-java-nio-bytebuffer-flip + bb.position(bb.position() + 4); // position is always 0 here? + //((Buffer) bb).position(((Buffer) bb).position() + 4); // position is always 0 here? + byte[] bs = new byte[size]; + bb.get(bs); + ScribMessage m = deserialize(bs); + bb.compact(); // Post: bb:put + return m; + } + + private static byte[] serialize(Object o) throws IOException { + try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) { + try (ObjectOutput out = new ObjectOutputStream(bos)) { + out.writeObject(o); + return bos.toByteArray(); + } + } + } + + private static ScribMessage deserialize(byte[] bs) throws IOException, ClassNotFoundException { + try (ByteArrayInputStream bis = new ByteArrayInputStream(bs)) { + try (ObjectInput in = new ObjectInputStream(bis)) { + return (ScribMessage) in.readObject(); + } + } + } +} diff --git a/scribble-runtime/src/main/java/org/scribble/runtime/message/ScribInterrupt.java b/scribble-runtime/src/main/java/org/scribble/runtime/message/ScribInterrupt.java new file mode 100644 index 000000000..eb0f4968d --- /dev/null +++ b/scribble-runtime/src/main/java/org/scribble/runtime/message/ScribInterrupt.java @@ -0,0 +1,41 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.runtime.message; + +import org.scribble.core.type.name.Op; + +public class ScribInterrupt extends ScribMessage +{ + private static final long serialVersionUID = 1L; + + public static final Op SCRIB_INTERR = new Op("__interr"); + + public ScribInterrupt(Throwable t) + { + super(SCRIB_INTERR, new Object[] { t }); + } + + @Override + public int hashCode() + { + int hash = 79; + hash = 31 * hash + super.hashCode(); + return hash; + } + + public boolean canEqual(Object o) + { + return o instanceof ScribInterrupt; + } +} diff --git a/scribble-runtime/src/main/java/org/scribble/runtime/message/ScribMessage.java b/scribble-runtime/src/main/java/org/scribble/runtime/message/ScribMessage.java new file mode 100644 index 000000000..11a07ad0d --- /dev/null +++ b/scribble-runtime/src/main/java/org/scribble/runtime/message/ScribMessage.java @@ -0,0 +1,98 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.runtime.message; + +import java.io.Serializable; +import java.util.Arrays; +import java.util.stream.Collectors; + +import org.scribble.core.type.name.Op; + +public class ScribMessage implements Serializable +{ + private static final long serialVersionUID = 1L; + + // add msg source + public final Op op; + public final Object[] payload; + + public ScribMessage(Op op, Object... payload) + { + this.op = op; + this.payload = payload; // FIXME: make defensive array copy? + } + + /*// Unicast + public MulticastSignature toMulticastSignature(Role src, Role dest, Scope scope) + { + return toMulticastSignature(src, Arrays.asList(dest), scope); + } + + public MulticastSignature toMulticastSignature(Role src, List dests, Scope scope) + { + return new MulticastSignature(src, dests, scope, op, getPayloadTypes()); + } + + protected final List getPayloadTypes() + { + List types = new LinkedList<>(); + for (Object o : this.payload) + { + // FIXME: routine should be plugin based on schema + types.add(new PayloadType(o.getClass().toString())); + } + return types; + }*/ + + @Override + public int hashCode() + { + int hash = 73; + //hash = 31 * hash + super.hashCode(); + hash = 31 * hash + this.op.hashCode(); + hash = 31 * hash + this.payload.hashCode(); + return hash; + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof ScribMessage)) + { + return false; + } + ScribMessage m = (ScribMessage) o; + return m.canEqual(this) && this.op.equals(m.op) && this.payload.equals(m.payload); + } + + public boolean canEqual(Object o) + { + return o instanceof ScribMessage; + } + + @Override + public String toString() + { + String s = this.op + "("; + if (this.payload.length > 0) + { + s += Arrays.asList(this.payload).stream().map((o) -> o.toString()).collect(Collectors.joining(", ")); + } + return s + ")"; + } +} diff --git a/scribble-runtime/src/main/java/org/scribble/runtime/message/ScribMessageFormatter.java b/scribble-runtime/src/main/java/org/scribble/runtime/message/ScribMessageFormatter.java new file mode 100644 index 000000000..b46249ace --- /dev/null +++ b/scribble-runtime/src/main/java/org/scribble/runtime/message/ScribMessageFormatter.java @@ -0,0 +1,34 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.runtime.message; + +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.nio.ByteBuffer; + +public interface ScribMessageFormatter +{ + //byte[] toBytes(ScribMessage m) throws IOException; + @Deprecated + void writeMessage(DataOutputStream dos, ScribMessage m) throws IOException; + @Deprecated + ScribMessage readMessage(DataInputStream dis) throws IOException; + + byte[] toBytes(ScribMessage m) throws IOException; + + // Pre and post: bb:put (maybe get would be more intuitive, but Buffers work better with put as default) + // Returns null if not enough data (FIXME?) + ScribMessage fromBytes(ByteBuffer bb) throws IOException, ClassNotFoundException; +} diff --git a/scribble-runtime/src/main/java/org/scribble/runtime/net/BinaryChannelEndpoint.java b/scribble-runtime/src/main/java/org/scribble/runtime/net/BinaryChannelEndpoint.java new file mode 100644 index 000000000..ae30dbba2 --- /dev/null +++ b/scribble-runtime/src/main/java/org/scribble/runtime/net/BinaryChannelEndpoint.java @@ -0,0 +1,215 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.runtime.net; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.channels.spi.AbstractSelectableChannel; +import java.util.LinkedList; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; + +import org.scribble.runtime.message.ScribInterrupt; +import org.scribble.runtime.message.ScribMessage; +import org.scribble.runtime.session.SessionEndpoint; +import org.scribble.util.RuntimeScribException; + +public abstract class BinaryChannelEndpoint +{ + //protected MPSTEndpoint se; + protected SessionEndpoint se; + + //protected BinaryChannelEndpoint parent; + private AbstractSelectableChannel c; + private ByteBuffer bb; + + //private final SocketChannel; + protected final List msgs = new LinkedList<>(); + + private boolean isClosed = false; + + private int count = 0; // How many ScribMessages read so far // volatile? + private int ticket = 0; // Index of the next expected ScribMessage + + private final List> pending = new LinkedList<>(); + + // Server side + //protected BinaryChannelEndpoint(MPSTEndpoint se, AbstractSelectableChannel c) throws IOException + protected BinaryChannelEndpoint(SessionEndpoint se, AbstractSelectableChannel c) throws IOException + { + this.bb = ByteBuffer.allocate(16921); // FIXME: size // Use put mode as default + init(se, c); + } + + // Client side + protected BinaryChannelEndpoint() + { + this.bb = ByteBuffer.allocate(16921); // FIXME: size // Use put mode as default + } + + //public abstract void initClient(MPSTEndpoint se, String host, int port) throws IOException; + public abstract void initClient(SessionEndpoint se, String host, int port) throws IOException; + + //protected void init(MPSTEndpoint se, AbstractSelectableChannel c) throws IOException + protected void init(SessionEndpoint se, AbstractSelectableChannel c) throws IOException + { + this.se = se; + this.c = c; + this.c.configureBlocking(false); + } + + // Pre: selector is paused + //protected BinaryChannelEndpoint(BinaryChannelEndpoint c) + public void wrapChannel(BinaryChannelEndpoint c) throws IOException + { + this.se = c.se; + //this.msgs.addAll(c.msgs); // Guaranteed to be empty/0 for reconnect? + //this.count = c.count; + //this.ticket = c.ticket; + //this.parent = c; + this.c = c.c; + this.bb = c.bb; + + //FIXME: complete all pending futures on parent chan -- no: not enough by itself, that is just reading the already-deserialized cache + //FIXME: pull all pending data out of parent chan (due to selector not handling it yet -- in send states, we just need to clear all expected messages up to this point) + // -- so that wrapper handshake is starting clean + // --- futures must be completed before here, since selector is paused + } + + public AbstractSelectableChannel getSelectableChannel() // For asynchrony (via nio Selector) -- maybe implement/extend instead + { + return this.c; + } + + public void write(ScribMessage m) throws IOException + { + writeBytes(this.se.smf.toBytes(m)); + } + + // Default CompletableFuture executed by common forkjoin pool -- so all messages that are received/async'd will eventually be pulled from the queue (no manual GC necessary) + public synchronized CompletableFuture getFuture() + { + // FIXME: better exception handling (integrate with Future interface?) + final int ticket = getTicket(); + CompletableFuture fut = CompletableFuture.supplyAsync(() -> + { + try + { + ScribMessage m = read(ticket); + if (m instanceof ScribInterrupt) // FIXME: hacked in + { + throw new RuntimeScribException((Throwable) ((ScribInterrupt) m).payload[0]); + } + return m; + } + catch(IOException e) + { + throw new RuntimeScribException(e); + } + finally + { + this.pending.remove(0); // Safe? + } + }); + synchronized (this.pending) + { + this.pending.add(fut); + } + return fut; + } + + public void sync() throws IOException // Hacky + { + try + { + synchronized (this.pending) + { + if (!this.pending.isEmpty()) + { + this.pending.get(this.pending.size() - 1).get(); + } + } + } + catch (InterruptedException | ExecutionException e) + { + throw new IOException(e); + } + } + + private synchronized ScribMessage read(int ticket) throws IOException + { + try + { + while (this.count < ticket && !this.isClosed) // "Chain" futures directly? i.e. each future syncs on predecessor? + { + wait(); + } + while (this.msgs.isEmpty() && !this.isClosed) + { + wait(); + } + if (this.isClosed) + { + throw new IOException("Channel closed"); + } + this.count++; + ScribMessage m = this.msgs.remove(0); + notifyAll(); // A later future might have gone first and blocked, so wake up (with the message already enqueued, so no notify coming from there) // finally? + return m; + } + catch (InterruptedException e) + { + throw new IOException(e); + } + } + + protected synchronized void enqueue(ScribMessage m) + { + this.msgs.add(m); + //this.count++; + notifyAll(); + } + + public abstract void writeBytes(byte[] bs) throws IOException; + protected abstract void readBytesIntoBuffer() throws IOException; // synchronized (against read) // bytes ready for reading: try to deserialize and then enqueue, or else cache for later + + public synchronized void readAndEnqueueMessages() throws ClassNotFoundException, IOException // Here for synchronisation + { + readBytesIntoBuffer(); + ScribMessage m; + while ((m = this.se.smf.fromBytes(this.bb)) != null) + { + enqueue(m); + } + } + + public synchronized void close() throws IOException + { + this.isClosed = true; + notifyAll(); + } + + public synchronized int getTicket() + { + //return ++this.ticket; + return this.ticket++; + } + + // post: bb:put + public ByteBuffer getBuffer() + { + return this.bb; + } +} diff --git a/scribble-runtime/src/main/java/org/scribble/runtime/net/BinaryChannelWrapper.java b/scribble-runtime/src/main/java/org/scribble/runtime/net/BinaryChannelWrapper.java new file mode 100644 index 000000000..ee63ed663 --- /dev/null +++ b/scribble-runtime/src/main/java/org/scribble/runtime/net/BinaryChannelWrapper.java @@ -0,0 +1,66 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.runtime.net; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.security.KeyManagementException; +import java.security.NoSuchAlgorithmException; + +import org.scribble.runtime.session.SessionEndpoint; + +public abstract class BinaryChannelWrapper extends BinaryChannelEndpoint +{ + // Use this in readUnwrappedBytesIntoBuffer (super.getBuffer used for read-but-still-wrapped -- decoded into here by unwrap) + private final ByteBuffer wrapped = ByteBuffer.allocate(16921); // FIXME: size // Use put mode as default + + protected BinaryChannelWrapper() + { + + } + + @Override + //public void initClient(MPSTEndpoint se, String host, int port) throws IOException + public void initClient(SessionEndpoint se, String host, int port) throws IOException + { + throw new RuntimeException("Shouldn't get in here: "); + } + + public abstract void clientHandshake() throws IOException, KeyManagementException, NoSuchAlgorithmException; // FIXME: name + public abstract void serverHandshake() throws IOException, KeyManagementException, NoSuchAlgorithmException; // FIXME: name + + public abstract byte[] wrap(byte[] bs) throws IOException; + public abstract void unwrap() throws IOException; // Decode from this.wrapped (this.getUnwrapped()) into this.bb + + protected abstract void writeWrappedBytes(byte[] bs) throws IOException; + protected abstract void readWrappedBytesIntoBuffer() throws IOException; // Read wrapped data into this.wrapped + + @Override + public void writeBytes(byte[] bs) throws IOException + { + writeWrappedBytes(wrap(bs)); + } + + @Override + protected void readBytesIntoBuffer() throws IOException + { + readWrappedBytesIntoBuffer(); + unwrap(); + } + + protected ByteBuffer getWrapped() + { + return this.wrapped; + } +} diff --git a/scribble-runtime/src/main/java/org/scribble/runtime/net/SSLSocketChannelServer.java b/scribble-runtime/src/main/java/org/scribble/runtime/net/SSLSocketChannelServer.java new file mode 100644 index 000000000..bb9d40870 --- /dev/null +++ b/scribble-runtime/src/main/java/org/scribble/runtime/net/SSLSocketChannelServer.java @@ -0,0 +1,54 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.runtime.net; + +import java.io.IOException; +import java.nio.channels.ServerSocketChannel; + +import org.scribble.runtime.session.SessionEndpoint; + +// FIXME: +public class SSLSocketChannelServer extends ScribServerSocket +{ + private ServerSocketChannel ss; + + public SSLSocketChannelServer(int port) throws IOException + { + super(port); + throw new RuntimeException("TODO"); + /*this.ss = ServerSocketChannel.open(); + this.ss.socket().bind(new InetSocketAddress(port));*/ + } + + @Override + //public synchronized SocketChannelEndpoint accept(MPSTEndpoint se) throws IOException + public synchronized SocketChannelEndpoint accept(SessionEndpoint se) throws IOException + { + return new SocketChannelEndpoint(se, ss.accept()); + } + + @Override + public void close() + { + try + { + this.ss.close(); + } + catch (IOException e) + { + // FIXME + e.printStackTrace(); + } + } +} diff --git a/scribble-runtime/src/main/java/org/scribble/runtime/net/SSLSocketChannelWrapper.java b/scribble-runtime/src/main/java/org/scribble/runtime/net/SSLSocketChannelWrapper.java new file mode 100644 index 000000000..78847bc7d --- /dev/null +++ b/scribble-runtime/src/main/java/org/scribble/runtime/net/SSLSocketChannelWrapper.java @@ -0,0 +1,279 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.runtime.net; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.ByteBuffer; +import java.nio.channels.SocketChannel; +import java.security.KeyManagementException; +import java.security.NoSuchAlgorithmException; + +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLEngine; +import javax.net.ssl.SSLEngineResult; +import javax.net.ssl.SSLException; +import javax.net.ssl.SSLSession; + +public class SSLSocketChannelWrapper extends BinaryChannelWrapper +{ + private SSLEngine engine; + + private ByteBuffer EMPTY = ByteBuffer.allocate(0); + + private ByteBuffer myAppData; + private ByteBuffer myNetData; + + //private ByteBuffer peerAppData = ByteBuffer.allocate(16916); // Hacked constant + //private ByteBuffer peerNetData; + + public SSLSocketChannelWrapper() + { + + } + + private void init(InetSocketAddress addr) throws NoSuchAlgorithmException, KeyManagementException + { + SSLContext sslContext = SSLContext.getInstance("TLS"); + sslContext.init(null, null, null); + this.engine = sslContext.createSSLEngine(addr.getHostName(), addr.getPort()); + } + + @Override + public void clientHandshake() throws IOException, KeyManagementException, NoSuchAlgorithmException + { + SocketChannel s = getSelectableChannel(); + init((InetSocketAddress) s.getRemoteAddress()); + this.engine.setUseClientMode(true); + SSLSession session = this.engine.getSession(); + this.myAppData = ByteBuffer.allocate(session.getApplicationBufferSize()); // 16916 + this.myNetData = ByteBuffer.allocate(session.getPacketBufferSize()); // 16921 + //this.peerAppData = ByteBuffer.allocate(16916); // Hacked constant + //this.peerNetData = ByteBuffer.allocate(session.getPacketBufferSize()); + doHandshake(s, this.engine, this.myNetData); + } + + @Override + public void serverHandshake() throws IOException, KeyManagementException, NoSuchAlgorithmException + { + SocketChannel s = getSelectableChannel(); + init((InetSocketAddress) s.getRemoteAddress()); + throw new RuntimeException("TODO"); + } + + @Override + public SocketChannel getSelectableChannel() + { + return (SocketChannel) super.getSelectableChannel(); + } + + @Override + protected void writeWrappedBytes(byte[] bs) throws IOException + { + getSelectableChannel().write(ByteBuffer.wrap(bs)); + } + + @Override + protected void readWrappedBytesIntoBuffer() throws IOException + { + ByteBuffer bb = getWrapped(); + getSelectableChannel().read(bb); + } + + @Override + public byte[] wrap(byte[] bs) throws IOException + { + this.myAppData.put(bs); + this.myAppData.flip(); + this.myNetData.clear(); + while (this.myAppData.hasRemaining()) + { + SSLEngineResult res = this.engine.wrap(this.myAppData, this.myNetData); + if (res.getStatus() == SSLEngineResult.Status.OK) + { + this.myAppData.compact(); + this.myAppData.flip(); + } + else + { + // Handle other status: BUFFER_OVERFLOW (write some first), BUFFER_UNDERFLOW, CLOSED + throw new RuntimeException("TODO: " + res.getStatus()); + } + } + this.myAppData.compact(); // Should be same as clear here (i.e. empty) + this.myNetData.flip(); + byte[] res = new byte[this.myNetData.remaining()]; + System.arraycopy(this.myNetData.array(), this.myNetData.position(), res, 0, res.length); + return res; + } + + // Decode from this.wrapped (this.getUnwrapped()) into this.bb + @Override + public void unwrap() throws IOException // Decode from this.wrapped (this.getUnwrapped()) into this.bb + { + ByteBuffer peerNetData = getWrapped(); + ByteBuffer peerAppData = getBuffer(); + //for (boolean done = false; !done; ) + { + //s.read(peerNetData); // Assumes there is something to read (or else blocked) + peerNetData.flip(); + SSLEngineResult res = this.engine.unwrap(peerNetData, peerAppData); + peerNetData.compact(); + if (res.getStatus() == SSLEngineResult.Status.OK) + { + //done = true; + } + else if (res.getStatus() == SSLEngineResult.Status.BUFFER_UNDERFLOW) + { + //peerNetData.flip(); + //return; + } + + else if (res.getStatus() == SSLEngineResult.Status.CLOSED) + { + // FIXME: check if closed is OK or not (if not, throw exception) + } + + else + { + // Handle other status: BUFFER_OVERFLOW + throw new RuntimeException("TODO: " + res.getStatus()); + } + } + } + + private void doHandshake(SocketChannel s, SSLEngine engine, ByteBuffer myNetData) throws IOException + { + ByteBuffer peerNetData = ByteBuffer.allocate(engine.getSession().getPacketBufferSize()); + ByteBuffer peerAppData = ByteBuffer.allocate(engine.getSession().getApplicationBufferSize()); + + engine.beginHandshake(); // Not explicitly needed for initial handshake + + SSLEngineResult.HandshakeStatus hs = engine.getHandshakeStatus(); + while (hs != SSLEngineResult.HandshakeStatus.FINISHED && hs != SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING) + { + switch (hs) + { + case NEED_UNWRAP: + { + for (boolean done = false; !done; ) + { + peerNetData.flip(); + SSLEngineResult res = engine.unwrap(peerNetData, peerAppData); + peerNetData.compact(); + + hs = res.getHandshakeStatus(); + switch (res.getStatus()) + { + case OK: + { + done = true; + break; + } + case BUFFER_UNDERFLOW: + { + if (s.read(peerNetData) < 0) + { + throw new RuntimeException("TODO: "); + } + break; + } + default: + { + // Handle other status: BUFFER_OVERFLOW, CLOSED + throw new RuntimeException("TODO: " + res.getStatus()); + } + } + } + break; + } + case NEED_WRAP: + { + myNetData.clear(); + SSLEngineResult res = engine.wrap(EMPTY, myNetData); + + hs = res.getHandshakeStatus(); + switch (res.getStatus()) + { + case OK: + { + myNetData.flip(); + while (myNetData.hasRemaining()) + { + if (s.write(myNetData) < 0) + { + throw new RuntimeException("TODO: "); + } + } + myNetData.compact(); + break; + } + default: + { + // Handle other status: BUFFER_OVERFLOW (write some first to free up space), BUFFER_UNDERFLOW, CLOSED + throw new RuntimeException("TODO: " + hs); + } + } + break; + } + case NEED_TASK: + { + engine.getDelegatedTask().run(); + hs = engine.getHandshakeStatus(); + break; + } + default: + { + // Handle other status: // FINISHED or NOT_HANDSHAKING + throw new RuntimeException("TODO: " + hs); + } + } + } + } + + private void doShutdown() throws SSLException, IOException + { + SocketChannel s = getSelectableChannel(); + this.engine.closeOutbound(); + myNetData.clear(); + while (!this.engine.isOutboundDone()) + { + SSLEngineResult res = this.engine.wrap(EMPTY, myNetData); + if (res.getStatus() != SSLEngineResult.Status.CLOSED) // FIXME: is this the correct state to check for? or OK? (or both) + { + throw new RuntimeException("TODO: " + res.getStatus()); + } + this.myNetData.flip(); + while (this.myNetData.hasRemaining()) + { + int num1 = s.write(this.myNetData); + if (num1 == -1) + { + throw new RuntimeException("TODO: "); + } + this.myNetData.compact(); + this.myNetData.flip(); + } + } + + //s1.close(); + } + + @Override + public synchronized void close() throws IOException + { + doShutdown(); + super.close(); + } +} diff --git a/scribble-runtime/src/main/java/org/scribble/runtime/net/ScribServerSocket.java b/scribble-runtime/src/main/java/org/scribble/runtime/net/ScribServerSocket.java new file mode 100644 index 000000000..1cf3879f5 --- /dev/null +++ b/scribble-runtime/src/main/java/org/scribble/runtime/net/ScribServerSocket.java @@ -0,0 +1,51 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.runtime.net; + +import java.io.IOException; + +import org.scribble.main.ScribRuntimeException; +import org.scribble.runtime.session.SessionEndpoint; + +public abstract class ScribServerSocket implements AutoCloseable +{ + public final int port; + + private boolean reg = false; + + public ScribServerSocket(int port) throws IOException + { + this.port = port; + } + + //public abstract BinaryChannelEndpoint accept(MPSTEndpoint se) throws IOException; // synchronize + public abstract BinaryChannelEndpoint accept(SessionEndpoint se) throws IOException; // synchronize + + public synchronized void bind() throws ScribRuntimeException + { + if (this.reg) + { + throw new ScribRuntimeException("Server socket already registered."); + } + this.reg = true; + } + + public synchronized void unbind() + { + this.reg = false; + } + + @Override + public abstract void close(); +} diff --git a/scribble-runtime/src/main/java/org/scribble/runtime/net/SocketChannelEndpoint.java b/scribble-runtime/src/main/java/org/scribble/runtime/net/SocketChannelEndpoint.java new file mode 100644 index 000000000..6b8eac311 --- /dev/null +++ b/scribble-runtime/src/main/java/org/scribble/runtime/net/SocketChannelEndpoint.java @@ -0,0 +1,91 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.runtime.net; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.ByteBuffer; +import java.nio.channels.SocketChannel; + +import org.scribble.runtime.session.SessionEndpoint; + +public class SocketChannelEndpoint extends BinaryChannelEndpoint +{ + //private final SocketChannel s; + + //private final ByteBuffer bb = ByteBuffer.allocate(16921); // FIXME: size + + // Server side + //public SocketChannelEndpoint(MPSTEndpoint se, SocketChannel s) throws IOException + public SocketChannelEndpoint(SessionEndpoint se, SocketChannel s) throws IOException + { + super(se, s); + } + + // Client side + public SocketChannelEndpoint() + { + + } + + @Override + //public void initClient(MPSTEndpoint se, String host, int port) throws IOException + public void initClient(SessionEndpoint se, String host, int port) throws IOException + { + SocketChannel s = SocketChannel.open(new InetSocketAddress(host, port)); + super.init(se, s); + } + + @Override + public SocketChannel getSelectableChannel() + { + return (SocketChannel) super.getSelectableChannel(); + } + + public void writeBytes(byte[] bs) throws IOException + { + getSelectableChannel().write(ByteBuffer.wrap(bs)); // Currently does not depend on SocketChannel + // flush not supported -- async: manually check if written yet if needed + } + + @Override + public synchronized void readBytesIntoBuffer() throws IOException + { + /*getSelectableChannel().read(this.bb); // Pre: bb:put + // FIXME: what if bb is full? + ScribMessage m = this.se.smf.fromBytes(this.bb); // Post: bb:put + if (m != null) + { + enqueue(m); + }*/ + ByteBuffer bb = (ByteBuffer) getBuffer(); + getSelectableChannel().read(bb); // Currently does not depend on SocketChannel + //bb.compact(); // Post: bb:put + } + + @Override + public void close() + { + try + { + super.close(); + getSelectableChannel().close(); + } + catch (IOException e) + { + // FIXME: (BinaryChannelEndpoint read will throw exception) + e.printStackTrace(); + } + } +} diff --git a/scribble-runtime/src/main/java/org/scribble/runtime/net/SocketChannelServer.java b/scribble-runtime/src/main/java/org/scribble/runtime/net/SocketChannelServer.java new file mode 100644 index 000000000..d301be0ce --- /dev/null +++ b/scribble-runtime/src/main/java/org/scribble/runtime/net/SocketChannelServer.java @@ -0,0 +1,53 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.runtime.net; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.channels.ServerSocketChannel; + +import org.scribble.runtime.session.SessionEndpoint; + +public class SocketChannelServer extends ScribServerSocket +{ + private ServerSocketChannel ss; + + public SocketChannelServer(int port) throws IOException + { + super(port); + this.ss = ServerSocketChannel.open(); + this.ss.socket().bind(new InetSocketAddress(port)); + } + + @Override + //public synchronized SocketChannelEndpoint accept(MPSTEndpoint se) throws IOException + public synchronized SocketChannelEndpoint accept(SessionEndpoint se) throws IOException + { + return new SocketChannelEndpoint(se, this.ss.accept()); + } + + @Override + public void close() + { + try + { + this.ss.close(); + } + catch (IOException e) + { + // FIXME + e.printStackTrace(); + } + } +} diff --git a/scribble-runtime/src/main/java/org/scribble/runtime/net/SocketEndpoint.java b/scribble-runtime/src/main/java/org/scribble/runtime/net/SocketEndpoint.java new file mode 100644 index 000000000..34f210b9c --- /dev/null +++ b/scribble-runtime/src/main/java/org/scribble/runtime/net/SocketEndpoint.java @@ -0,0 +1,140 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.runtime.net; + +import java.io.DataInputStream; +import java.io.IOException; + +import org.scribble.core.type.name.Role; +import org.scribble.runtime.message.ScribMessage; +import org.scribble.runtime.session.MPSTEndpoint; + +// Read/write Objects on the binary connection to an endpoint in the session +@Deprecated +public class SocketEndpoint +{ + private final MPSTEndpoint ep; + //private final Role peer; + private final SocketWrapper sw; + + public SocketWrapper getSocketWrapper() + { + return this.sw; + } + + private final ReceiverThread receiver; + + public SocketEndpoint(MPSTEndpoint ep, Role peer, SocketWrapper sw) //throws IOException + { + this.ep = ep; + //this.peer = peer; + this.sw = sw; + + this.receiver = new ReceiverThread(ep, peer, sw.dis); + this.receiver.start(); + } + + /*// For SelfSocketEndpoint only + protected SocketEndpoint(Role src, SessionInputQueue inputq) + { + this.src = src; + this.inputq = inputq; + this.sw = null; + this.recthread = null; + }*/ + + public void writeMessage(ScribMessage msg) throws IOException + { + this.ep.smf.writeMessage(this.sw.dos, msg); + } + + public void flush() throws IOException + { + this.sw.dos.flush(); + } + + public void writeMessageAndFlush(ScribMessage msg) throws IOException + { + writeMessage(msg); + flush(); + } + + public void close() throws IOException + { + this.sw.close(); + } + + @Override + public String toString() + { + return this.sw.sock.getInetAddress().toString() + ":" + this.sw.sock.getPort(); + } +} + +// Could move to EndpointInputQueues +class ReceiverThread extends Thread +{ + /*private final MPSTEndpoint ep; + private final Role peer; + private final DataInputStream dis; + + private Throwable fail;*/ + + public ReceiverThread(MPSTEndpoint ep, Role peer, DataInputStream dis) + { + /*this.ep = ep; + this.peer = peer; + this.dis = dis;*/ + + //ep.getInputQueues().register(peer); + } + + public void run() + { + /*EndpointInputQueues queues = null;//this.ep.getInputQueues(); + try + { + while (true) + { + ScribMessage m = this.ep.smf.readMessage(this.dis); + queues.enqueue(this.peer, m); // FIXME: bounded buffer? (endpoint queue property?) + } + } + catch (IOException e) + { + this.fail = e; + } + finally + { + try + { + dis.close(); // Maybe just rely on main SocketEndpoint.close + } + catch (IOException e) + { + if (this.fail == null) + { + this.fail = e; + } + } + finally + { + if (this.fail != null) + { + queues.interrupt(this.peer, this.fail); + } + } + }*/ + } +} diff --git a/scribble-runtime/src/main/java/org/scribble/runtime/net/SocketWrapper.java b/scribble-runtime/src/main/java/org/scribble/runtime/net/SocketWrapper.java new file mode 100644 index 000000000..e53b92176 --- /dev/null +++ b/scribble-runtime/src/main/java/org/scribble/runtime/net/SocketWrapper.java @@ -0,0 +1,59 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.runtime.net; + +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.net.Socket; + +// FIXME: should be IO wrapper: should abstract sockets, shared memory, RMI, AMQP, etc etc +@Deprecated +public class SocketWrapper +{ + protected final Socket sock; + protected final DataOutputStream dos; + protected final DataInputStream dis; + + public SocketWrapper(Socket s) throws IOException + { + this.sock = s; + this.dos = new DataOutputStream(s.getOutputStream()); + this.dis = new DataInputStream(s.getInputStream()); + } + + public void close() throws IOException + { + try + { + this.dis.close(); + } + finally + { + try + { + this.dos.close(); + } + finally + { + this.sock.close(); + } + } + } + + public Socket getSocket() + { + return this.sock; + } +} diff --git a/scribble-runtime/src/main/java/org/scribble/runtime/session/CBEndpoint.java b/scribble-runtime/src/main/java/org/scribble/runtime/session/CBEndpoint.java new file mode 100644 index 000000000..fab986022 --- /dev/null +++ b/scribble-runtime/src/main/java/org/scribble/runtime/session/CBEndpoint.java @@ -0,0 +1,187 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.runtime.session; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.function.Function; + +import org.scribble.core.type.name.Role; +import org.scribble.main.ScribRuntimeException; +import org.scribble.runtime.handlers.ScribBranch; +import org.scribble.runtime.handlers.ScribOutputEvent; +import org.scribble.runtime.handlers.ScribSigMessage; +import org.scribble.runtime.handlers.states.ScribEndState; +import org.scribble.runtime.handlers.states.ScribInputState; +import org.scribble.runtime.handlers.states.ScribOutputState; +import org.scribble.runtime.handlers.states.ScribState; +import org.scribble.runtime.message.ScribMessage; +import org.scribble.runtime.message.ScribMessageFormatter; + +public class CBEndpoint extends MPSTEndpoint +{ + protected final ScribState init; + protected final Map> outputs = new HashMap<>(); + protected final Map> inputs = new HashMap<>(); + + protected final D data; + + protected final Map states = new HashMap<>(); // Bypass problem of mutual references and static field initialisation (class loading) + + public CBEndpoint(S sess, R self, ScribMessageFormatter smf, ScribState init, D data) throws IOException, ScribRuntimeException + { + super(sess, self, smf); + this.init = init; + this.data = data; + } + + public Future run() throws ScribRuntimeException + { + Object[] res = new Object[1]; + + // FIXME: integrate with selector (or make Executor) + new Thread() + { + private final CBEndpoint edep; + + { + this.edep = CBEndpoint.this; + } + + public void run() + { + try + { + ScribState curr = this.edep.init; + while (!(curr instanceof ScribEndState)) + { + if (curr instanceof ScribOutputState) + { + // FIXME: make ScribOutputEvent an interface and add to bounds of output icallback (to preclude dynamic cast check) -- also make generated ..._Message an interface + ScribOutputEvent m = (ScribOutputEvent) this.edep.outputs.get(curr).apply(this.edep.data); // FIXME: state object + /*getChannelEndpoint(m.getPeer()).write(new ScribMessage(m.getOp(), m.getPayload().toArray(new Object[0]))); // FIXME: ScribEvent has extra Role + curr = this.edep.states.get(((ScribOutputState) curr).succs.get(m.getOp()));*/ + if (m instanceof ScribSigMessage) + { + getChannelEndpoint(m.getPeer()).write(((ScribSigMessage) m).getSig()); + } + else + { + getChannelEndpoint(m.getPeer()).write(new ScribMessage(m.getOp(), m.getPayload())); // API gen extends ScribMessage, but no guarantee about user-defined types -- can only rely on ScribOutputEvent i/f + } + curr = this.edep.states.get(((ScribOutputState) curr).succs.get(m.getOp())); + } + else if (curr instanceof ScribInputState) + { + try // cf. ReceiveSocket#readScribMessage + { + ScribMessage m = getChannelEndpoint(((ScribInputState) curr).peer).getFuture().get(); + this.edep.inputs.get(curr).dispatch(this.edep.data, m); + curr = this.edep.states.get(((ScribInputState) curr).succs.get(m.op)); + } + catch (InterruptedException e) + { + //throw new IOException(e); + res[0] = new IOException(e); + break; + } + catch (ExecutionException e) + { + //throw new IOException(e); + res[0] = new IOException(e); + break; + } + } + else + { + throw new RuntimeException("Shouldn't get in here: " + curr); + } + } + } + catch (IOException e) + { + res[0] = e; + } + + if (res[0] == null) + { + res[0] = 0; + } + synchronized(res) + { + res.notify(); + } + setCompleted(); + } + }.start(); + + return new EventDrivenEndpointFuture(res); + } +} + +class EventDrivenEndpointFuture implements Future +{ + private final Object[] res; + + protected EventDrivenEndpointFuture(Object[] res) + { + this.res = res; + } + + @Override + public boolean cancel(boolean mayInterruptIfRunning) + { + throw new RuntimeException("TODO"); + } + + @Override + public Void get() throws InterruptedException, ExecutionException + { + while (this.res[0] == null) + { + synchronized (this.res) + { + this.res.wait(); + } + } + if (this.res[0] instanceof IOException) + { + throw new ExecutionException((IOException) this.res[0]); + } + return null; + } + + @Override + public Void get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException + { + throw new RuntimeException("TODO"); + } + + @Override + public boolean isCancelled() + { + throw new RuntimeException("TODO"); + } + + @Override + public boolean isDone() + { + return this.res[0] != null; + } +} \ No newline at end of file diff --git a/scribble-runtime/src/main/java/org/scribble/runtime/session/EndpointInputQueues.java b/scribble-runtime/src/main/java/org/scribble/runtime/session/EndpointInputQueues.java new file mode 100644 index 000000000..aef3dcfa0 --- /dev/null +++ b/scribble-runtime/src/main/java/org/scribble/runtime/session/EndpointInputQueues.java @@ -0,0 +1,179 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.runtime.session; + +import java.io.IOException; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CompletableFuture; + +import org.scribble.core.type.name.Role; +import org.scribble.runtime.message.ScribInterrupt; +import org.scribble.runtime.message.ScribMessage; +import org.scribble.util.RuntimeScribException; + +@Deprecated +public class EndpointInputQueues +{ + // FIXME: factor out individual role queues (with counts and tickets, and bounded cache size?) + + private final Map> queues = new HashMap<>(); + //private final List list = new LinkedList<>(); + + private final Map counts = new HashMap<>(); // How many ScribMessages read so far + private final Map tickets = new HashMap<>(); // Index of the next expected ScribMessage + + public EndpointInputQueues() + { + + } + + public synchronized int getTicket(Role peer) + { + int next = this.tickets.get(peer) + 1; + this.tickets.put(peer, next); + return next; + } + + public synchronized void register(Role peer) + { + this.queues.put(peer, new LinkedList<>()); + this.counts.put(peer, 0); + this.tickets.put(peer, 0); + } + + public synchronized void enqueue(Role peer, ScribMessage o) + { + this.queues.get(peer).add(o); + //this.list.add(o); + this.counts.put(peer, this.counts.get(peer) + 1); + notifyAll(); // FIXME: notify just for each peer + } + + public synchronized void interrupt(Role peer, Throwable t) + { + enqueue(peer, new ScribInterrupt(t)); + } + + public synchronized boolean isEmpty(Role peer) + { + return this.queues.get(peer).isEmpty(); + } + + /*public synchronized Object peek(Role src) + { + return this.queues.get(src).get(0); + }*/ + + // Default CompletableFuture executed by common forkjoin pool -- so all messages that are received/async'd will eventually be pulled from the queue (no manual GC necessary) + public synchronized CompletableFuture getFuture(Role peer) + { + // FIXME: better exception handling (integrate with Future interface?) + return CompletableFuture.supplyAsync(() -> + { + try + { + ScribMessage m = dequeue(peer, getTicket(peer)); + if (m instanceof ScribInterrupt) // FIXME: hacked in + { + throw new RuntimeScribException((Throwable) ((ScribInterrupt) m).payload[0]); + } + return m; + } + catch(IOException e) + { + throw new RuntimeScribException(e); + } + }); + } + + protected synchronized ScribMessage dequeue(Role peer, int ticket) throws IOException + { + try + { + while (this.counts.get(peer) < ticket) + { + wait(); + } + List queue = this.queues.get(peer); + while (queue.isEmpty()) + { + wait(); + } + ScribMessage m = queue.remove(0); + //this.list.remove(o); + return m; + } + catch (InterruptedException e) + { + throw new IOException(e); + } + } + + /*public boolean isEmpty() + { + return this.list.isEmpty(); + }*/ + + /*public Object dequeue() + { + Object o = this.list.remove(0); + for (List os : this.global.values()) + { + if (os.contains(o)) + { + os.remove(o); + break; + } + } + return o; + }*/ + + /*// Synchronized against usage in SocketEndpoint + public synchronized Object readObject() throws IOException + { + synchronized (this) + { + while (isEmpty()) + { + try + { + this.wait(); + } + catch (InterruptedException e) + { + throw new IOException(e); + } + } + return dequeue(); + } + }*/ + + /*public ScribbleInterrupt checkForInterrupt() + { + synchronized (this) + { + for (List queue : this.global.values()) + { + if (!queue.isEmpty() && (queue.get(0) instanceof ScribbleInterrupt)) + { + return (ScribbleInterrupt) queue.remove(0); + } + } + } + return null; + }*/ +} diff --git a/scribble-runtime/src/main/java/org/scribble/runtime/session/ExplicitEndpoint.java b/scribble-runtime/src/main/java/org/scribble/runtime/session/ExplicitEndpoint.java new file mode 100644 index 000000000..ba353a2b3 --- /dev/null +++ b/scribble-runtime/src/main/java/org/scribble/runtime/session/ExplicitEndpoint.java @@ -0,0 +1,38 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.runtime.session; + +import java.io.IOException; + +import org.scribble.core.type.name.Role; +import org.scribble.main.ScribRuntimeException; +import org.scribble.runtime.message.ScribMessageFormatter; + +public class ExplicitEndpoint extends SessionEndpoint +{ + public ExplicitEndpoint(S sess, R self, ScribMessageFormatter smf) throws IOException, ScribRuntimeException + { + super(sess, self, smf); + } + + // FIXME HACK: "init" really only for MPSTEndpoint? Then refactor into there only + @Override + public void init() throws ScribRuntimeException + { + if (this.init) + { + throw new ScribRuntimeException("Session endpoint already initialised."); + } + } +} diff --git a/scribble-runtime/src/main/java/org/scribble/runtime/session/MPSTEndpoint.java b/scribble-runtime/src/main/java/org/scribble/runtime/session/MPSTEndpoint.java new file mode 100644 index 000000000..709e51813 --- /dev/null +++ b/scribble-runtime/src/main/java/org/scribble/runtime/session/MPSTEndpoint.java @@ -0,0 +1,111 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.runtime.session; + +import java.io.IOException; +import java.net.UnknownHostException; +import java.util.concurrent.Callable; + +import org.scribble.core.type.name.Role; +import org.scribble.main.ScribRuntimeException; +import org.scribble.runtime.message.ScribMessageFormatter; +import org.scribble.runtime.net.BinaryChannelEndpoint; +import org.scribble.runtime.net.ScribServerSocket; + +// FIXME: factor out between role-endpoint based socket and channel-endpoint sockets +//.. initiator and joiner endpoints +public class MPSTEndpoint extends SessionEndpoint +{ + public MPSTEndpoint(S sess, R self, ScribMessageFormatter smf) throws IOException, ScribRuntimeException + { + super(sess, self, smf); + } + + public void request(Role role, Callable cons, String host, int port) throws ScribRuntimeException, UnknownHostException, IOException + { + MPSTEndpoint.request(this, role, cons, host, port); + } + + // HACK FIXME: refactor (location, protected, etc) + public static void request(SessionEndpoint se, Role role, Callable cons, String host, int port) throws ScribRuntimeException, UnknownHostException, IOException + { + // Can connect unlimited, as long as not already used via init + //if (this.init) + if (se.init) + { + //throw new ScribbleRuntimeException("Socket already initialised: " + this.getClass()); + throw new ScribRuntimeException("Socket already initialised: " + se.getClass()); + } + //if (this.chans.containsKey(role)) + if (se.chans.containsKey(role)) + { + throw new ScribRuntimeException("Already connected to: " + role); + } + try + { + BinaryChannelEndpoint c = cons.call(); + /*c.initClient(this, host, port); + register(role, c);*/ + c.initClient(se, host, port); + se.register(role, c); + } + catch (Exception e) + { + if (e instanceof IOException) + { + throw (IOException) e; + } + throw new IOException(e); + } + } + + public void accept(ScribServerSocket ss, Role role) throws IOException, ScribRuntimeException + { + accept(this, ss, role); + } + + //public static void accept(SessionEndpoint se, ScribServerSocket ss, Role role) throws IOException, ScribbleRuntimeException + public static void accept(SessionEndpoint se, ScribServerSocket ss, Role role) throws IOException, ScribRuntimeException + { + //if (this.init) + if (se.init) + { + //throw new ScribbleRuntimeException("Socket already initialised: " + this.getClass()); + throw new ScribRuntimeException("Socket already initialised: " + se.getClass()); + } + //if (this.chans.containsKey(role)) + if (se.chans.containsKey(role)) + { + throw new ScribRuntimeException("Already connected to: " + role); + } + //register(role, ss.accept(this)); // FIXME: serv map in SessionEndpoint not currently used + se.register(role, ss.accept(se)); // FIXME: serv map in SessionEndpoint not currently used + } + + public void disconnect(Role role) throws IOException, ScribRuntimeException + { + MPSTEndpoint.disconnect(this, role); + } + + public static void disconnect(SessionEndpoint se, Role role) throws IOException, ScribRuntimeException + { + //if (!this.chans.containsKey(role)) + if (!se.chans.containsKey(role)) + { + throw new ScribRuntimeException("Not connected to: " + role); + } + //deregister(role); + se.deregister(role); + } +} diff --git a/scribble-runtime/src/main/java/org/scribble/runtime/session/OpEnum.java b/scribble-runtime/src/main/java/org/scribble/runtime/session/OpEnum.java new file mode 100644 index 000000000..64419db70 --- /dev/null +++ b/scribble-runtime/src/main/java/org/scribble/runtime/session/OpEnum.java @@ -0,0 +1,19 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.runtime.session; + +public interface OpEnum +{ + +} diff --git a/scribble-runtime/src/main/java/org/scribble/runtime/session/Principal.java b/scribble-runtime/src/main/java/org/scribble/runtime/session/Principal.java new file mode 100644 index 000000000..0f9d52675 --- /dev/null +++ b/scribble-runtime/src/main/java/org/scribble/runtime/session/Principal.java @@ -0,0 +1,67 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.runtime.session; + +import java.io.Serializable; + +import org.scribble.core.type.name.Role; + +@Deprecated +public class Principal implements Serializable +{ + private static final long serialVersionUID = 1L; + + public final Role role; + /*public final String host; + public final int port; // The "session port"*/ + + public Principal(Role role)//, String host, int port) + { + this.role = role; + //this.host = host; + //this.port = port; + } + + @Override + public int hashCode() + { + int hash = 859; + hash = 31 * hash + this.role.hashCode(); + //hash = 31 * hash + this.host.hashCode(); + //hash = 31 * hash + this.port; + return hash; + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof Principal)) + { + return false; + } + Principal p = (Principal) o; + return this.role.equals(p.role);//this.host.equals(p.host) && this.port == p.port; + } + + @Override + public String toString() + { + //return this.role + "@" + this.host + ":" + this.port; + return this.role.toString(); + } +} diff --git a/scribble-runtime/src/main/java/org/scribble/runtime/session/ScribInputSelector.java b/scribble-runtime/src/main/java/org/scribble/runtime/session/ScribInputSelector.java new file mode 100644 index 000000000..5041da9e9 --- /dev/null +++ b/scribble-runtime/src/main/java/org/scribble/runtime/session/ScribInputSelector.java @@ -0,0 +1,154 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.runtime.session; + +import java.io.IOException; +import java.nio.channels.ClosedChannelException; +import java.nio.channels.SelectionKey; +import java.nio.channels.Selector; +import java.nio.channels.spi.AbstractSelectableChannel; +import java.util.Set; + +import org.scribble.core.type.name.Role; +import org.scribble.runtime.net.BinaryChannelEndpoint; + +public class ScribInputSelector extends Thread +{ + //private MPSTEndpoint se; // FIXME + private SessionEndpoint se; // FIXME + private final Selector sel; + + private volatile boolean paused = false; + private volatile boolean closed = false; + + //public ScribInputSelector(MPSTEndpoint se) throws IOException + public ScribInputSelector(SessionEndpoint se) throws IOException + { + this.se = se; + this.sel = Selector.open(); + } + + @Override + public void run() + { + try + { + //waitForInit(); + //..FIXME: reg serversocketchannel with sel -- midsession reg needs wakeup and re-select? + //..here: do java smtp version using nio + + while (!this.closed) + { + this.sel.select(); + if (this.closed) + { + return; + } + synchronized (this) // sync'd with pause, unpause + { + while (paused) + { + wait(); + } + + Set keys = this.sel.selectedKeys(); + for (SelectionKey key : keys) + { + //SocketChannel s = (SocketChannel) key.channel(); + if (key.isReadable()) + { + Role peer = (Role) key.attachment(); + this.se.chans.get(peer).readAndEnqueueMessages(); // Read as many message as possible as selector only woken up by actual I/O + } + else + { + throw new RuntimeException("TODO: " + key); + } + } + } + } + } + catch (Exception e) + { + // FIXME: throw to user -- e.g. MessageFormatter.fromBytes exception + e.printStackTrace(); // FIXME? java.nio.channels.CancelledKeyException + } + finally + { + try + { + this.sel.close(); + } + catch (IOException e) + { + // FIXME + e.printStackTrace(); + } + } + } + + protected Selector getSelector() + { + return this.sel; + } + + // synchronize? + protected SelectionKey register(AbstractSelectableChannel c) throws ClosedChannelException + { + return c.register(this.sel, SelectionKey.OP_READ); + } + + protected void deregister(SelectionKey key) // FIXME: refactor to internalise key inside here? + { + key.cancel(); + } + + // process all keys and keep doing until all pending futures have completed -- i.e. all reads done up to this send state (currently wrap assumed to in send state only) + protected synchronized void clear() + { + + } + + protected synchronized void pause() + { + this.paused = true; + this.sel.wakeup(); + } + + protected synchronized void unpause() + { + this.paused = false; + notify(); + } + + protected synchronized void close() + { + this.closed = true; + this.paused = false; + //for (BinaryChannelEndpoint c : this.se.chans.values()) + for (Role peer : this.se.getPeers()) + { + try + { + BinaryChannelEndpoint c = this.se.getChannelEndpoint(peer); + c.close(); // dereg from sel? + } + catch (IOException e) + { + e.printStackTrace(); + } + } + this.sel.wakeup(); + } +} diff --git a/scribble-runtime/src/main/java/org/scribble/runtime/session/Session.java b/scribble-runtime/src/main/java/org/scribble/runtime/session/Session.java new file mode 100644 index 000000000..53f21f628 --- /dev/null +++ b/scribble-runtime/src/main/java/org/scribble/runtime/session/Session.java @@ -0,0 +1,166 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.runtime.session; + +import java.io.IOException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Random; + +import org.scribble.core.type.name.GProtoName; +import org.scribble.core.type.name.Role; +import org.scribble.main.ScribRuntimeException; +import org.scribble.util.ScribException; + +public abstract class Session +{ + private static final Map sessions = new HashMap(); + + public final int id; + + public final List impath; + public final String modpath; + public final GProtoName proto; + + //private final Map> endpoints = new HashMap<>(); // Only for local endpoints + private final Map> endpoints = new HashMap<>(); // Only for local endpoints + + public Session(int id, List impath, String modpath, GProtoName proto) + { + this.id = id; + this.impath = impath; + this.modpath = modpath; + this.proto = proto; + + Session.sessions.put(id, this); + } + + public Session(List importPath, String source, GProtoName proto) + { + this(getFreshId(), importPath, source, proto); + } + + /*// Client side + //public SessionEndpointOld toEndpoint(Principal p) throws ScribbleException, IOException + public SessionEndpoint project(R role, ScribMessageFormatter smf) throws ScribbleRuntimeException + { + if (this.endpoints.containsKey(role)) + { + throw new ScribbleRuntimeException("Session endpoint already created for: " + role); + } + try + { + SessionEndpoint ep = new SessionEndpoint<>(this, role, smf); + this.endpoints.put(role, ep); + return ep; + } + catch (IOException e) + { + throw new ScribbleRuntimeException(e); + } + }*/ + //protected

SessionEndpoint project(R role, ScribMessageFormatter smf) throws ScribbleRuntimeException, IOException + //protected void project(MPSTEndpoint se) throws ScribbleRuntimeException, IOException + protected void project(SessionEndpoint se) throws ScribRuntimeException, IOException + { + if (!getRoles().contains(se.self)) + { + throw new ScribRuntimeException("Invalid role: " + se.self); + } + if (this.endpoints.containsKey(se.self)) + { + throw new ScribRuntimeException("Session endpoint already created for: " + se.self); + } + //SessionEndpoint ep = new SessionEndpoint<>(this, role, smf); + this.endpoints.put(se.self, se); + //return ep; + } + + /*// Server side + protected SessionEndpoint project(R role, ScribMessageFormatter smf, ScribServerSocket ss) throws ScribbleRuntimeException, IOException + { + // FIXME: check valid role + if (this.endpoints.containsKey(role)) + { + throw new ScribbleRuntimeException("Session endpoint already created for: " + role); + } + SessionEndpoint ep = (ss == null) + ? new SessionEndpoint<>(this, role, smf) + : new SessionEndpoint<>(this, role, smf, ss); + this.endpoints.put(role, ep); + return ep; + }*/ + + /*public SessionEndpointOld project(Principal p) throws ScribbleException, IOException + { + if (this.endpoints.containsKey(p.role)) + { + throw new ScribbleException("Session endpoint already created for: " + p.role); + } + SessionEndpointOld ep = new SessionEndpointOld(this, p); + //this.endpoints.put(p.role, ep); + return ep; + }*/ + + public boolean hasEndpoint(Role role) + { + return this.endpoints.containsKey(role); + } + + //public SessionEndpoint getEndpoint(Role role) throws ScribbleException + public MPSTEndpoint getEndpoint(R role) throws ScribException + { + if (!this.endpoints.containsKey(role)) + { + throw new ScribException("No endpoint for: " + role); + } + @SuppressWarnings("unchecked") + MPSTEndpoint cast = (MPSTEndpoint) this.endpoints.get(role); // FIXME: + return cast; + } + + /*public static boolean hasSession(int id) + { + return Session.sessions.containsKey(id); + }*/ + + public static Session getSession(int id) throws ScribException + { + if (!Session.sessions.containsKey(id)) + { + throw new ScribException("No such session: " + id); + } + return Session.sessions.get(id); + } + + private static int getFreshId() + { + Random random = new Random(); + int id = random.nextInt(10000); + while (Session.sessions.keySet().contains(id)) + { + id = random.nextInt(10000); + } + return id; + } + + @Override + protected void finalize() + { + Session.sessions.remove(this.id); + } + + public abstract List getRoles(); +} diff --git a/scribble-runtime/src/main/java/org/scribble/runtime/session/SessionEndpoint.java b/scribble-runtime/src/main/java/org/scribble/runtime/session/SessionEndpoint.java new file mode 100644 index 000000000..c26225fb4 --- /dev/null +++ b/scribble-runtime/src/main/java/org/scribble/runtime/session/SessionEndpoint.java @@ -0,0 +1,386 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.runtime.session; + +import java.io.IOException; +import java.nio.channels.SelectionKey; +import java.security.GeneralSecurityException; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +import org.scribble.core.type.name.Role; +import org.scribble.main.ScribRuntimeException; +import org.scribble.runtime.message.ScribMessageFormatter; +import org.scribble.runtime.net.BinaryChannelEndpoint; +import org.scribble.runtime.net.BinaryChannelWrapper; +import org.scribble.runtime.net.ScribServerSocket; +import org.scribble.runtime.util.Buf; +import org.scribble.util.RuntimeScribException; + +// FIXME: factor out between role-endpoint based socket and channel-endpoint sockets +//.. initiator and joiner endpoints +public abstract class SessionEndpoint implements AutoCloseable +{ + public final Buf gc = new Buf<>(); + + public final Session sess; + public final Role self; + public final ScribMessageFormatter smf; + + protected boolean init = false; + //private boolean bound = false; + private boolean complete = false; + private boolean closed = false; + + protected final Map servs = new HashMap<>(); // For multi-role endpoints? // Or currently only self is used as a key, but should be peer roles instead? + // Generally, think was in the middle of refactoring for explicit connections + protected final Map chans = new HashMap<>(); + + private final ScribInputSelector sel; + private final Map keys = new HashMap<>(); + + public SessionEndpoint(S sess, R self, ScribMessageFormatter smf) throws IOException, ScribRuntimeException + { + this.sess = sess; + this.self = self; + this.smf = smf; + + sess.project(this); + + this.sel = new ScribInputSelector(this); + this.sel.start(); + } + + /*// FIXME: generalise roles and server socks for endpoints playing multiple roles + public SessionEndpoint(Session sess, Role self, ScribMessageFormatter smf, ScribServerSocket ss) throws IOException, ScribbleRuntimeException + { + this(sess, self, smf); + //register(self, ss); + this.sel.pause(); + this.servs.put(self, ss); + this.sel.unpause(); + } + + // FIXME: allowing multiple serversocks to be registered, but it just overrides the self entry (already set by constructor) -- server socks not identified with peer (or protocol state) + // -- and InitSocket accept always uses the self server sock + //public synchronized void register(Role self, ScribServerSocket ss) throws IOException, ScribbleRuntimeException + // TODO: was refactoring for explicit connections + protected synchronized void register(Role self, ScribServerSocket ss) throws IOException, ScribbleRuntimeException + { + this.sel.pause(); + this.servs.put(self, ss); + this.sel.unpause(); + }*/ + + /*public synchronized void register(Role peer, String host, int port) throws IOException + { + throw new RuntimeException("TODO: " + host + ", " + port); + }*/ + + public synchronized void register(Role peer, BinaryChannelEndpoint c) throws IOException + { + this.sel.pause(); + SelectionKey key = this.sel.register(c.getSelectableChannel()); + key.attach(peer); + this.keys.put(peer, key); + this.chans.put(peer, c); + this.sel.unpause(); + } + + // w is uninitialised (need to use wrapChannel) + public synchronized void reregister(Role peer, BinaryChannelWrapper w) throws IOException, GeneralSecurityException + { + /*this.sel.pause(); + SelectionKey old = getChannelEndpoint(peer).getSelectableChannel().keyFor(this.sel.getSelector()); + if (old == null) + { + throw new RuntimeException("Endpoint not yet registered for: " + peer); + } + old.cancel(); + SelectionKey key = this.sel.register(c.getSelectableChannel()); + key.attach(peer); + this.chans.put(peer, c); + this.sel.unpause();*/ + + BinaryChannelEndpoint c = getChannelEndpoint(peer); + c.sync(); + + this.sel.pause(); + // FIXME: consume all pending messages/futures first? or ok to leave data in existing bb -- or only permit in states where bb is empty? + // Underlying selectable channel is the same, so no need to cancel key and re-reg -- OK to assume in general? + w.wrapChannel(c); + w.clientHandshake(); + this.chans.put(peer, w); // SelectoinKey unchanged? + this.sel.unpause(); + } + + public synchronized void deregister(Role peer) throws IOException + { + this.sel.pause(); + try + { + //this.keys.remove(peer).cancel(); + this.sel.deregister(this.keys.remove(peer)); + this.chans.remove(peer).close(); + } + finally + { + this.sel.unpause(); + } + } + + public ScribInputSelector getSelector() + { + return this.sel; + } + + public BinaryChannelEndpoint getChannelEndpoint(Role role) + { + if (!this.chans.containsKey(role)) + { + throw new RuntimeScribException(this.self + " is not connected to: " + role); + } + return this.chans.get(role); + } + + public void setCompleted() + { + this.complete = true; + } + + public boolean isCompleted() + { + return this.complete; + } + + @Override + public synchronized void close() throws ScribRuntimeException + { + if (!this.closed) + { + try + { + this.closed = true; + this.sel.close(); + this.servs.values().forEach(ss -> ss.unbind()); + } + finally + { + if (!isCompleted()) // Subsumes use -- must be used for sess to be completed + { + throw new ScribRuntimeException("Session not completed: " + this.self); + } + } + } + } + + public ScribServerSocket getSelfServerSocket() + { + ScribServerSocket ss = this.servs.get(this.self); + if (ss == null) + { + throw new RuntimeScribException("No server registered."); + } + return ss; + } + + protected Set getPeers() + { + return this.chans.keySet(); + } + + + /*public void connect(Role role, Callable cons, String host, int port) throws ScribbleRuntimeException, UnknownHostException, IOException + { + // Can connect unlimited, as long as not already used via init + if (this.init) + { + throw new ScribbleRuntimeException("Socket already initialised: " + this.getClass()); + } + if (this.chans.containsKey(role)) + { + throw new ScribbleRuntimeException("Already connected to: " + role); + } + try + { + BinaryChannelEndpoint c = cons.call(); + c.initClient(this, host, port); + register(role, c); + } + catch (Exception e) + { + if (e instanceof IOException) + { + throw (IOException) e; + } + throw new IOException(e); + } + } + + public void accept(ScribServerSocket ss, Role role) throws IOException, ScribbleRuntimeException + { + if (this.init) + { + throw new ScribbleRuntimeException("Socket already initialised: " + this.getClass()); + } + if (this.chans.containsKey(role)) + { + throw new ScribbleRuntimeException("Already connected to: " + role); + } + register(role, ss.accept(this)); // FIXME: serv map in SessionEndpoint not currently used + } + + public void disconnect(Role role) throws IOException, ScribbleRuntimeException + { + if (!this.chans.containsKey(role)) + { + throw new ScribbleRuntimeException("Not connected to: " + role); + } + deregister(role); + }*/ + + /*public void init() + { + this.initialised = true; + }*/ + + /*protected boolean isInitialised() + { + return this.initialised; + }*/ + + //public void bind() throws ScribbleRuntimeException + public void init() throws ScribRuntimeException + { + /*if (this.bound) + { + throw new ScribbleRuntimeException("Session endpoint already bound."); + }*/ + //if (!this.initialised) + if (this.init) + { + throw new ScribRuntimeException("Session endpoint already initialised."); + } + //this.bound = true; + this.init = true; + } + + + + + + /*public final Session sess; + //public final Principal self; + public final Role self; + public final ScribMessageFormatter smf; + + private boolean complete = false; + + private final Map socks = new HashMap<>(); // Includes SelfSocketEndpoint + private final EndpointInputQueues queues = new EndpointInputQueues(); + + //protected final LocalProtocolDecl root; + //public final Monitor monitor; + + protected SessionEndpoint(Session sess, Role self, ScribMessageFormatter smf) //throws ScribbleException, IOException + { + this.sess = sess; + this.self = self; + this.smf = smf; + + /*ProtocolName lpn = Projector.makeProjectedProtocolName(sess.proto, this.self.role); + this.root = (LocalProtocolDecl) projections.get(lpn.getPrefix()).protos.get(0);* / + //this.monitor = createMonitor(sess.impath, sess.source, sess.proto, self); + } + + public void setCompleted() + { + this.complete = true; + } + + public boolean isCompleted() + { + return this.complete; + } + + // Only for remote endpoints (self SocketEndpoint is done in above constructor; but not recorded in role-principal map) + public void register(Role peer, SocketWrapper sw) //throws IOException + { + this.socks.put(peer, new SocketEndpoint(this, peer, sw)); + } + + /*public Set getRemoteRoles() + { + return this.remroles.keySet(); + } + + public Principal getRemotePrincipal(Role role) + { + return this.remroles.get(role); + }* / + + public SocketEndpoint getSocketEndpoint(Role role) + { + if (!this.socks.containsKey(role)) + { + throw new RuntimeScribbleException(this.self + " is not connected to: " + role); + } + return this.socks.get(role); + } + + public EndpointInputQueues getInputQueues() + { + return this.queues; + } + + public void close() + { + for (SocketEndpoint se : this.socks.values()) + { + try + { + se.close(); + } + catch (IOException e) + { + // FIXME: + } + } + } + + /* // proto is fullname + private static Monitor createMonitor(List impath, String source, ProtocolName proto, Role self) throws ScribbleException, IOException + { + // FIXME: API (strings vs non-strings, simple vs full names) + Job job = Tool.getWellFormedJob(impath, source); + Map projections = Tool.getProjections(job, proto.getSimpleName().toString(), self.toString()); + Map graphs = Tool.buildGraphs(job, projections); + + ProtocolName lpn = Projector.makeProjectedProtocolName(proto, self); + System.out.println("[DEBUG] Projected graph: " + graphs.get(lpn).toDot()); + + return new Monitor(graphs, lpn); + }*/ + + /*public Set getRemoteRoles() + { + return this.remroles.keySet(); + } + + public Principal getRemotePrincipal(Role role) + { + return this.remroles.get(role); + }*/ +} diff --git a/scribble-runtime/src/main/java/org/scribble/runtime/statechans/AcceptSocket.java b/scribble-runtime/src/main/java/org/scribble/runtime/statechans/AcceptSocket.java new file mode 100644 index 000000000..1415ae8e6 --- /dev/null +++ b/scribble-runtime/src/main/java/org/scribble/runtime/statechans/AcceptSocket.java @@ -0,0 +1,45 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.runtime.statechans; + +import java.io.IOException; + +import org.scribble.core.type.name.Role; +import org.scribble.main.ScribRuntimeException; +import org.scribble.runtime.net.ScribServerSocket; +import org.scribble.runtime.session.MPSTEndpoint; +import org.scribble.runtime.session.Session; +import org.scribble.runtime.session.SessionEndpoint; + +public abstract class AcceptSocket extends LinearSocket +{ + //protected AcceptSocket(MPSTEndpoint ep) + protected AcceptSocket(SessionEndpoint ep) + { + super(ep); + } + + /*public void accept(ScribServerSocket ss, Role role) throws IOException, ScribbleRuntimeException + { + use(); + this.ep.register(role, ss.accept()); + }*/ + + protected void accept(ScribServerSocket ss, Role role) throws IOException, ScribRuntimeException + { + use(); + //this.se.accept(ss, role); // FIXME: csat + MPSTEndpoint.accept(this.se, ss, role); + } +} diff --git a/scribble-runtime/src/main/java/org/scribble/runtime/statechans/AffineSocket.java b/scribble-runtime/src/main/java/org/scribble/runtime/statechans/AffineSocket.java new file mode 100644 index 000000000..fd1d1a5c5 --- /dev/null +++ b/scribble-runtime/src/main/java/org/scribble/runtime/statechans/AffineSocket.java @@ -0,0 +1,33 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.runtime.statechans; + +import org.scribble.core.type.name.Role; +import org.scribble.runtime.session.MPSTEndpoint; +import org.scribble.runtime.session.Session; + +@Deprecated +public abstract class AffineSocket extends LinearSocket +{ + protected AffineSocket(MPSTEndpoint ep) + { + super(ep); + } + + /*@Override + protected void close() throws ScribbleRuntimeException + { + this.ep.close(); // No used check + }*/ +} diff --git a/scribble-runtime/src/main/java/org/scribble/runtime/statechans/BranchSocket.java b/scribble-runtime/src/main/java/org/scribble/runtime/statechans/BranchSocket.java new file mode 100644 index 000000000..80acc14fa --- /dev/null +++ b/scribble-runtime/src/main/java/org/scribble/runtime/statechans/BranchSocket.java @@ -0,0 +1,27 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.runtime.statechans; + +import org.scribble.core.type.name.Role; +import org.scribble.runtime.session.Session; +import org.scribble.runtime.session.SessionEndpoint; + +public abstract class BranchSocket extends ReceiveSocket +{ + //protected BranchSocket(MPSTEndpoint ep) + protected BranchSocket(SessionEndpoint ep) + { + super(ep); + } +} diff --git a/scribble-runtime/src/main/java/org/scribble/runtime/statechans/CaseSocket.java b/scribble-runtime/src/main/java/org/scribble/runtime/statechans/CaseSocket.java new file mode 100644 index 000000000..f502d8c03 --- /dev/null +++ b/scribble-runtime/src/main/java/org/scribble/runtime/statechans/CaseSocket.java @@ -0,0 +1,28 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.runtime.statechans; + +import org.scribble.core.type.name.Role; +import org.scribble.runtime.session.Session; +import org.scribble.runtime.session.SessionEndpoint; + +// For "receiving" the payloads after a branch is done +public abstract class CaseSocket extends LinearSocket // No I/O induced by this socket itself (i.e. not a ReceiveSocket) +{ + //protected CaseSocket(MPSTEndpoint ep) + protected CaseSocket(SessionEndpoint ep) + { + super(ep); + } +} diff --git a/scribble-runtime/src/main/java/org/scribble/runtime/statechans/ConnectSocket.java b/scribble-runtime/src/main/java/org/scribble/runtime/statechans/ConnectSocket.java new file mode 100644 index 000000000..26a5a8434 --- /dev/null +++ b/scribble-runtime/src/main/java/org/scribble/runtime/statechans/ConnectSocket.java @@ -0,0 +1,46 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.runtime.statechans; + +import java.io.IOException; +import java.net.UnknownHostException; +import java.util.concurrent.Callable; + +import org.scribble.core.type.name.Role; +import org.scribble.main.ScribRuntimeException; +import org.scribble.runtime.net.BinaryChannelEndpoint; +import org.scribble.runtime.session.MPSTEndpoint; +import org.scribble.runtime.session.Session; + +@Deprecated +public abstract class ConnectSocket extends LinearSocket +{ + protected ConnectSocket(MPSTEndpoint ep) + { + super(ep); + } + + /*public void connect(Role role, String host, int port) throws ScribbleRuntimeException, UnknownHostException, IOException + { + use(); + Socket s = new Socket(host, port); + this.ep.register(role, new SocketWrapper(s)); + }*/ + + protected void connect(Role role, Callable cons, String host, int port) throws ScribRuntimeException, UnknownHostException, IOException + { + use(); + //this.se.connect(role, cons, host, port); + } +} diff --git a/scribble-runtime/src/main/java/org/scribble/runtime/statechans/EndSocket.java b/scribble-runtime/src/main/java/org/scribble/runtime/statechans/EndSocket.java new file mode 100644 index 000000000..8ca386cd0 --- /dev/null +++ b/scribble-runtime/src/main/java/org/scribble/runtime/statechans/EndSocket.java @@ -0,0 +1,51 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.runtime.statechans; + +import org.scribble.core.type.name.Role; +import org.scribble.main.ScribRuntimeException; +import org.scribble.runtime.session.Session; +import org.scribble.runtime.session.SessionEndpoint; + +public abstract class EndSocket extends ScribSocket +{ + //public EndSocket(SessionEndpoint se, boolean dummy) + //protected EndSocket(MPSTEndpoint se) + protected EndSocket(SessionEndpoint se) + { + super(se); + } + + public void end() throws ScribRuntimeException + { + /*super.use(); + this.se.setCompleted();*/ + /*if (!this.se.isCompleted()) // Disabled for user implementations of the Handle interface -- No: unnecessary -- and if EndSocket has been returned, then session must be complete anyway... + { + throw new ScribbleRuntimeException("Session not completed: " + this.se); + }*/ + this.se.setCompleted(); + this.se.close(); + //this.closed = true; + } + + /*@Override + public void close() + { + if (!this.closed) + { + this.ep.close(); + } + }*/ +} diff --git a/scribble-runtime/src/main/java/org/scribble/runtime/statechans/InitSocket.java b/scribble-runtime/src/main/java/org/scribble/runtime/statechans/InitSocket.java new file mode 100644 index 000000000..8dc8f3c0f --- /dev/null +++ b/scribble-runtime/src/main/java/org/scribble/runtime/statechans/InitSocket.java @@ -0,0 +1,94 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.runtime.statechans; + +import java.io.IOException; +import java.net.UnknownHostException; +import java.util.concurrent.Callable; + +import org.scribble.core.type.name.Role; +import org.scribble.main.ScribRuntimeException; +import org.scribble.runtime.net.BinaryChannelEndpoint; +import org.scribble.runtime.net.ScribServerSocket; +import org.scribble.runtime.session.MPSTEndpoint; +import org.scribble.runtime.session.Session; + +// Establishing transport connections handled in here and wrapped up in SocketWrapper +@Deprecated +public abstract class InitSocket extends LinearSocket implements AutoCloseable +{ + protected InitSocket(MPSTEndpoint se) + { + super(se); + } + + public void connect(Callable cons, Role role, String host, int port) throws ScribRuntimeException, UnknownHostException, IOException + { + // Can connect unlimited, as long as not already used via init + if (isUsed()) + { + throw new ScribRuntimeException("Socket already initialised: " + this.getClass()); + } + try + { + BinaryChannelEndpoint c = cons.call(); + c.initClient(se, host, port); + this.se.register(role, c); + } + catch (Exception e) + { + if (e instanceof IOException) + { + throw (IOException) e; + } + throw new IOException(e); + } + } + + public void accept(ScribServerSocket ss, Role role) throws IOException, ScribRuntimeException + { + //accept(null, role); + if (isUsed()) + { + throw new ScribRuntimeException("Socket already initialised: " + this.getClass()); + } + this.se.register(role, ss.accept(this.se)); // FIXME: serv map in SessionEndpoint not currently used + } + + @Deprecated + public void accept(Role role) throws IOException, ScribRuntimeException + { + if (isUsed()) + { + throw new ScribRuntimeException("Socket already initialised: " + this.getClass()); + } + this.se.register(role, this.se.getSelfServerSocket().accept(this.se)); + } + + @Override + public void close() throws ScribRuntimeException + { + try + { + this.se.close(); + } + finally + { + if (!this.se.isCompleted()) // Subsumes use -- must be used for sess to be completed + { + throw new ScribRuntimeException("Session not completed: " + this.se.self); + } + } + } +} diff --git a/scribble-runtime/src/main/java/org/scribble/runtime/statechans/LinearSocket.java b/scribble-runtime/src/main/java/org/scribble/runtime/statechans/LinearSocket.java new file mode 100644 index 000000000..7244c2491 --- /dev/null +++ b/scribble-runtime/src/main/java/org/scribble/runtime/statechans/LinearSocket.java @@ -0,0 +1,111 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.runtime.statechans; + +import java.io.IOException; +import java.util.concurrent.Callable; + +import org.scribble.core.type.name.Role; +import org.scribble.main.ScribRuntimeException; +import org.scribble.runtime.net.BinaryChannelWrapper; +import org.scribble.runtime.session.Session; +import org.scribble.runtime.session.SessionEndpoint; + +// Not AutoClosable -- leave that to InitSocket +public abstract class LinearSocket extends ScribSocket +{ + private boolean used = false; + + //protected LinearSocket(MPSTEndpoint ep) + protected LinearSocket(SessionEndpoint ep) + { + super(ep); + } + + protected boolean isUsed() + { + return this.used; + } + + //protected synchronized void use() throws ScribbleRuntimeException + protected void use() throws ScribRuntimeException + { + if (this.used) + { + throw new ScribRuntimeException("Linear socket resource already used: " + this.getClass()); + } + this.used = true; + } + + //protected // FIXME: generate API operation + public void wrapClient(Role peer, Callable cons) throws IOException, ScribRuntimeException + { + //use(); // FIXME: should be use for proper API operation + if (this.used) + { + throw new ScribRuntimeException("Linear socket resource already used: " + this.getClass()); + } + try + { + this.se.reregister(peer, cons.call()); + } + catch (Exception e) + { + if (e instanceof IOException) + { + throw (IOException) e; + } + throw new IOException(e); + } + } + + // FIXME: refactor + // FIXME: State supertype of T + public static T wrapClient(T s, Role peer, Callable cons) throws IOException, ScribRuntimeException + { + ((LinearSocket) s).wrapClient(peer, cons); + return s; + } + + protected void wrapServer() + { + throw new RuntimeException("TODO"); + } + + /*// Only triggered by autoclose or explicit close, i.e. not called directly by user + protected synchronized void close() throws ScribbleRuntimeException + { + if (!this.used) + { + this.ep.close(); + throw new ScribbleRuntimeException("Socket resource not used: " + this.getClass()); + } + }*/ + + /*// FIXME: factor out transport parameter + // FIXME: close old socket -- handle old receive thread (consider messsages still arriving -- maybe only support reconnect for states where this is not possible) + // FIXME: synch new receive thread with old one if messages are allowed to still arrive on old one + public void reconnect(Role role, String host, int port) throws ScribbleRuntimeException, UnknownHostException, IOException + { + // Can connect unlimited, as long as not already used via init + if (this.used) + { + throw new ScribbleRuntimeException("Linear socket resource already used: " + this.getClass()); + } + SSLSocketFactory fact = (SSLSocketFactory) SSLSocketFactory.getDefault(); + Socket s1 = this.ep.getSocketEndpoint(role).getSocketWrapper().getSocket(); // FIXME: check already connected + SSLSocket s2 = (SSLSocket) fact.createSocket(s1, s1.getInetAddress().getHostAddress(), s1.getPort(), true); + this.ep.register(role, new SocketWrapper(s2)); // Replaces old SocketEndpoint // FIXME: tidy up + }*/ +} diff --git a/scribble-runtime/src/main/java/org/scribble/runtime/statechans/OutputSocket.java b/scribble-runtime/src/main/java/org/scribble/runtime/statechans/OutputSocket.java new file mode 100644 index 000000000..fb03f76c5 --- /dev/null +++ b/scribble-runtime/src/main/java/org/scribble/runtime/statechans/OutputSocket.java @@ -0,0 +1,91 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.runtime.statechans; + +import java.io.IOException; +import java.net.UnknownHostException; +import java.util.concurrent.Callable; + +import org.scribble.core.type.name.Op; +import org.scribble.core.type.name.Role; +import org.scribble.main.ScribRuntimeException; +import org.scribble.runtime.message.ScribMessage; +import org.scribble.runtime.net.BinaryChannelEndpoint; +import org.scribble.runtime.session.MPSTEndpoint; +import org.scribble.runtime.session.Session; +import org.scribble.runtime.session.SessionEndpoint; + +public abstract class OutputSocket extends LinearSocket +{ + //protected OutputSocket(MPSTEndpoint ep) + protected OutputSocket(SessionEndpoint ep) + { + super(ep); + } + + protected void writeScribMessage(Role peer, Op op, Object... payload) throws IOException, ScribRuntimeException + { + writeScribMessage(peer, new ScribMessage(op, payload)); + } + + protected void writeScribMessage(Role peer, ScribMessage msg) throws IOException, ScribRuntimeException + { + use(); + /*SocketEndpoint se = this.ep.getSocketEndpoint(peer); + se.writeMessageAndFlush(msg);*/ + this.se.getChannelEndpoint(peer).write(msg); + } + + // FIXME: check if MPST/ExplicitEndpoint + protected void connect(Role role, Callable cons, String host, int port) throws ScribRuntimeException, UnknownHostException, IOException + { + use(); + //this.se.connect(role, cons, host, port); + MPSTEndpoint.request(this.se, role, cons, host, port); + } + + // FIXME: check if MPST/ExplicitEndpoint + protected void disconnect(Role role) throws ScribRuntimeException, UnknownHostException, IOException + { + use(); + //this.se.disconnect(role); + MPSTEndpoint.disconnect(this.se, role); + } + + //public void wrap(Callable cons, Role role, String host, int port) throws ScribbleRuntimeException, UnknownHostException, IOException + + /*// Right to limit reconnect to send state? Or generalise and manually handle pending incoming messages on old connection? + public void reconnect(Callable cons, Role role, String host, int port) throws ScribbleRuntimeException, UnknownHostException, IOException + { + // Following InitSocket.connect + use(); + + ...FIXME: close old and make new + + try + { + BinaryChannelEndpoint c = cons.call(); + c.initClient(se, host, port); + this.se.reregister(role, c); + } + catch (Exception e) + { + if (e instanceof IOException) + { + throw (IOException) e; + } + throw new IOException(e); + } + }*/ +} diff --git a/scribble-runtime/src/main/java/org/scribble/runtime/statechans/ReceiveSocket.java b/scribble-runtime/src/main/java/org/scribble/runtime/statechans/ReceiveSocket.java new file mode 100644 index 000000000..f9919c99a --- /dev/null +++ b/scribble-runtime/src/main/java/org/scribble/runtime/statechans/ReceiveSocket.java @@ -0,0 +1,69 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.runtime.statechans; + +import java.io.IOException; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; + +import org.scribble.core.type.name.Role; +import org.scribble.main.ScribRuntimeException; +import org.scribble.runtime.message.ScribMessage; +import org.scribble.runtime.session.Session; +import org.scribble.runtime.session.SessionEndpoint; + +public abstract class ReceiveSocket extends LinearSocket +{ + private CompletableFuture fut; + + protected ReceiveSocket(SessionEndpoint se) + { + super(se); + } + + protected ScribMessage readScribMessage(Role peer) throws ClassNotFoundException, IOException, ScribRuntimeException + { + try + { + //ScribMessage m = this.ep.smf.readMessage(this.ep.getSocketEndpoint(role).dis); + ScribMessage m = getFuture(peer).get(); + + //System.out.println("Read: " + m); + + return m; + } + catch (InterruptedException e) + { + throw new IOException(e); + } + catch (ExecutionException e) + { + // The Future converts the RuntimeScribbleException wrapper for the underlying IOException into an ExecutionException + throw new IOException(e); + } + } + + protected boolean isDone(Role peer) + { + //return !this.ep.getInputQueues().isEmpty(peer); + return (this.fut == null) || (this.fut.isDone()); + } + + protected CompletableFuture getFuture(Role peer) throws ScribRuntimeException + { + use(); + //this.fut = this.ep.getInputQueues().getFuture(peer); + return this.se.getChannelEndpoint(peer).getFuture(); + } +} diff --git a/scribble-runtime/src/main/java/org/scribble/runtime/statechans/ScribSocket.java b/scribble-runtime/src/main/java/org/scribble/runtime/statechans/ScribSocket.java new file mode 100644 index 000000000..ec296ac75 --- /dev/null +++ b/scribble-runtime/src/main/java/org/scribble/runtime/statechans/ScribSocket.java @@ -0,0 +1,29 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.runtime.statechans; + +import org.scribble.core.type.name.Role; +import org.scribble.runtime.session.Session; +import org.scribble.runtime.session.SessionEndpoint; + +// FIXME: rename package (and class?) to statechans -- cf., handlers package +public abstract class ScribSocket +{ + protected SessionEndpoint se; + + protected ScribSocket(SessionEndpoint ep) + { + this.se = ep; + } +} diff --git a/scribble-runtime/src/main/java/org/scribble/runtime/util/Buf.java b/scribble-runtime/src/main/java/org/scribble/runtime/util/Buf.java new file mode 100644 index 000000000..bd04b02ad --- /dev/null +++ b/scribble-runtime/src/main/java/org/scribble/runtime/util/Buf.java @@ -0,0 +1,29 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.runtime.util; + +public class Buf +{ + public T val; + + public Buf() + { + + } + + public Buf(T val) + { + this.val = val; + } +} diff --git a/scribble-runtime/src/main/java/org/scribble/runtime/util/ScribFuture.java b/scribble-runtime/src/main/java/org/scribble/runtime/util/ScribFuture.java new file mode 100644 index 000000000..3e2f9a7a2 --- /dev/null +++ b/scribble-runtime/src/main/java/org/scribble/runtime/util/ScribFuture.java @@ -0,0 +1,86 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.runtime.util; + +import java.io.IOException; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; + +import org.scribble.runtime.message.ScribMessage; + +// P is payload type as an array +public abstract class ScribFuture //implements Future

+{ + private CompletableFuture future; + private ScribMessage m; + + public ScribFuture(CompletableFuture future) + { + this.future = future; + } + + // Not synch: can return false while get is blocked + public boolean isDone() + { + return this.m != null; + } + + protected synchronized ScribMessage get() throws IOException + { + try + { + if (isDone()) + { + return this.m; + } + this.m = this.future.get(); + + //System.out.println("Got: " + m); + + return this.m; + } + catch (InterruptedException | ExecutionException e) + { + throw new IOException(e); + } + } + + public abstract ScribFuture sync() throws IOException; //ExecutionException, InterruptedException; // sync returns the Future (cf. get returns the val) + + /*@Override + public P get(long timeout, TimeUnit unit) + throws InterruptedException, ExecutionException, TimeoutException + { + ScribMessage m = this.future.get(timeout, unit); + return (P) m.payload.clone()[0]; // FIXME: exactly one payload + } + + @Override + public boolean cancel(boolean mayInterruptIfRunning) + { + return this.future.cancel(mayInterruptIfRunning); + } + + @Override + public boolean isCancelled() + { + return this.future.isCancelled(); + } + + @Override + public boolean isDone() + { + return this.future.isDone(); + }*/ +} diff --git a/scribble-test/pom.xml b/scribble-test/pom.xml new file mode 100644 index 000000000..49d617a80 --- /dev/null +++ b/scribble-test/pom.xml @@ -0,0 +1,90 @@ + + + 4.0.0 + + + scribble-test + + + + org.scribble + scribble-core + + + org.scribble + scribble-parser + + + + org.scribble + scribble-cli + + + org.scribble + scribble-runtime + + + junit + junit + test + + + + + org.scribble + parent + 0.5.1-SNAPSHOT + ../pom.xml + + + + + + + + + + com.mycila + license-maven-plugin + + + **/*.scr + **/*.java + **/*.policy + **/*.xml + **/*.html + **/stylesheet.css + **/script.js + **/package-list + **/IGNORE + **/*.versionsBackup + + + + + + + + scribble-test + + diff --git a/scribble-test/src/main/java/org/scribble/Dummy.java b/scribble-test/src/main/java/org/scribble/Dummy.java new file mode 100644 index 000000000..3e336c4cf --- /dev/null +++ b/scribble-test/src/main/java/org/scribble/Dummy.java @@ -0,0 +1,5 @@ +package org.scribble; + +// HACK: Dummy file to avoid mvn "empty scribble-test jar" warning +public class Dummy { +} diff --git a/scribble-test/src/test/java/org/scribble/test/ExecUtil.java b/scribble-test/src/test/java/org/scribble/test/ExecUtil.java new file mode 100644 index 000000000..0d4accb1e --- /dev/null +++ b/scribble-test/src/test/java/org/scribble/test/ExecUtil.java @@ -0,0 +1,174 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.test; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.util.Map; +import java.util.TreeMap; +import java.util.concurrent.BrokenBarrierException; +import java.util.concurrent.Callable; +import java.util.concurrent.CyclicBarrier; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +import org.apache.commons.io.IOUtils; + + +public class ExecUtil { + /** + * The summary of a process. + * @author Tiago Cogumbreiro (cogumbreiro@users.sf.net) + * + */ + public static class ProcessSummary { + /** + * The standard output. + */ + public final String stdout; + /** + * The standard error output. + */ + public final String stderr; + /** + * The exit value of the process. + */ + public final int exitValue; + public ProcessSummary(String stdout, String stderr, int exitValue) { + this.stdout = stdout; + this.stderr = stderr; + this.exitValue = exitValue; + } + } + public static String joinPath(String ...parts) { + return join(File.separator, parts); + } + public static String joinPath(Iterable parts) { + return join(File.separator, parts); + } + public static String join(String separator, String ...parts) { + int count = 0; + StringBuilder builder = new StringBuilder(); + for (String part : parts) { + if (count > 0) { + builder.append(separator); + } + builder.append(part); + count++; + } + return builder.toString(); + } + public static String join(String separator, Iterable parts) { + int count = 0; + StringBuilder builder = new StringBuilder(); + for (String part : parts) { + if (count > 0) { + builder.append(separator); + } + builder.append(part); + count++; + } + return builder.toString(); + } + + /** + * Runs a process, up to a certain timeout, + * + * @throws IOException + * @throws TimeoutException + * @throws ExecutionException + * @throws InterruptedException + */ + public static ProcessSummary execUntil(long timeout, String... command) + throws IOException, InterruptedException, ExecutionException { + return execUntil(new TreeMap(), timeout, command); + } + + /** + * Runs a process, up to a certain timeout, + * + * @throws IOException + * @throws TimeoutException + * @throws ExecutionException + * @throws InterruptedException + */ + public static ProcessSummary execUntil(Map env, long timeout, String... command) + throws IOException, InterruptedException, ExecutionException { + ProcessBuilder builder = new ProcessBuilder(command); + builder.environment().putAll(env); + Process process = builder.start(); + ExecutorService executorService = Executors.newFixedThreadPool(3); + CyclicBarrier onStart = new CyclicBarrier(3); + Future stderr = executorService.submit(toString(process.getErrorStream(), + onStart)); + Future stdout = executorService.submit(toString(process.getInputStream(), + onStart)); + Future waitFor = executorService.submit(waitFor(process, + onStart)); + ProcessSummary result = null; + try { + waitFor.get(timeout, TimeUnit.MILLISECONDS); + } catch (TimeoutException e) { + // timeouts are ok + } finally { + process.destroy(); + waitFor.get(); + result = new ProcessSummary(stdout.get(), stderr.get(), process.exitValue()); + executorService.shutdown(); + } + return result; + } + + /** + * Waits for a process to terminate. + * + * @param process The process it should wait for. + * @param onStart Notifies others upon starting. + * @return The return code. + */ + public static Callable waitFor(final Process process, + final CyclicBarrier onStart) { + return new Callable() { + public Integer call() throws InterruptedException, BrokenBarrierException { + onStart.await(); + return process.waitFor(); + } + }; + } + + /** + * Converts an input stream to a string as much as possible. It stops + * at IOExceptions, but returns what it read thus far. + * @param in The input stream. + * @param onStart Notify others that it started. + */ + private static Callable toString(final InputStream input, final CyclicBarrier onStart) { + return new Callable() { + public String call() throws InterruptedException, BrokenBarrierException, IOException { + onStart.await(); + try { + return IOUtils.toString(input); + } finally { + IOUtils.closeQuietly(input); + } + } + }; + } + +} diff --git a/scribble-test/src/test/java/org/scribble/test/Harness.java b/scribble-test/src/test/java/org/scribble/test/Harness.java new file mode 100644 index 000000000..e153f17f4 --- /dev/null +++ b/scribble-test/src/test/java/org/scribble/test/Harness.java @@ -0,0 +1,137 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.test; + +import java.io.File; +import java.util.Collection; +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; + +public class Harness +{ + //private static final SuffixFileFilter SCRIBBLE_EXT = new SuffixFileFilter(".scr"); + private static final String SCRIBBLE_EXT = ".scr"; + + protected static final String DIR_IGNORE_FILE = "IGNORE"; + protected static final String TEST_DIR_FLAG = "test.dir"; + + /*/** + * Returns the java builder with the default settings to use JArmus. + * + * @param className + * @return + * / + // Currently unused + @Deprecated + public static JavaProcessBuilder java(String className) + { + JavaProcessBuilder java = new JavaProcessBuilder(className); + // java.appendClasspath("lib/antlr-3.5.2-complete.jar"); + // java.appendClasspath("bin/"); + java.appendClasspath("target/classes/"); + java.appendClasspath("c:/Users/Raymond/.m2/repository/org/antlr/antlr-runtime/3.2/antlr-runtime-3.2.jar/"); + java.appendClasspath("../core/target/classes/"); + java.appendClasspath("../parser/target/classes/"); + /*java.appendClasspath("../validation/target/classes/"); + java.appendClasspath("../projection/target/classes/"); + java.appendClasspath("../trace/target/classes/");*/ + /*java.appendClasspath("C:/Users/Raymond/.m2/repository/org/codehaus/jackson/jackson-mapper-asl/1.9.9/jackson-mapper-asl-1.9.9.jar/"); + java.appendClasspath("C:/Users/Raymond/.m2/repository/org/codehaus/jackson/jackson-core-asl/1.9.9/jackson-core-asl-1.9.9.jar/");* / + // java.appendClasspath("org.scribble2.cli.CommandLine -path modules/validation/src/test/scrib/src modules/validation/src/test/scrib/src/Test.scr/"); + return java; + } + //*/ + + /** + * Returns all Scribble files in a given directory. + * + * @param dir + * @return + */ + private static Collection getScribbleFilePaths(String dir) + { + /* // Broken: somehow interfering with JUnit results (e.g., bad.efsm.grecursion.unfair.Test01) + NameFileFilter ignore = new NameFileFilter("IGNORE"); + TreeSet result = new TreeSet<>(); + FileUtils.listFiles(new File(directory), SCRIBBLE_EXT, new IgnoredDirectoryWhenFilter(ignore)).stream().forEach((file) -> result.add(file.getPath())); + */ + /*return getAllScrFilesUnderDirectory(dir).stream() // Debugging AllTest/BadTest bad.efsm.grecursion.unfair.Test01; problem + .map((f) -> f.getAbsolutePath().toString()) + .collect(Collectors.toList());*/ + List res = new LinkedList<>(); + for (File f : getAllScrFilesUnderDirectory(dir)) + { + res.add(f.getAbsolutePath().toString()); + } + return res; + } + + private static List getAllScrFilesUnderDirectory(String path) + { + List res = new LinkedList<>(); + for (File f : new File(path).listFiles()) + { + if (f.isFile()) + { + if (f.getName().equals(Harness.DIR_IGNORE_FILE)) + { + return Collections.emptyList(); + } + else if (f.getName().endsWith(Harness.SCRIBBLE_EXT)) + { + res.add(f); + } + } + else if (f.isDirectory()) + { + res.addAll(getAllScrFilesUnderDirectory(f.getAbsolutePath())); + } + } + return res; + } + + public static Collection findTests(String path) + { + return getScribbleFilePaths(path); + //return Collections.emptyList(); + } + + // dir should be full path + public static Collection makeTests(boolean isBadTest, String dir) + { + /*return findTests(dir).stream() // Debugging AllTest/BadTest bad.efsm.grecursion.unfair.Test01; problem + .map((e) -> new Object[] { e, isBadTest }) + .collect(Collectors.toList());*/ + List res = new LinkedList<>(); + for (String t : findTests(dir)) + { + res.add(new Object[] { t, isBadTest }); + } + return res; + } + + // root is relative path from cli/src/test/resources + // This is for "Good/BarTest (test.dir)", i.e., running single test from inside Eclipse + // root is used as a default if the test.dir property is not present + public static Collection checkTestDirProperty(boolean isBadTest, String root) + { + String dir = System.getProperty(Harness.TEST_DIR_FLAG); + if (dir == null) + { + dir = ClassLoader.getSystemResource(root).getFile(); + } + return makeTests(isBadTest, dir); + } +} diff --git a/scribble-test/src/test/java/org/scribble/test/IgnoredDirectoryWhenFilter.java b/scribble-test/src/test/java/org/scribble/test/IgnoredDirectoryWhenFilter.java new file mode 100644 index 000000000..8e034c56a --- /dev/null +++ b/scribble-test/src/test/java/org/scribble/test/IgnoredDirectoryWhenFilter.java @@ -0,0 +1,35 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.test; + +import java.io.File; +import java.io.FileFilter; + +import org.apache.commons.io.filefilter.AbstractFileFilter; + +public class IgnoredDirectoryWhenFilter extends AbstractFileFilter { + private final FileFilter filter; + + public IgnoredDirectoryWhenFilter(FileFilter filter) { + this.filter = filter; + } + + @Override + public boolean accept(File file) { + if (!file.isDirectory()) { + return false; + } + return file.listFiles(filter).length == 0; + } +} diff --git a/scribble-test/src/test/java/org/scribble/test/JavaProcessBuilder.java b/scribble-test/src/test/java/org/scribble/test/JavaProcessBuilder.java new file mode 100644 index 000000000..40f35b6bf --- /dev/null +++ b/scribble-test/src/test/java/org/scribble/test/JavaProcessBuilder.java @@ -0,0 +1,134 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.test; + +import java.io.File; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; +import java.util.Map.Entry; + +@Deprecated +public class JavaProcessBuilder { + private String jvm; + private Collection classpath = new ArrayList<>(); + private String javaAgent; + private String javaAgentArgs; + private String program; + private Collection programArgs = new ArrayList<>(); + private Map systemProps = new HashMap<>(); + public JavaProcessBuilder(String jvm, String program) { + this.jvm = jvm; + this.program = program; + } + public JavaProcessBuilder(String program) { + this("java", program); + } + public String getJvm() { + return jvm; + } + public void setJvm(String jvm) { + this.jvm = jvm; + } + public void setProgram(String program) { + this.program = program; + } + public String getProgram() { + return program; + } + public void appendClasspath(String param) { + classpath.add(param); + } + public void appendProgramArgument(String arg) { + programArgs.add(arg); + } + public void setJavaAgent(String param) { + this.javaAgent = param; + } + public String getJavaAgent() { + return javaAgent; + } + public void setJavaAgentArgs(String javaAgentArgs) { + this.javaAgentArgs = javaAgentArgs; + } + public String getJavaAgentArgs() { + return javaAgentArgs; + } + + public void setSystemProperty(String key) { + setSystemProperty(key, null); + } + + public void setSystemProperty(String key, String value) { + systemProps.put(key, value); + } + + public void unsetSystemProperty(String key) { + systemProps.remove(key); + } + + private String buildClasspath() { + return ExecUtil.join(File.pathSeparator, classpath); + } + + private String buildJavaAgent() { + StringBuilder builder = new StringBuilder("-javaagent:"); + builder.append(javaAgent); + if (javaAgentArgs != null) { + builder.append('='); + builder.append(javaAgentArgs); + } + return builder.toString(); + } + + public String[] build() { + Collection result = new ArrayList<>(); + result.add(jvm); + if (classpath.size() > 0) { + result.add("-cp"); + result.add(buildClasspath()); + } + if (javaAgent != null) { + result.add(buildJavaAgent()); + } + buildSystemProperties(result); + result.add(program); + result.addAll(programArgs); + return result.toArray(new String[0]); + } + private void buildSystemProperties(Collection result) { + for (Entry entry : systemProps.entrySet()) { + StringBuilder builder = new StringBuilder(); + builder.append("-D"); + builder.append(entry.getKey()); + if (entry.getValue() != null) { + builder.append("="); + builder.append(entry.getValue()); + } + result.add(builder.toString()); + } + } + public void setSystemProperties(Properties props) { + systemProps.clear(); + for (String key : props.stringPropertyNames()) { + systemProps.put(key, props.getProperty(key)); + } + } + @Override + public String toString() { + return ExecUtil.join(" ", build()); + } +} \ No newline at end of file diff --git a/scribble-test/src/test/java/org/scribble/test/ScribAllTest.java b/scribble-test/src/test/java/org/scribble/test/ScribAllTest.java new file mode 100644 index 000000000..47afda3cf --- /dev/null +++ b/scribble-test/src/test/java/org/scribble/test/ScribAllTest.java @@ -0,0 +1,49 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.test; + +import java.util.Collection; +import java.util.LinkedList; +import java.util.List; + +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.junit.runners.Parameterized.Parameters; + +/** + * Runs all tests under good and bad root directories in Scribble. + * + * N.B. Currently in exclude list of root pom surefire config. + */ +//@RunWith(value = Parameterized.class) +@RunWith(Parameterized.class) +public class ScribAllTest extends ScribTestBase +{ + public ScribAllTest(String example, boolean isBadTest) + { + super(example, isBadTest); + } + + @Parameters(name = "{0}") + public static Collection data() + { + // Test all tests under good and bad root directories + String dir_good = ClassLoader.getSystemResource(ScribGoodTest.GOOD_DIR).getFile(); + String dir_bad = ClassLoader.getSystemResource(ScribBadTest.BAD_DIR).getFile(); + List result = new LinkedList<>(); + result.addAll(Harness.makeTests(ScribTestBase.GOOD_TEST, dir_good)); + result.addAll(Harness.makeTests(ScribTestBase.BAD_TEST, dir_bad)); + return result; + } +} diff --git a/scribble-test/src/test/java/org/scribble/test/ScribBadTest.java b/scribble-test/src/test/java/org/scribble/test/ScribBadTest.java new file mode 100644 index 000000000..ae15719e1 --- /dev/null +++ b/scribble-test/src/test/java/org/scribble/test/ScribBadTest.java @@ -0,0 +1,40 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.test; + +import java.util.Collection; + +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.junit.runners.Parameterized.Parameters; + +// For running all tests under the specified directory as bad tests +// Needs -Dtest.dir=[test root dir] system property -- Eclipse VM arg: -Dtest.dir=${selected_resource_loc} +//@RunWith(value = Parameterized.class) +@RunWith(Parameterized.class) +public class ScribBadTest extends ScribTestBase +{ + protected static final String BAD_DIR = "bad"; + + public ScribBadTest(String example, boolean isBadTest) + { + super(example, isBadTest); + } + + @Parameters(name = "{0}") + public static Collection data() + { + return Harness.checkTestDirProperty(ScribTestBase.BAD_TEST, ScribBadTest.BAD_DIR); + } +} diff --git a/scribble-test/src/test/java/org/scribble/test/ScribGoodTest.java b/scribble-test/src/test/java/org/scribble/test/ScribGoodTest.java new file mode 100644 index 000000000..22203cc43 --- /dev/null +++ b/scribble-test/src/test/java/org/scribble/test/ScribGoodTest.java @@ -0,0 +1,41 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.test; + +import java.util.Collection; + +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.junit.runners.Parameterized.Parameters; + +// For running all tests under the specified directory as good tests +// Needs -Dtest.dir=[test root dir] system property -- Eclipse VM arg: -Dtest.dir=${selected_resource_loc} +@RunWith(value = Parameterized.class) +public class ScribGoodTest extends ScribTestBase +{ + protected static final String GOOD_DIR = "good"; + + public ScribGoodTest(String example, boolean isBadTest) + { + super(example, isBadTest); + } + + @Parameters(name = "{0}") + public static Collection data() + { + //String dir = ClassLoader.getSystemResource(AllTest.GOOD_ROOT).getFile(); // No: checkTestDirProperty does this + String dir = ScribGoodTest.GOOD_DIR; + return Harness.checkTestDirProperty(ScribTestBase.GOOD_TEST, dir); + } +} diff --git a/scribble-test/src/test/java/org/scribble/test/ScribTestBase.java b/scribble-test/src/test/java/org/scribble/test/ScribTestBase.java new file mode 100644 index 000000000..2780a3fbf --- /dev/null +++ b/scribble-test/src/test/java/org/scribble/test/ScribTestBase.java @@ -0,0 +1,122 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package org.scribble.test; + +import java.io.File; +import java.io.IOException; +import java.util.concurrent.ExecutionException; + +import org.junit.Assert; +import org.junit.Test; +import org.scribble.cli.CLFlags; +import org.scribble.cli.CommandLine; +import org.scribble.cli.CommandLineException; +import org.scribble.util.AntlrSourceException; +import org.scribble.util.ScribException; + +/* + * Packaging following pattern of putting tests into same package but different directory as classes being tested: + * (in this case, testing org.scribble.cli.CommandLine -- but this essentially tests most of core/parser) + */ +public abstract class ScribTestBase +{ + protected static int NUM_SKIPPED = 0; // HACK + + protected static final boolean GOOD_TEST = false; + protected static final boolean BAD_TEST = !GOOD_TEST; + + protected final String example; + protected final boolean isBadTest; + + // relative to scribble-test/src/test/resources (or target/test-classes/) + protected static final String TEST_ROOT_DIR = "."; // FIXME: make relative to scribble-java root (for subclasses in extension modules) + + public ScribTestBase(String example, boolean isBadTest) + { + this.example = example; + this.isBadTest = isBadTest; + } + + protected String getTestRootDir() + { + return ScribTestBase.TEST_ROOT_DIR; + } + + protected String[] getSkipList() + { + return new String[0]; + } + + protected boolean checkSkip() + { + String[] SKIP = getSkipList(); + String tmp = this.example.replace("\\", "/"); + for (String skip : SKIP) + { + if (tmp.endsWith(skip)) + { + ScribTestBase.NUM_SKIPPED++; + System.out.println("[scrib-test] Test on skip-list: " + this.example + " (" + ScribTestBase.NUM_SKIPPED + " skipped.)"); + return true; + } + } + return false; + } + + protected void runTest(String dir) throws CommandLineException, AntlrSourceException + { + new CommandLine(this.example, CLFlags.JUNIT_FLAG, CLFlags.IMPORT_PATH_FLAG, dir).run(); + // Added JUNIT flag -- but for some reason only bad DoArgList01.scr was breaking without it... + } + + @Test + public void tests() throws IOException, InterruptedException, ExecutionException + { + if (checkSkip()) + { + return; + } + + // TODO: For now just locate classpath for resources -- later maybe directly execute job + /*URL url = ClassLoader.getSystemResource(AllTest.GOOD_ROOT); // Assume good/bad have same parent + String dir = url.getFile().substring(0, url.getFile().length() - ("/" + AllTest.GOOD_ROOT).length());*/ + String dir = ClassLoader.getSystemResource(getTestRootDir()).getFile(); + if (File.separator.equals("\\")) // HACK: Windows + { + dir = dir.substring(1).replace("/", "\\"); + } + + try + { + // FIXME: read runtime arguments from a config file, e.g. -oldwf, -fair, etc + // Also need a way to specify expected tool output (e.g. projections/EFSMs for good, errors for bad) + //new CommandLine(this.example, CLArgParser.JUNIT_FLAG, CLArgParser.IMPORT_PATH_FLAG, dir).run(); + // Added JUNIT flag -- but for some reason only bad DoArgList01.scr was breaking without it... + runTest(dir); + Assert.assertFalse("Expecting exception", this.isBadTest); + } + catch (ScribException e) + { + Assert.assertTrue("Unexpected exception '" + e.getMessage() + "'", this.isBadTest); + } + catch (CommandLineException e) + { + throw new RuntimeException(e); + } + catch (Exception e) // Includes AntlrSourceExceptions that are not ScribbleExceptions -- hacky? + { + throw new RuntimeException(e); + } + } +} diff --git a/scribble-test/src/test/resources/bad/efsm/grecursion/unfair/Test01.scr b/scribble-test/src/test/resources/bad/efsm/grecursion/unfair/Test01.scr new file mode 100644 index 000000000..42fb6de49 --- /dev/null +++ b/scribble-test/src/test/resources/bad/efsm/grecursion/unfair/Test01.scr @@ -0,0 +1,40 @@ +//$ bin/scribblec.sh -ip scribble-test/src/test/resources scribble-test/src/test/resources/bad/efsm/grecursion/unfair/Test01.scr + +module bad.efsm.grecursion.unfair.Test01; + + +// OK if -fair +// Also tests GraphBuilderUtil addContinueEdge (addEdge vs. addEdgeAux) AllTest/BadTest problem +global protocol Proto1(role A, role B, role C) +{ + rec Y + { + choice at A + { + rec X + { + choice at A + { + 1() from A to B; + continue X; + } + or + { + 2() from A to C; + continue Y; + } + or + { + 3() from A to B; + 3() from A to C; + } + } + } + or + { + 4() from A to B; + continue Y; + } + } +} + diff --git a/scribble-test/src/test/resources/bad/efsm/grecursion/unfair/Test06.scr b/scribble-test/src/test/resources/bad/efsm/grecursion/unfair/Test06.scr new file mode 100644 index 000000000..f2669e6b1 --- /dev/null +++ b/scribble-test/src/test/resources/bad/efsm/grecursion/unfair/Test06.scr @@ -0,0 +1,30 @@ +//$ bin/scribblec.sh scribble-test/src/test/resources/bad/efsm/grecursion/unfair/Test06.scr + +module bad.efsm.grecursion.unfair.Test06; + + +global protocol Proto1(role A, role B, role C) +{ + choice at A // OK if -fair + { + 1() from A to B; + do Proto1Aux1(A, B, C); + } + or + { + do Proto1Aux2(A, B, C); + } +} + +aux global protocol Proto1Aux1(role A, role B, role C) +{ + do Proto1(A, B, C); +} + +aux global protocol Proto1Aux2(role A, role B, role C) +{ + 2() from A to B; + 3() from B to C; + do Proto1(A, B, C); +} + diff --git a/scribble-test/src/test/resources/bad/efsm/grecursion/unfair/Test11b.scr b/scribble-test/src/test/resources/bad/efsm/grecursion/unfair/Test11b.scr new file mode 100644 index 000000000..16750ac7d --- /dev/null +++ b/scribble-test/src/test/resources/bad/efsm/grecursion/unfair/Test11b.scr @@ -0,0 +1,29 @@ +//$ bin/scribblec.sh -ip scribble-test/src/test/resources scribble-test/src/test/resources/bad/efsm/grecursion/unfair/Test11b.scr + +module bad.efsm.grecursion.unfair.Test11b; + + +// OK if -fair +global protocol Proto1(role A, role B, role C) +{ + rec X + { + choice at A + { + 1() from A to B; + choice at B + { + 2() from B to A; + //4() from B to C; // Testing EFSM building + continue X; + } + or + { + 3() from B to A; + 4() from B to C; + continue X; + } + } + } +} + diff --git a/scribble-test/src/test/resources/bad/efsm/grecursion/unfair/Test11c.scr b/scribble-test/src/test/resources/bad/efsm/grecursion/unfair/Test11c.scr new file mode 100644 index 000000000..77b731781 --- /dev/null +++ b/scribble-test/src/test/resources/bad/efsm/grecursion/unfair/Test11c.scr @@ -0,0 +1,24 @@ +module bad.efsm.grecursion.unfair.Test11c; + + +global protocol Proto1(role A, role B, role C) +{ + rec X + { + choice at A + { + 1() from A to B; + choice at B + { + 2() from B to A; + } + or + { + 3() from B to A; + 4() from B to C; + } + continue X; + } + } +} + diff --git a/scribble-test/src/test/resources/bad/liveness/messagelive/Test01.scr b/scribble-test/src/test/resources/bad/liveness/messagelive/Test01.scr new file mode 100644 index 000000000..7090e7ab0 --- /dev/null +++ b/scribble-test/src/test/resources/bad/liveness/messagelive/Test01.scr @@ -0,0 +1,25 @@ +//$ bin/scribblec.sh -ip scribble-test/src/test/resources scribble-test/src/test/resources/bad/liveness/messagelive/Test01.scr + +module bad.liveness.messagelive.Test01; + + +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + 1() from A to B; // Bad: testing deadlock detection (input blocked -> terminated) + 2() from A to B; // Message liveness -- also counterpart wait-for + 2() from B to C; + } + or + { + 1() from A to B; + rec X + { + // NB: not a role progress problem: A is already done by here + 4() from B to C; + 5() from C to B; + continue X; + } + } +} diff --git a/scribble-test/src/test/resources/bad/liveness/messagelive/Test02.scr b/scribble-test/src/test/resources/bad/liveness/messagelive/Test02.scr new file mode 100644 index 000000000..575283d0f --- /dev/null +++ b/scribble-test/src/test/resources/bad/liveness/messagelive/Test02.scr @@ -0,0 +1,20 @@ +module bad.liveness.messagelive.Test02; + + +global protocol Proto1(role A, role B, role C) +{ + 1() from A to B; + choice at B + { + rec X + { + 2() from B to C; + continue X; + } + } + or + { + 3() from B to C; + } + 4() from A to C; +} diff --git a/scribble-test/src/test/resources/bad/liveness/messagelive/Test03a.scr b/scribble-test/src/test/resources/bad/liveness/messagelive/Test03a.scr new file mode 100644 index 000000000..81381a08b --- /dev/null +++ b/scribble-test/src/test/resources/bad/liveness/messagelive/Test03a.scr @@ -0,0 +1,22 @@ +module bad.liveness.messagelive.Test03a; + + +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + rec X + { + choice at A + { + 1() from A to B; + continue X; + } + } + } + or + { + 2() from A to B; + } + 2() from C to B; +} diff --git a/scribble-test/src/test/resources/bad/liveness/messagelive/unfair/Test03b.scr b/scribble-test/src/test/resources/bad/liveness/messagelive/unfair/Test03b.scr new file mode 100644 index 000000000..3632f5425 --- /dev/null +++ b/scribble-test/src/test/resources/bad/liveness/messagelive/unfair/Test03b.scr @@ -0,0 +1,27 @@ +module bad.liveness.messagelive.unfair.Test03b; + + +// Cf. bad.liveness.messagelive.Test03a +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + rec X + { + choice at A + { + 1() from A to B; + continue X; + } + or + { + () from A to B; + } + } + } + or + { + 2() from A to B; + } + 2() from C to B; // OK if -fair +} diff --git a/scribble-test/src/test/resources/bad/liveness/roleprog/Test01.scr b/scribble-test/src/test/resources/bad/liveness/roleprog/Test01.scr new file mode 100644 index 000000000..c7ae97263 --- /dev/null +++ b/scribble-test/src/test/resources/bad/liveness/roleprog/Test01.scr @@ -0,0 +1,21 @@ +module bad.liveness.roleprog.Test01; + + +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + rec X // Fairness irrelevant + { + 1() from A to B; + //1() from A to C; + continue X; + } + } + or + { + 2() from A to B; + 2() from A to C; // "role liveness" + } +} + diff --git a/scribble-test/src/test/resources/bad/liveness/roleprog/Test02.scr b/scribble-test/src/test/resources/bad/liveness/roleprog/Test02.scr new file mode 100644 index 000000000..9b1b63e27 --- /dev/null +++ b/scribble-test/src/test/resources/bad/liveness/roleprog/Test02.scr @@ -0,0 +1,20 @@ +module bad.liveness.roleprog.Test02; + + +global protocol Proto1(role A, role B, role C) +{ + 1() from A to B; + choice at B + { + rec X + { + 2() from B to C; + continue X; + } + } + or + { + 3() from B to C; + } + 4() from C to A; +} diff --git a/scribble-test/src/test/resources/bad/liveness/roleprog/Test03a.scr b/scribble-test/src/test/resources/bad/liveness/roleprog/Test03a.scr new file mode 100644 index 000000000..7d25a753c --- /dev/null +++ b/scribble-test/src/test/resources/bad/liveness/roleprog/Test03a.scr @@ -0,0 +1,22 @@ +module bad.liveness.roleprog.Test03a; + + +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + rec X + { + choice at A + { + 1() from A to B; + continue X; + } + } + } + or + { + 2() from A to B; + 2() from B to C; // Role progress violation for C + } +} diff --git a/scribble-test/src/test/resources/bad/liveness/roleprog/Test03b.scr b/scribble-test/src/test/resources/bad/liveness/roleprog/Test03b.scr new file mode 100644 index 000000000..80505f481 --- /dev/null +++ b/scribble-test/src/test/resources/bad/liveness/roleprog/Test03b.scr @@ -0,0 +1,26 @@ +module bad.liveness.roleprog.Test03b; + + +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + rec X + { + choice at A + { + 1() from A to B; + continue X; + } + or + { + () from A to B; // Also wait-for error at C -- tests projected choice case pruning (for C) + } + } + } + or + { + 2() from A to B; + 2() from B to C; // Role progress violation for C + } +} diff --git a/scribble-test/src/test/resources/bad/liveness/roleprog/unfair/Test01.scr b/scribble-test/src/test/resources/bad/liveness/roleprog/unfair/Test01.scr new file mode 100644 index 000000000..511a7dfe3 --- /dev/null +++ b/scribble-test/src/test/resources/bad/liveness/roleprog/unfair/Test01.scr @@ -0,0 +1,22 @@ +module bad.liveness.roleprog.unfair.Test01; + + +// OK if -fair +global protocol Proto1(role A, role B, role C) +{ + rec X + { + choice at A + { + 1() from A to B; + 1() from B to C; + } + or + { + 2() from A to B; + //4() from B to C; + continue X; + } + } +} + diff --git a/scribble-test/src/test/resources/bad/liveness/roleprog/unfair/Test02.scr b/scribble-test/src/test/resources/bad/liveness/roleprog/unfair/Test02.scr new file mode 100644 index 000000000..643ba5c8c --- /dev/null +++ b/scribble-test/src/test/resources/bad/liveness/roleprog/unfair/Test02.scr @@ -0,0 +1,24 @@ +module bad.liveness.roleprog.unfair.Test02; + + +// OK if -fair +// Cf. good.wfchoice.gchoice.Choice11; +global protocol Proto1(role A, role B, role C) +{ + rec X + { + 1() from A to C; // bad liveness + choice at A + { + 1() from A to C; + continue X; + } + or + { + 2() from A to B; + 2() from A to C; + } + } +} + + diff --git a/scribble-test/src/test/resources/bad/liveness/roleprog/unfair/Test03a.scr b/scribble-test/src/test/resources/bad/liveness/roleprog/unfair/Test03a.scr new file mode 100644 index 000000000..d76b30397 --- /dev/null +++ b/scribble-test/src/test/resources/bad/liveness/roleprog/unfair/Test03a.scr @@ -0,0 +1,23 @@ +module bad.liveness.roleprog.unfair.Test03a; + + +global protocol Proto1(role A, role B, role C) +{ + rec X + { + choice at A + { + 1() from A to B; + 1() from A to C; + continue X; + } + or + { + 2() from A to B; + continue X; + } + //continue X; + } +} + + diff --git a/scribble-test/src/test/resources/bad/liveness/roleprog/unfair/Test03b.scr b/scribble-test/src/test/resources/bad/liveness/roleprog/unfair/Test03b.scr new file mode 100644 index 000000000..3587efe15 --- /dev/null +++ b/scribble-test/src/test/resources/bad/liveness/roleprog/unfair/Test03b.scr @@ -0,0 +1,23 @@ +module bad.liveness.roleprog.unfair.Test03b; + + +global protocol Proto1(role A, role B, role C) +{ + rec X + { + choice at A + { + 1() from A to B; + 1() from A to C; + //continue X; + } + or + { + 2() from A to B; + //continue X; + } + continue X; + } +} + + diff --git a/scribble-test/src/test/resources/bad/liveness/roleprog/unfair/Test04a.scr b/scribble-test/src/test/resources/bad/liveness/roleprog/unfair/Test04a.scr new file mode 100644 index 000000000..786f171bb --- /dev/null +++ b/scribble-test/src/test/resources/bad/liveness/roleprog/unfair/Test04a.scr @@ -0,0 +1,38 @@ +module bad.liveness.roleprog.unfair.Test04a; + + +global protocol Proto1(role A, role B, role C, role D) +{ + // OK if -fair + choice at A + { + 1() from A to B; + rec X + { + 1() from A to B; + choice at B + { + 2() from B to C; + choice at C + { + 2() from C to A; + continue X; + } + or + { + 3() from C to A; + 3() from C to D; + continue X; + } + } + } + } + or + { + 0() from A to B; + 0() from B to C; + 0() from C to D; + } +} + + diff --git a/scribble-test/src/test/resources/bad/liveness/roleprog/unfair/Test04b.scr b/scribble-test/src/test/resources/bad/liveness/roleprog/unfair/Test04b.scr new file mode 100644 index 000000000..972a82504 --- /dev/null +++ b/scribble-test/src/test/resources/bad/liveness/roleprog/unfair/Test04b.scr @@ -0,0 +1,37 @@ +module bad.liveness.roleprog.unfair.Test04b; + + +global protocol Proto1(role A, role B, role C, role D) +{ + // OK if -fair + choice at A + { + 1() from A to B; + rec X + { + 1() from A to B; + choice at B + { + 2() from B to C; + choice at C + { + 2() from C to A; + } + or + { + 3() from C to A; + 3() from C to D; + } + continue X; + } + } + } + or + { + 0() from A to B; + 0() from B to C; + 0() from C to D; + } +} + + diff --git a/scribble-test/src/test/resources/bad/liveness/roleprog/unfair/Test05.scr b/scribble-test/src/test/resources/bad/liveness/roleprog/unfair/Test05.scr new file mode 100644 index 000000000..85271df0c --- /dev/null +++ b/scribble-test/src/test/resources/bad/liveness/roleprog/unfair/Test05.scr @@ -0,0 +1,26 @@ +module bad.liveness.roleprog.unfair.Test05; + + +global protocol Proto1(role A, role B, role C, role D) +{ + choice at A + { + 1() from A to B; + rec X + { + 2() from B to C; + choice at C + { + 2() from C to A; + } + or + { + () from C to A; + () from C to D; + } + continue X; // OK if -fair + } + } +} + + diff --git a/scribble-test/src/test/resources/bad/liveness/roleprog/unfair/Test06.scr b/scribble-test/src/test/resources/bad/liveness/roleprog/unfair/Test06.scr new file mode 100644 index 000000000..24414f745 --- /dev/null +++ b/scribble-test/src/test/resources/bad/liveness/roleprog/unfair/Test06.scr @@ -0,0 +1,31 @@ +//$ bin/scribblec.sh scribble-test/src/test/resources/bad/liveness/roleprog/unfair/Test06.scr + +module bad.liveness.roleprog.unfair.Test06; + + +// Duplicate of bad.efsm.unfair.Test06 +global protocol Proto1(role A, role B, role C) +{ + choice at A // OK if -fair + { + 1() from A to B; + do Proto1Aux1(A, B, C); + } + or + { + do Proto1Aux2(A, B, C); + } +} + +aux global protocol Proto1Aux1(role A, role B, role C) +{ + do Proto1(A, B, C); +} + +aux global protocol Proto1Aux2(role A, role B, role C) +{ + 2() from A to B; + 3() from B to C; + do Proto1(A, B, C); +} + diff --git a/scribble-test/src/test/resources/bad/reach/globals/gchoice/Test01.scr b/scribble-test/src/test/resources/bad/reach/globals/gchoice/Test01.scr new file mode 100644 index 000000000..fb9ff2271 --- /dev/null +++ b/scribble-test/src/test/resources/bad/reach/globals/gchoice/Test01.scr @@ -0,0 +1,21 @@ +module bad.reach.globals.gchoice.Test01; + + +global protocol Proto1(role A, role B, role C) +{ + rec X + { + choice at A + { + 1() from A to B; + 1() from B to A; + continue X; + } + or + { + // Bad: (empty) case pruned, so reachability fails (no "optional") + } + } + 2() from A to B; + 3() from B to C; +} diff --git a/scribble-test/src/test/resources/bad/reach/globals/gdo/Test01a.scr b/scribble-test/src/test/resources/bad/reach/globals/gdo/Test01a.scr new file mode 100644 index 000000000..0bfd3e9bc --- /dev/null +++ b/scribble-test/src/test/resources/bad/reach/globals/gdo/Test01a.scr @@ -0,0 +1,16 @@ +module bad.reach.globals.gdo.Test01a; + + +global protocol Proto1(role A, role B) +{ + 1() from A to B; + do Proto1(A, B); + 3() from A to B; +} + +aux global protocol Proto2(role C, role D) +{ + 2() from C to D; + do Proto2(C, D); + //2() from C to D; +} diff --git a/scribble-test/src/test/resources/bad/reach/globals/gdo/Test01b.scr b/scribble-test/src/test/resources/bad/reach/globals/gdo/Test01b.scr new file mode 100644 index 000000000..a3965c9ae --- /dev/null +++ b/scribble-test/src/test/resources/bad/reach/globals/gdo/Test01b.scr @@ -0,0 +1,17 @@ +module bad.reach.globals.gdo.Test01b; + + +//aux +global protocol Proto1(role A, role B) +{ + 1() from A to B; + do Proto1(A, B); + 3() from A to B; +} + +global protocol Proto2(role C, role D) +{ + 2() from C to D; + do Proto2(C, D); + //2() from C to D; +} diff --git a/scribble-test/src/test/resources/bad/reach/globals/gdo/Test02a.scr b/scribble-test/src/test/resources/bad/reach/globals/gdo/Test02a.scr new file mode 100644 index 000000000..5f129d9ed --- /dev/null +++ b/scribble-test/src/test/resources/bad/reach/globals/gdo/Test02a.scr @@ -0,0 +1,17 @@ +module bad.reach.globals.gdo.Test02a; + + +global protocol Proto1(role A, role B) +{ + 1() from A to B; + do Proto1(A, B); + //3() from A to B; +} + +//aux +global protocol Proto2(role C, role D) +{ + 2() from C to D; + do Proto2(C, D); + 2() from C to D; +} diff --git a/scribble-test/src/test/resources/bad/reach/globals/gdo/Test02b.scr b/scribble-test/src/test/resources/bad/reach/globals/gdo/Test02b.scr new file mode 100644 index 000000000..37a569197 --- /dev/null +++ b/scribble-test/src/test/resources/bad/reach/globals/gdo/Test02b.scr @@ -0,0 +1,16 @@ +module bad.reach.globals.gdo.Test02b; + + +aux global protocol Proto1(role A, role B) +{ + 1() from A to B; + do Proto1(A, B); + //3() from A to B; +} + +global protocol Proto2(role C, role D) +{ + 2() from C to D; + do Proto2(C, D); + 2() from C to D; +} diff --git a/scribble-test/src/test/resources/bad/reach/globals/gdo/Test03.scr b/scribble-test/src/test/resources/bad/reach/globals/gdo/Test03.scr new file mode 100644 index 000000000..938e92979 --- /dev/null +++ b/scribble-test/src/test/resources/bad/reach/globals/gdo/Test03.scr @@ -0,0 +1,13 @@ +module bad.reach.globals.gdo.Test03; + + +import bad.reach.globals.gdo.pack1.Test03b; + + +global protocol Foo(role A, role B) +{ + 1() from A to B; + do bad.reach.globals.gdo.pack1.Test03b.Bar(A, B); + 2() from A to B; +} + diff --git a/scribble-test/src/test/resources/bad/reach/globals/gdo/Test04.scr b/scribble-test/src/test/resources/bad/reach/globals/gdo/Test04.scr new file mode 100644 index 000000000..82926a113 --- /dev/null +++ b/scribble-test/src/test/resources/bad/reach/globals/gdo/Test04.scr @@ -0,0 +1,16 @@ +module bad.reach.globals.gdo.Test04; + + +global protocol Foo(role A, role B) +{ + choice at A + { + 1() from A to B; + } + or + { + do Foo(A, B); // Unguarded gets unfolded.. + 2() from A to B; // ..becomes unreachable after continue once unfolded + } +} + diff --git a/scribble-test/src/test/resources/bad/reach/globals/gdo/Test04a.scr b/scribble-test/src/test/resources/bad/reach/globals/gdo/Test04a.scr new file mode 100644 index 000000000..18e9c0809 --- /dev/null +++ b/scribble-test/src/test/resources/bad/reach/globals/gdo/Test04a.scr @@ -0,0 +1,16 @@ +module bad.reach.globals.gdo.Test04a; + + +global protocol Foo(role A, role B) +{ + choice at A + { + do Foo(A, B); // Unguarded gets unfolded.. + 2() from A to B; // ..becomes unreachable after continue once unfolded + } + or + { + 1() from A to B; + } +} + diff --git a/scribble-test/src/test/resources/bad/reach/globals/gdo/Test05a.scr b/scribble-test/src/test/resources/bad/reach/globals/gdo/Test05a.scr new file mode 100644 index 000000000..94889b91d --- /dev/null +++ b/scribble-test/src/test/resources/bad/reach/globals/gdo/Test05a.scr @@ -0,0 +1,16 @@ +module bad.reach.globals.gdo.Test05a; + + +global protocol Foo(role A, role B) +{ + choice at A + { + 1() from A to B; + do Foo(A, B); + 3() from A to B; + } or { + 2() from A to B; + 3() from A to B; + } +} + diff --git a/scribble-test/src/test/resources/bad/reach/globals/gdo/Test05b.scr b/scribble-test/src/test/resources/bad/reach/globals/gdo/Test05b.scr new file mode 100644 index 000000000..5cff1758f --- /dev/null +++ b/scribble-test/src/test/resources/bad/reach/globals/gdo/Test05b.scr @@ -0,0 +1,16 @@ +module bad.reach.globals.gdo.Test05b; + + +global protocol Foo(role A, role B) +{ + choice at A + { + 1() from A to B; + do Foo(A, B); + } or { + 2() from A to B; + 3() from A to B; + } + 3() from A to B; +} + diff --git a/scribble-test/src/test/resources/bad/reach/globals/gdo/Test06a.scr b/scribble-test/src/test/resources/bad/reach/globals/gdo/Test06a.scr new file mode 100644 index 000000000..8b95fb77b --- /dev/null +++ b/scribble-test/src/test/resources/bad/reach/globals/gdo/Test06a.scr @@ -0,0 +1,23 @@ +module bad.reach.globals.gdo.Test06a; + + +global protocol Foo(role A, role B) +{ + choice at A + { + 1() from A to B; + do Foo(A, B); + do Bar(A, B); + } + or + { + do Bar(A, B); + } +} + +global protocol Bar(role C, role D) +{ + 5() from C to D; + do Bar(C, D); +} + diff --git a/scribble-test/src/test/resources/bad/reach/globals/gdo/Test06b.scr b/scribble-test/src/test/resources/bad/reach/globals/gdo/Test06b.scr new file mode 100644 index 000000000..30375c45f --- /dev/null +++ b/scribble-test/src/test/resources/bad/reach/globals/gdo/Test06b.scr @@ -0,0 +1,23 @@ +module bad.reach.globals.gdo.Test06b; + + +global protocol Foo(role A, role B) +{ + choice at A + { + 1() from A to B; + do Bar(A, B); + do Foo(A, B); + } + or + { + do Bar(A, B); + } +} + +global protocol Bar(role C, role D) +{ + 5() from C to D; + do Bar(C, D); +} + diff --git a/scribble-test/src/test/resources/bad/reach/globals/gdo/Test06c.scr b/scribble-test/src/test/resources/bad/reach/globals/gdo/Test06c.scr new file mode 100644 index 000000000..e65290b92 --- /dev/null +++ b/scribble-test/src/test/resources/bad/reach/globals/gdo/Test06c.scr @@ -0,0 +1,23 @@ +module bad.reach.globals.gdo.Test06c; + + +global protocol Foo(role A, role B) +{ + choice at A + { + 1() from A to B; + do Foo(A, B); + do Bar(A, B); + } + or + { + do Bar(A, B); + } +} + +global protocol Bar(role C, role D) +{ + 5() from C to D; + do Bar(C, D); +} + diff --git a/scribble-test/src/test/resources/bad/reach/globals/gdo/Test06d.scr b/scribble-test/src/test/resources/bad/reach/globals/gdo/Test06d.scr new file mode 100644 index 000000000..370ae7ffc --- /dev/null +++ b/scribble-test/src/test/resources/bad/reach/globals/gdo/Test06d.scr @@ -0,0 +1,23 @@ +module bad.reach.globals.gdo.Test06d; + + +global protocol Foo(role A, role B) +{ + choice at A + { + 1() from A to B; + do Foo(A, B); + } + or + { + do Bar(A, B); + do Foo(A, B); + } +} + +global protocol Bar(role C, role D) +{ + 5() from C to D; + do Bar(C, D); +} + diff --git a/scribble-test/src/test/resources/bad/reach/globals/gdo/Test06e.scr b/scribble-test/src/test/resources/bad/reach/globals/gdo/Test06e.scr new file mode 100644 index 000000000..ba36b783a --- /dev/null +++ b/scribble-test/src/test/resources/bad/reach/globals/gdo/Test06e.scr @@ -0,0 +1,23 @@ +module bad.reach.globals.gdo.Test06e; + + +global protocol Foo(role A, role B) +{ + choice at A + { + 1() from A to B; + do Foo(A, B); // No continuation after this choice permitted, will become non tail recursive once inlined + } + or + { + 2() from A to B; + } + 3() from A to B; +} + +global protocol Bar(role C, role D) +{ + 5() from C to D; + do Bar(C, D); +} + diff --git a/scribble-test/src/test/resources/bad/reach/globals/gdo/pack1/IGNORE b/scribble-test/src/test/resources/bad/reach/globals/gdo/pack1/IGNORE new file mode 100644 index 000000000..e69de29bb diff --git a/scribble-test/src/test/resources/bad/reach/globals/gdo/pack1/Test03b.scr b/scribble-test/src/test/resources/bad/reach/globals/gdo/pack1/Test03b.scr new file mode 100644 index 000000000..9cb890b48 --- /dev/null +++ b/scribble-test/src/test/resources/bad/reach/globals/gdo/pack1/Test03b.scr @@ -0,0 +1,12 @@ +module bad.reach.globals.gdo.pack1.Test03b; + + +import bad.reach.globals.gdo.Test03; + + +global protocol Bar(role C, role D) +{ + 3() from C to D; + do bad.reach.globals.gdo.Test03.Foo(C, D); +} + diff --git a/scribble-test/src/test/resources/bad/reach/globals/grecursion/Recursion01b.scr b/scribble-test/src/test/resources/bad/reach/globals/grecursion/Recursion01b.scr new file mode 100644 index 000000000..7a36ff8c3 --- /dev/null +++ b/scribble-test/src/test/resources/bad/reach/globals/grecursion/Recursion01b.scr @@ -0,0 +1,16 @@ +module bad.reach.globals.grecursion.Recursion01b; + + +global protocol Recursion1b(role A, role B) +{ + //rec A { } // Currently OK (role/recvar name clash). Disallow? + + rec X + { + l1() from A to B; + continue X; + //continue Y; // Uncomment bad, even if above line is commented + l2() from A to B; // Uncomment bad + } +} + diff --git a/scribble-test/src/test/resources/bad/reach/globals/grecursion/Recursion01c.scr b/scribble-test/src/test/resources/bad/reach/globals/grecursion/Recursion01c.scr new file mode 100644 index 000000000..385a55183 --- /dev/null +++ b/scribble-test/src/test/resources/bad/reach/globals/grecursion/Recursion01c.scr @@ -0,0 +1,20 @@ +module bad.reach.globals.grecursion.Recursion01c; + + +global protocol Recursion1c(role A, role B) +{ + rec X + { + choice at A + { + l1() from A to B; + continue X; + l2() from A to B; + } + or + { + l3() from A to B; + } + } +} + diff --git a/scribble-test/src/test/resources/bad/reach/globals/grecursion/Recursion03a.scr b/scribble-test/src/test/resources/bad/reach/globals/grecursion/Recursion03a.scr new file mode 100644 index 000000000..d03aa5c04 --- /dev/null +++ b/scribble-test/src/test/resources/bad/reach/globals/grecursion/Recursion03a.scr @@ -0,0 +1,19 @@ +module bad.reach.globals.grecursion.Recursion03a; + + +global protocol Recursion3a(role A, role B) +{ + rec X + { + l1() from A to B; + rec Y + { + l2() from B to A; + continue Y; + //continue X; // Uncomment OK if above line is commented + } + l3() from B to A; // Uncommemt bad + } + //l4() from B to A; // Uncomment bad +} + diff --git a/scribble-test/src/test/resources/bad/reach/globals/grecursion/Recursion03b.scr b/scribble-test/src/test/resources/bad/reach/globals/grecursion/Recursion03b.scr new file mode 100644 index 000000000..fe80c0509 --- /dev/null +++ b/scribble-test/src/test/resources/bad/reach/globals/grecursion/Recursion03b.scr @@ -0,0 +1,19 @@ +module bad.reach.globals.grecursion.Recursion03b; + + +global protocol Recursion3b(role A, role B) +{ + rec X + { + l1() from A to B; + rec Y + { + l2() from B to A; + continue Y; + //continue X; // Uncomment OK if above line is commented + } + //l3() from B to A; // Uncommemt bad + } + l4() from B to A; // Uncomment bad +} + diff --git a/scribble-test/src/test/resources/bad/reach/globals/grecursion/Recursion04b.scr b/scribble-test/src/test/resources/bad/reach/globals/grecursion/Recursion04b.scr new file mode 100644 index 000000000..98a856f2a --- /dev/null +++ b/scribble-test/src/test/resources/bad/reach/globals/grecursion/Recursion04b.scr @@ -0,0 +1,18 @@ +module bad.reach.globals.grecursion.Recursion04b; + + +global protocol Recursion4b(role A, role B) +{ + rec X + { + l1() from A to B; + rec Y + //rec X // Uncomment bad, even if above line is commented + { + l2() from B to A; + continue X; + continue Y; // Uncomment OK if the above line is commented + } + } +} + diff --git a/scribble-test/src/test/resources/bad/reach/globals/grecursion/Recursion05a.scr b/scribble-test/src/test/resources/bad/reach/globals/grecursion/Recursion05a.scr new file mode 100644 index 000000000..e5b76dddd --- /dev/null +++ b/scribble-test/src/test/resources/bad/reach/globals/grecursion/Recursion05a.scr @@ -0,0 +1,18 @@ +module bad.reach.globals.grecursion.Recursion05a; + + +global protocol Recursion5a(role A, role B) +{ + rec X + { + l1() from A to B; + continue X; // Uncomment makes the below rec bad + //continue Y; // Uncomment bad + } + rec Y + { + l2() from B to A; + continue Y; // A bad "continue X" here tested in Recursion11 + } +} + diff --git a/scribble-test/src/test/resources/bad/reach/globals/grecursion/Recursion06a.scr b/scribble-test/src/test/resources/bad/reach/globals/grecursion/Recursion06a.scr new file mode 100644 index 000000000..dfd631d0e --- /dev/null +++ b/scribble-test/src/test/resources/bad/reach/globals/grecursion/Recursion06a.scr @@ -0,0 +1,22 @@ +module bad.reach.globals.grecursion.Recursion06a; + + +global protocol Recursion6a(role A, role B) +{ + rec X + { + choice at A + { + l1() from A to B; + continue X; + l1() from A to B; // Uncomment bad + } + or + { + l2() from A to B; + } + //l3() from A to B; // Uncomment bad. "General recursion" issue ("unfold stacking"). Fix is to move inside the second choice block + } + l4() from A to B; +} + diff --git a/scribble-test/src/test/resources/bad/reach/globals/grecursion/Recursion06b.scr b/scribble-test/src/test/resources/bad/reach/globals/grecursion/Recursion06b.scr new file mode 100644 index 000000000..ee5e84564 --- /dev/null +++ b/scribble-test/src/test/resources/bad/reach/globals/grecursion/Recursion06b.scr @@ -0,0 +1,22 @@ +module bad.reach.globals.grecursion.Recursion06b; + + +global protocol Recursion6(role A, role B) +{ + rec X + { + choice at A + { + l1() from A to B; + continue X; + //l1() from A to B; // Uncomment bad + } + or + { + l2() from A to B; + } + l3() from A to B; // Uncomment bad. "General recursion" issue ("unfold stacking"). Fix is to move inside the second choice block + } + l4() from A to B; +} + diff --git a/scribble-test/src/test/resources/bad/reach/globals/grecursion/Recursion07a.scr b/scribble-test/src/test/resources/bad/reach/globals/grecursion/Recursion07a.scr new file mode 100644 index 000000000..525c561da --- /dev/null +++ b/scribble-test/src/test/resources/bad/reach/globals/grecursion/Recursion07a.scr @@ -0,0 +1,21 @@ +module bad.reach.globals.grecursion.Recursion07a; + + +global protocol Recursion7a(role A, role B) +{ + rec X + { + choice at A + { + l1() from A to B; + } + or + { + l2() from A to B; + } + continue X; + l3() from A to B; // Uncomment bad + } + //l3() from A to B; // Uncomment bad +} + diff --git a/scribble-test/src/test/resources/bad/reach/globals/grecursion/Recursion07b.scr b/scribble-test/src/test/resources/bad/reach/globals/grecursion/Recursion07b.scr new file mode 100644 index 000000000..fafa65a71 --- /dev/null +++ b/scribble-test/src/test/resources/bad/reach/globals/grecursion/Recursion07b.scr @@ -0,0 +1,21 @@ +module bad.reach.globals.grecursion.Recursion07b; + + +global protocol Recursion7b(role A, role B) +{ + rec X + { + choice at A + { + l1() from A to B; + } + or + { + l2() from A to B; + } + continue X; + //l3() from A to B; // Uncomment bad + } + l3() from A to B; // Uncomment bad +} + diff --git a/scribble-test/src/test/resources/bad/reach/globals/grecursion/Recursion08a.scr b/scribble-test/src/test/resources/bad/reach/globals/grecursion/Recursion08a.scr new file mode 100644 index 000000000..d4ca58747 --- /dev/null +++ b/scribble-test/src/test/resources/bad/reach/globals/grecursion/Recursion08a.scr @@ -0,0 +1,21 @@ +module bad.reach.globals.grecursion.Recursion08a; + + +global protocol Recursion8a(role A, role B) +{ + rec X + { + choice at A + { + l1() from A to B; + continue X; + } + or + { + l2() from A to B; + continue X; + } + } + l3() from A to B; +} + diff --git a/scribble-test/src/test/resources/bad/reach/globals/grecursion/Recursion08b.scr b/scribble-test/src/test/resources/bad/reach/globals/grecursion/Recursion08b.scr new file mode 100644 index 000000000..6ee8fbf15 --- /dev/null +++ b/scribble-test/src/test/resources/bad/reach/globals/grecursion/Recursion08b.scr @@ -0,0 +1,21 @@ +module bad.reach.globals.grecursion.Recursion08b; + + +global protocol Recursion8b(role A, role B) +{ + rec X + { + choice at A + { + l1() from A to B; + continue X; + } + or + { + l2() from A to B; + continue X; + } + l3() from A to B; + } +} + diff --git a/scribble-test/src/test/resources/bad/reach/globals/grecursion/Recursion11.scr b/scribble-test/src/test/resources/bad/reach/globals/grecursion/Recursion11.scr new file mode 100644 index 000000000..4b5c7ccb4 --- /dev/null +++ b/scribble-test/src/test/resources/bad/reach/globals/grecursion/Recursion11.scr @@ -0,0 +1,17 @@ +module bad.reach.globals.grecursion.Recursion11; + + +global protocol Recursion11(role A, role B) +{ + rec X + { + l1() from A to B; + continue X; + } + rec Y + { + l2() from B to A; + continue X; // Not really a reachability case, caught by name disamb + } +} + diff --git a/scribble-test/src/test/resources/bad/reach/globals/grecursion/Recursion17a.scr b/scribble-test/src/test/resources/bad/reach/globals/grecursion/Recursion17a.scr new file mode 100644 index 000000000..7c2ea98a0 --- /dev/null +++ b/scribble-test/src/test/resources/bad/reach/globals/grecursion/Recursion17a.scr @@ -0,0 +1,26 @@ +module bad.reach.globals.grecursion.Recursion17a; + + +global protocol Foo(role A, role B) +{ + rec Z + { + choice at A + { + rec X + { + 1() from A to B; + continue X; + 4() from A to B; + } + } + or + { + rec Y + { + 2() from A to B; + } + } + } + 3() from A to B; +} diff --git a/scribble-test/src/test/resources/bad/reach/globals/grecursion/Recursion17b.scr b/scribble-test/src/test/resources/bad/reach/globals/grecursion/Recursion17b.scr new file mode 100644 index 000000000..f37889257 --- /dev/null +++ b/scribble-test/src/test/resources/bad/reach/globals/grecursion/Recursion17b.scr @@ -0,0 +1,26 @@ +module good.reach.globals.grecursion.Recursion17b; + + +global protocol Foo(role A, role B) +{ + rec Z + { + choice at A + { + rec X + { + 1() from A to B; + continue X; + } + 4() from A to B; + } + or + { + rec Y + { + 2() from A to B; + } + } + } + 3() from A to B; +} diff --git a/scribble-test/src/test/resources/bad/reach/globals/grecursion/Recursion17c.scr b/scribble-test/src/test/resources/bad/reach/globals/grecursion/Recursion17c.scr new file mode 100644 index 000000000..76e48cbd0 --- /dev/null +++ b/scribble-test/src/test/resources/bad/reach/globals/grecursion/Recursion17c.scr @@ -0,0 +1,26 @@ +module bad.reach.globals.grecursion.Recursion17c; + + +global protocol Foo(role A, role B) +{ + rec Z + { + choice at A + { + rec X + { + 1() from A to B; + continue X; + } + } + or + { + rec Y + { + 2() from A to B; + continue Y; + } + } + } + 3() from A to B; +} diff --git a/scribble-test/src/test/resources/bad/reach/globals/grecursion/Recursion17d.scr b/scribble-test/src/test/resources/bad/reach/globals/grecursion/Recursion17d.scr new file mode 100644 index 000000000..ef13445f8 --- /dev/null +++ b/scribble-test/src/test/resources/bad/reach/globals/grecursion/Recursion17d.scr @@ -0,0 +1,26 @@ +module bad.reach.globals.grecursion.Recursion17d; + + +global protocol Foo(role A, role B) +{ + rec Z + { + choice at A + { + rec X + { + 1() from A to B; + continue X; + } + } + or + { + rec Y + { + 2() from A to B; + continue Z; + } + } + } + 3() from A to B; +} diff --git a/scribble-test/src/test/resources/bad/reach/globals/grecursion/Recursion17e.scr b/scribble-test/src/test/resources/bad/reach/globals/grecursion/Recursion17e.scr new file mode 100644 index 000000000..7375025f6 --- /dev/null +++ b/scribble-test/src/test/resources/bad/reach/globals/grecursion/Recursion17e.scr @@ -0,0 +1,26 @@ +module bad.reach.globals.grecursion.Recursion17e; + + +global protocol Foo(role A, role B) +{ + rec Z + { + choice at A + { + rec X + { + 1() from A to B; + } + } + or + { + rec Y + { + 2() from A to B; + continue Z; + } + } + 4() from A to B; + } + 3() from A to B; +} diff --git a/scribble-test/src/test/resources/bad/reach/globals/grecursion/Recursion17f.scr b/scribble-test/src/test/resources/bad/reach/globals/grecursion/Recursion17f.scr new file mode 100644 index 000000000..5a55465d7 --- /dev/null +++ b/scribble-test/src/test/resources/bad/reach/globals/grecursion/Recursion17f.scr @@ -0,0 +1,26 @@ +module bad.reach.globals.grecursion.Recursion17f; + + +global protocol Foo(role A, role B) +{ + rec Z + { + choice at A + { + rec X + { + 1() from A to B; + } + } + or + { + rec Y + { + 2() from A to B; + continue Z; + } + 4() from A to B; + } + } + 3() from A to B; +} diff --git a/scribble-test/src/test/resources/bad/reach/globals/grecursion/Recursion18.scr b/scribble-test/src/test/resources/bad/reach/globals/grecursion/Recursion18.scr new file mode 100644 index 000000000..cd90c4633 --- /dev/null +++ b/scribble-test/src/test/resources/bad/reach/globals/grecursion/Recursion18.scr @@ -0,0 +1,20 @@ +module bad.reach.globals.grecursion.Recursion18; + + +global protocol Foo(role A, role B) +{ + rec X + { + choice at A + { + 1() from A to B; + } + or + { + 2() from A to B; + continue X; + } + continue X; // Bad reach // Reachability error comes out as a graph building error if not checked first + } +} + diff --git a/scribble-test/src/test/resources/bad/reach/globals/grecursion/Recursion19a.scr b/scribble-test/src/test/resources/bad/reach/globals/grecursion/Recursion19a.scr new file mode 100644 index 000000000..e397203cd --- /dev/null +++ b/scribble-test/src/test/resources/bad/reach/globals/grecursion/Recursion19a.scr @@ -0,0 +1,12 @@ +module bad.reach.globals.grecursion.Recursion19a; + + +global protocol Foo(role A, role B, role C) +{ + rec X + { + 1() from A to B; + continue X; + } + 2() from A to C; +} diff --git a/scribble-test/src/test/resources/bad/safety/orphan/threeparty/Test01a.scr b/scribble-test/src/test/resources/bad/safety/orphan/threeparty/Test01a.scr new file mode 100644 index 000000000..8306ff631 --- /dev/null +++ b/scribble-test/src/test/resources/bad/safety/orphan/threeparty/Test01a.scr @@ -0,0 +1,19 @@ +module bad.safety.orphan.threeparty.Test01a; + + +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + 1() from A to B; + 2() from B to C; + } + or + { + 1() from A to B; + 2() from B to C; + 3() from B to C; // Also wait-for + } +} + + diff --git a/scribble-test/src/test/resources/bad/safety/orphan/threeparty/Test01b.scr b/scribble-test/src/test/resources/bad/safety/orphan/threeparty/Test01b.scr new file mode 100644 index 000000000..1336c35f3 --- /dev/null +++ b/scribble-test/src/test/resources/bad/safety/orphan/threeparty/Test01b.scr @@ -0,0 +1,19 @@ +module bad.safety.orphan.threeparty.Test01b; + + +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + 1() from A to B; + 2() from B to C; + } + or + { + 1() from A to B; + 4() from A to B; // Also wait-for + 2() from B to C; // (Mergeable B-C, no stuck) + } +} + + diff --git a/scribble-test/src/test/resources/bad/safety/orphan/threeparty/Test02.scr b/scribble-test/src/test/resources/bad/safety/orphan/threeparty/Test02.scr new file mode 100644 index 000000000..33e0d75e2 --- /dev/null +++ b/scribble-test/src/test/resources/bad/safety/orphan/threeparty/Test02.scr @@ -0,0 +1,22 @@ +module bad.safety.orphan.threeparty.Test02; + + +global protocol Proto1(role A, role B, role C) +{ + rec X + { + choice at A + { + 1() from A to B; + 3() from A to C; + continue X; // Also wait-for + } + or + { + 1() from A to B; + 4() from A to C; + } + } +} + + diff --git a/scribble-test/src/test/resources/bad/safety/orphan/threeparty/Test03.scr b/scribble-test/src/test/resources/bad/safety/orphan/threeparty/Test03.scr new file mode 100644 index 000000000..ec7832a8b --- /dev/null +++ b/scribble-test/src/test/resources/bad/safety/orphan/threeparty/Test03.scr @@ -0,0 +1,20 @@ +module bad.safety.orphan.threeparty.Test03; + + +global protocol Proto1(role A, role B, role C) +{ + // Wait-for + orphan error counterparts (arise together) + choice at A + { + 1() from A to B; + 1() from A to C; + 2() from B to C; + } + or + { + 1() from A to B; + 1() from A to C; + 2() from C to B; + } +} + diff --git a/scribble-test/src/test/resources/bad/safety/orphan/twoparty/Test01.scr b/scribble-test/src/test/resources/bad/safety/orphan/twoparty/Test01.scr new file mode 100644 index 000000000..6a3bc1219 --- /dev/null +++ b/scribble-test/src/test/resources/bad/safety/orphan/twoparty/Test01.scr @@ -0,0 +1,21 @@ +module bad.safety.orphan.twoparty.Test01; + + +global protocol Proto1(role A, role B) +{ + rec X + { + choice at A + { + 1() from A to B; // (..and counterpart wait-for) + continue X; + } + or + { + 1() from A to B; // Bad: orphans + } + } +} + + + diff --git a/scribble-test/src/test/resources/bad/safety/orphan/twoparty/Test02.scr b/scribble-test/src/test/resources/bad/safety/orphan/twoparty/Test02.scr new file mode 100644 index 000000000..31ed714fd --- /dev/null +++ b/scribble-test/src/test/resources/bad/safety/orphan/twoparty/Test02.scr @@ -0,0 +1,19 @@ +module bad.safety.orphan.twoparty.Test02; + + +global protocol Proto1(role A, role B) +{ + // Wait-for + orphan error counterparts (arise together) + choice at A + { + 1() from A to B; + 1() from B to A; + 2() from A to B; // Orphan (and deadlock) + } + or + { + 1() from A to B; + 1() from B to A; + } +} + diff --git a/scribble-test/src/test/resources/bad/safety/stuckmsg/fourparty/Test01.scr b/scribble-test/src/test/resources/bad/safety/stuckmsg/fourparty/Test01.scr new file mode 100644 index 000000000..f9a4350de --- /dev/null +++ b/scribble-test/src/test/resources/bad/safety/stuckmsg/fourparty/Test01.scr @@ -0,0 +1,38 @@ +module bad.safety.stuckmsg.fourparty.Test01; + + +global protocol Proto1(role A, role B, role C, role D) +{ + choice at A + { + 1() from A to B; + rec X + { + 1() from A to B; + choice at B + { + 2() from B to C; + 2() from C to D; + choice at C + { + 2() from C to A; + } + or + { + () from C to A; + 2() from C to D; // Reception error (but OK if following is commented) + () from C to D; + } + continue X; + } + } + } + or + { + 0() from A to B; + 0() from B to C; + 0() from C to D; + } +} + + diff --git a/scribble-test/src/test/resources/bad/safety/stuckmsg/fourparty/Test02a.scr b/scribble-test/src/test/resources/bad/safety/stuckmsg/fourparty/Test02a.scr new file mode 100644 index 000000000..80732dd17 --- /dev/null +++ b/scribble-test/src/test/resources/bad/safety/stuckmsg/fourparty/Test02a.scr @@ -0,0 +1,23 @@ +module bad.safety.stuckmsg.fourparty.Test02a; + + +global protocol Proto1(role A, role B, role C, role D) +{ + rec X + { + 1() from A to B; + continue X; // Checking safety in non-terminating global model + } + choice at C + { + 2() from C to D; + 3() from D to C; // Stuck messages also manifest as message liveness errors (subsumed? so unnecessary to check safety except for actual terminations? -- but morally, they are local safety errors for the roles, as opposed to global liveness errors for the system) + } + or + { + 2() from C to D; + 4() from D to C; + } +} + + diff --git a/scribble-test/src/test/resources/bad/safety/stuckmsg/fourparty/Test02b.scr b/scribble-test/src/test/resources/bad/safety/stuckmsg/fourparty/Test02b.scr new file mode 100644 index 000000000..a2cbaf56b --- /dev/null +++ b/scribble-test/src/test/resources/bad/safety/stuckmsg/fourparty/Test02b.scr @@ -0,0 +1,22 @@ +module bad.safety.stuckmsg.fourparty.Test02b; + + +global protocol Proto1(role A, role B, role C, role D) +{ + choice at A + { + 1() from A to B; + 2() from B to A; + } + or + { + 1() from A to B; + 3() from B to A; // A not safe (but not a terminal global state) + } + rec X + { + 4() from C to D; + continue X; + } +} + diff --git a/scribble-test/src/test/resources/bad/safety/stuckmsg/payloads/Test01a.scr b/scribble-test/src/test/resources/bad/safety/stuckmsg/payloads/Test01a.scr new file mode 100644 index 000000000..5e48c76b1 --- /dev/null +++ b/scribble-test/src/test/resources/bad/safety/stuckmsg/payloads/Test01a.scr @@ -0,0 +1,24 @@ +module bad.safety.stuckmsg.payloads.Test01a; + + +type "java.lang.Integer" from "rt.jar" as Int1; +type "java.lang.Integer" from "rt.jar" as Int2; + + +global protocol Proto1(role A, role B) +{ + choice at A + { + //1() from A to B; // Uncomment still bad + 1(Int1) from A to B; + 2() from B to A; + } + or + { + 1(Int2) from A to B; // here, payloads aren't considered as distinguishing for labels + // error is the special case of actions that are non-deterministic labels up to payloads + // (Syntactic MPST merge not defined for repeat labels, Cf. -oldwf) + 3() from B to A; + } +} + diff --git a/scribble-test/src/test/resources/bad/safety/stuckmsg/payloads/Test01b.scr b/scribble-test/src/test/resources/bad/safety/stuckmsg/payloads/Test01b.scr new file mode 100644 index 000000000..d25527166 --- /dev/null +++ b/scribble-test/src/test/resources/bad/safety/stuckmsg/payloads/Test01b.scr @@ -0,0 +1,24 @@ +module bad.safety.stuckmsg.payloads.Test01b; + + +type "java.lang.Integer" from "rt.jar" as Int1; +type "java.lang.Integer" from "rt.jar" as Int2; + + +global protocol Proto1(role A, role B) +{ + choice at A + { + 1(Int1) from A to B; + 2() from B to A; // Mergeable continuations, but still bad.. + } + or + { + 1(Int2) from A to B; // B doesn't know to treat as Int1 or Int2 + // here, payloads aren't considered as distinguishing for labels + // error is the special case of actions that are non-deterministic labels up to payloads + // (Syntactic MPST merge not defined for repeat labels) + 2() from B to A; + } +} + diff --git a/scribble-test/src/test/resources/bad/safety/stuckmsg/payloads/Test01c.scr b/scribble-test/src/test/resources/bad/safety/stuckmsg/payloads/Test01c.scr new file mode 100644 index 000000000..72b4c0252 --- /dev/null +++ b/scribble-test/src/test/resources/bad/safety/stuckmsg/payloads/Test01c.scr @@ -0,0 +1,25 @@ +module bad.safety.stuckmsg.payloads.Test01c; + + +type "java.lang.Integer" from "rt.jar" as Int1; +type "java.lang.Integer" from "rt.jar" as Int2; + + +// Cf. bad.safety.stuckmsg.payloads.Test01b +global protocol Proto1(role A, role B) +{ + choice at A + { + 1() from A to B; + 2(Int1) from B to A; + } + or + { + 1() from A to B; + 2(Int2) from B to A; // (Syntactic MPST merge not defined for repeat labels) + // here, payloads are considered as distinguishing (as default) -- whole I/O action used as label + // Cf.\ Test01b, non-deterministic actions of the same state + // here, actions on different states -- error manifests as regular stuck + } +} + diff --git a/scribble-test/src/test/resources/bad/safety/stuckmsg/payloads/Test01d.scr b/scribble-test/src/test/resources/bad/safety/stuckmsg/payloads/Test01d.scr new file mode 100644 index 000000000..9a9116bd1 --- /dev/null +++ b/scribble-test/src/test/resources/bad/safety/stuckmsg/payloads/Test01d.scr @@ -0,0 +1,24 @@ +module bad.safety.stuckmsg.payloads.Test01d; + + +type "java.lang.Integer" from "rt.jar" as Int1; +type "java.lang.Integer" from "rt.jar" as Int2; + + +global protocol Proto1(role A, role B) +{ + choice at A + { + 1() from A to B; // Uncomment still bad + 1(Int1) from A to B; + 2() from B to A; + } + or + { + 1(Int2) from A to B; // here, payloads aren't considered as distinguishing for labels + // error is the special case of actions that are non-deterministic labels up to payloads + // (Syntactic MPST merge not defined for repeat labels, Cf. -oldwf) + 3() from B to A; + } +} + diff --git a/scribble-test/src/test/resources/bad/safety/stuckmsg/payloads/Test01e.scr b/scribble-test/src/test/resources/bad/safety/stuckmsg/payloads/Test01e.scr new file mode 100644 index 000000000..3ad6e6a00 --- /dev/null +++ b/scribble-test/src/test/resources/bad/safety/stuckmsg/payloads/Test01e.scr @@ -0,0 +1,22 @@ +module bad.safety.stuckmsg.payloads.Test01e; + + +type "java.lang.Integer" from "rt.jar" as Int1; +type "java.lang.Integer" from "rt.jar" as Int2; + + +// Three-party +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + 1() from A to B; + 2(Int1) from B to C; + } + or + { + 1() from A to B; + 2(Int2) from B to C; // Payload actions deterministic at B (following initial non-det by A), but non-det at C + } +} + diff --git a/scribble-test/src/test/resources/bad/safety/stuckmsg/threeparty/Test01.scr b/scribble-test/src/test/resources/bad/safety/stuckmsg/threeparty/Test01.scr new file mode 100644 index 000000000..75acac56b --- /dev/null +++ b/scribble-test/src/test/resources/bad/safety/stuckmsg/threeparty/Test01.scr @@ -0,0 +1,23 @@ +module bad.safety.stuckmsg.threeparty.Test01; + + +// Cf. good.wfchoice.gchoice.Choice11; +global protocol Proto1(role A, role B, role C) +{ + rec X + { + 2() from A to B; // bad safety + choice at A + { + 1() from A to C; + continue X; + } + or + { + 2() from A to B; + 2() from A to C; + } + } +} + + diff --git a/scribble-test/src/test/resources/bad/safety/stuckmsg/threeparty/Test02.scr b/scribble-test/src/test/resources/bad/safety/stuckmsg/threeparty/Test02.scr new file mode 100644 index 000000000..03a326b38 --- /dev/null +++ b/scribble-test/src/test/resources/bad/safety/stuckmsg/threeparty/Test02.scr @@ -0,0 +1,23 @@ +module bad.safety.stuckmsg.threeparty.Test02; + + +global protocol Proto1(role A, role B, role C) +{ + rec X + { + choice at A + { + 1() from A to B; + 3() from A to C; + continue X; + } + or + { + 1() from A to B; + 2() from A to B; + 4() from A to C; + } + } +} + + diff --git a/scribble-test/src/test/resources/bad/safety/stuckmsg/threeparty/Test03.scr b/scribble-test/src/test/resources/bad/safety/stuckmsg/threeparty/Test03.scr new file mode 100644 index 000000000..f9bd4593a --- /dev/null +++ b/scribble-test/src/test/resources/bad/safety/stuckmsg/threeparty/Test03.scr @@ -0,0 +1,24 @@ +module bad.safety.stuckmsg.threeparty.Test03; + + +global protocol Proto1(role A, role B, role C) +{ + rec X + { + 1() from A to B; + 1() from B to C; + choice at B + { + 2() from B to A; + continue X; + } + or + { + 3() from B to A; + 1() from B to C; + 3() from B to C; + continue X; + } + } +} + diff --git a/scribble-test/src/test/resources/bad/safety/stuckmsg/twoparty/Test01a.scr b/scribble-test/src/test/resources/bad/safety/stuckmsg/twoparty/Test01a.scr new file mode 100644 index 000000000..307f47622 --- /dev/null +++ b/scribble-test/src/test/resources/bad/safety/stuckmsg/twoparty/Test01a.scr @@ -0,0 +1,16 @@ +module bad.safety.stuckmsg.twoparty.Test01a; + + +global protocol Proto1(role A, role B) +{ + choice at A + { + 1() from A to B; + } + or + { + 1() from A to B; + 2() from A to B; + } +} + diff --git a/scribble-test/src/test/resources/bad/safety/stuckmsg/twoparty/Test01b.scr b/scribble-test/src/test/resources/bad/safety/stuckmsg/twoparty/Test01b.scr new file mode 100644 index 000000000..dd584bdbd --- /dev/null +++ b/scribble-test/src/test/resources/bad/safety/stuckmsg/twoparty/Test01b.scr @@ -0,0 +1,20 @@ +module bad.safety.stuckmsg.twoparty.Test01b; + +global protocol Proto1(role A, role B) +{ + rec X + { + choice at A + { + 1() from A to B; + continue X; + } + or + { + 1() from A to B; + 2() from A to B; + continue X; + } + } +} + diff --git a/scribble-test/src/test/resources/bad/safety/stuckmsg/twoparty/Test03.scr b/scribble-test/src/test/resources/bad/safety/stuckmsg/twoparty/Test03.scr new file mode 100644 index 000000000..de77ac42c --- /dev/null +++ b/scribble-test/src/test/resources/bad/safety/stuckmsg/twoparty/Test03.scr @@ -0,0 +1,22 @@ +module bad.safety.stuckmsg.twoparty.Test03; + + +global protocol Foo(role A, role B) +{ + 1() from A to B; + choice at A + { + do Bar(A, B); + } + or + { + 1() from A to B; + 2() from A to B; + } +} + +global protocol Bar(role A, role B) +{ + do Foo(A, B); +} + diff --git a/scribble-test/src/test/resources/bad/safety/stuckmsg/twoparty/Test04.scr b/scribble-test/src/test/resources/bad/safety/stuckmsg/twoparty/Test04.scr new file mode 100644 index 000000000..6ce3cf899 --- /dev/null +++ b/scribble-test/src/test/resources/bad/safety/stuckmsg/twoparty/Test04.scr @@ -0,0 +1,18 @@ +module bad.safety.stuckmsg.twoparty.Test04; + + +// Cf. good.wfchoice.enabling.twoparty.Test02 +global protocol Proto1(role A, role B) +{ + choice at A + { + 1() from A to B; + 2() from B to A; + } + or + { + 1() from A to B; + 3() from B to A; + } +} + diff --git a/scribble-test/src/test/resources/bad/safety/waitfor/threeparty/Test01.scr b/scribble-test/src/test/resources/bad/safety/waitfor/threeparty/Test01.scr new file mode 100644 index 000000000..5faa8e4e0 --- /dev/null +++ b/scribble-test/src/test/resources/bad/safety/waitfor/threeparty/Test01.scr @@ -0,0 +1,19 @@ +module bad.safety.waitfor.threeparty.Test01; + + +global protocol Proto1(role A, role B, role C) +{ + rec X + { + choice at A + { + 1() from A to B; // C starved without -fair, but irrelevant to deadlock error + continue X; + } + or + { + 2() from A to C; // No reception error, but B can be deadlocked + } + } +} + diff --git a/scribble-test/src/test/resources/bad/safety/waitfor/threeparty/Test02.scr b/scribble-test/src/test/resources/bad/safety/waitfor/threeparty/Test02.scr new file mode 100644 index 000000000..5c07e6d6d --- /dev/null +++ b/scribble-test/src/test/resources/bad/safety/waitfor/threeparty/Test02.scr @@ -0,0 +1,30 @@ +module bad.safety.waitfor.threeparty.Test02; + + +global protocol Proto1(role A, role B, role C) +{ + rec X + { + choice at A + { + 1() from A to B; + choice at A + { + 1() from A to C; + continue X; // ** CHECKME: badly formed (for B) -- empty block bvelow is pruned leaving only the continue case, which leads to deadlock in global model, is this OK as WF algorithm? (any way to be unsound?) or should explicitly detect inconsistent choice block projections? + } + or + { + 3() from A to C; + } + } + or + { + 2() from A to C; + 2() from A to B; + } + } +} +//*/ + + diff --git a/scribble-test/src/test/resources/bad/safety/waitfor/threeparty/Test03.scr b/scribble-test/src/test/resources/bad/safety/waitfor/threeparty/Test03.scr new file mode 100644 index 000000000..03787c300 --- /dev/null +++ b/scribble-test/src/test/resources/bad/safety/waitfor/threeparty/Test03.scr @@ -0,0 +1,19 @@ +module bad.safety.waitfor.threeparty.Test03; + + +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + 1() from A to B; + 1() from B to C; + } + or + { + 2() from A to B; + //1() from B to C; // Comment is bad + } + 2() from C to B; +} + + diff --git a/scribble-test/src/test/resources/bad/safety/waitfor/threeparty/Test04.scr b/scribble-test/src/test/resources/bad/safety/waitfor/threeparty/Test04.scr new file mode 100644 index 000000000..e023382ce --- /dev/null +++ b/scribble-test/src/test/resources/bad/safety/waitfor/threeparty/Test04.scr @@ -0,0 +1,20 @@ +module bad.safety.waitfor.threeparty.Test04; + + +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + 1() from A to B; + 1() from A to C; + 1() from C to B; + } + or + { + 1() from A to B; // Uncomment is bad + 2() from A to B; + 2() from A to C; + 2() from C to B; // Also potential stuck + } +} + diff --git a/scribble-test/src/test/resources/bad/safety/waitfor/threeparty/Test05.scr b/scribble-test/src/test/resources/bad/safety/waitfor/threeparty/Test05.scr new file mode 100644 index 000000000..58bd3f8aa --- /dev/null +++ b/scribble-test/src/test/resources/bad/safety/waitfor/threeparty/Test05.scr @@ -0,0 +1,16 @@ +module bad.safety.waitfor.threeparty.Test05; + + +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + 1() from A to B; + } + or + { + 2() from A to B; + 4() from A to C; + } +} + diff --git a/scribble-test/src/test/resources/bad/safety/waitfor/twoparty/Test01.scr b/scribble-test/src/test/resources/bad/safety/waitfor/twoparty/Test01.scr new file mode 100644 index 000000000..77c1d96c7 --- /dev/null +++ b/scribble-test/src/test/resources/bad/safety/waitfor/twoparty/Test01.scr @@ -0,0 +1,26 @@ +module bad.safety.waitfor.twoparty.Test01; + + +global protocol Proto1(role A, role B) +{ + choice at A + { + 1() from A to B; + 1() from B to A; + 2() from A to B; // Async. permut. needs to be an asymmetric local feature; done "globally" allows potential deadlock + 2() from A to B; + 3() from B to A; + 3() from B to A; + } + or + { + 1() from A to B; + 1() from B to A; + 3() from B to A; // Potential deadlock + 3() from B to A; + 2() from A to B; + 2() from A to B; + } +} + + diff --git a/scribble-test/src/test/resources/bad/syntax/consistentchoicesubj/Test01.scr b/scribble-test/src/test/resources/bad/syntax/consistentchoicesubj/Test01.scr new file mode 100644 index 000000000..25c79211c --- /dev/null +++ b/scribble-test/src/test/resources/bad/syntax/consistentchoicesubj/Test01.scr @@ -0,0 +1,18 @@ +module bad.syntax.consistentchoicesubj.Test01; + + +// Maybe refactor as projection +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + 1() from A to B; + 1() from A to C; + } + or + { + 2() from A to B; + 2() from B to C; + } +} + diff --git a/scribble-test/src/test/resources/bad/syntax/consistentchoicesubj/Test02.scr b/scribble-test/src/test/resources/bad/syntax/consistentchoicesubj/Test02.scr new file mode 100644 index 000000000..5a99b0b90 --- /dev/null +++ b/scribble-test/src/test/resources/bad/syntax/consistentchoicesubj/Test02.scr @@ -0,0 +1,15 @@ +module bad.syntax.consistentchoicesubj.Test02; + + +// Maybe refactor as projection +global protocol Proto1(role C, role S) +{ + choice at C + { + choice at S // Fixed peekParentEnv index bug for enabled choice subjs + { + 1() from S to C; + } + } +} + diff --git a/scribble-test/src/test/resources/bad/syntax/consistentchoicesubj/Test04a.scr b/scribble-test/src/test/resources/bad/syntax/consistentchoicesubj/Test04a.scr new file mode 100644 index 000000000..6ca52a1f3 --- /dev/null +++ b/scribble-test/src/test/resources/bad/syntax/consistentchoicesubj/Test04a.scr @@ -0,0 +1,25 @@ +module bad.syntax.consistentchoicesubj.Test04a; + + +global protocol Proto1(role A, role B, role C) +{ + // Safe (without recursion), but (intentionally) not supported by local choice syntax -- so global model checking incomplete in general (i.e. morally, outside of Scribble syntax restrictions) + // Cf. -nolocalchoicecheck + /*rec X + {*/ + choice at A + { + 1() from A to B; + 3() from B to C; + //continue X; // With recursion, -nolocalchoicecheck under WF_1 is unsound + } + or + { + 2() from A to B; + 4() from A to C; + //continue X; + } + //} +} + + diff --git a/scribble-test/src/test/resources/bad/syntax/consistentchoicesubj/Test04b.scr b/scribble-test/src/test/resources/bad/syntax/consistentchoicesubj/Test04b.scr new file mode 100644 index 000000000..03c94d049 --- /dev/null +++ b/scribble-test/src/test/resources/bad/syntax/consistentchoicesubj/Test04b.scr @@ -0,0 +1,23 @@ +module bad.syntax.consistentchoicesubj.Test04b; + + +global protocol Proto1(role A, role B, role C) +{ + rec X + { + choice at A + { + 1() from A to B; + 3() from B to C; + continue X; + } + or + { + 2() from A to B; + 4() from A to C; + continue X; + } + } +} + + diff --git a/scribble-test/src/test/resources/bad/syntax/consistentchoicesubj/Test04c.scr b/scribble-test/src/test/resources/bad/syntax/consistentchoicesubj/Test04c.scr new file mode 100644 index 000000000..5429fa500 --- /dev/null +++ b/scribble-test/src/test/resources/bad/syntax/consistentchoicesubj/Test04c.scr @@ -0,0 +1,22 @@ +module bad.syntax.consistentchoicesubj.Test04c; + + +global protocol Proto1(role A, role B, role C) +{ + rec X + { + choice at A + { + 1() from A to B; + 3() from B to C; + } + or + { + 2() from A to B; + 4() from A to C; + } + continue X; // Would be OK, even ignoring inconsistent choice subjects, because C just needs to receive 3s or 4s with no further consequences + } +} + + diff --git a/scribble-test/src/test/resources/bad/syntax/consistentchoicesubj/Test05a.scr b/scribble-test/src/test/resources/bad/syntax/consistentchoicesubj/Test05a.scr new file mode 100644 index 000000000..801e79a58 --- /dev/null +++ b/scribble-test/src/test/resources/bad/syntax/consistentchoicesubj/Test05a.scr @@ -0,0 +1,20 @@ +module bad.syntax.consistentchoicesubj.Test05a; + + +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + 1() from A to B; + 1() from A to C; // Bad, even.. + 2() from B to C; + 3() from C to B; + } + or + { + 2() from A to B; + 2() from B to C; // ..without local choice subject check + 4() from C to B; + } +} + diff --git a/scribble-test/src/test/resources/bad/syntax/consistentchoicesubj/Test05b.scr b/scribble-test/src/test/resources/bad/syntax/consistentchoicesubj/Test05b.scr new file mode 100644 index 000000000..e73fdbd5f --- /dev/null +++ b/scribble-test/src/test/resources/bad/syntax/consistentchoicesubj/Test05b.scr @@ -0,0 +1,25 @@ +module bad.syntax.consistentchoicesubj.Test05b; + + +global protocol Proto1(role A, role B, role C) +{ + rec X + { + choice at A + { + 1() from A to B; + 1() from A to C; // Bad, even.. + 2() from B to C; + 3() from C to B; + } + or + { + 2() from A to B; + 2() from B to C; // ..without local choice subject check + 4() from C to B; + } + continue X; + } +} + + diff --git a/scribble-test/src/test/resources/bad/syntax/consistentchoicesubj/Test06a.scr b/scribble-test/src/test/resources/bad/syntax/consistentchoicesubj/Test06a.scr new file mode 100644 index 000000000..f6e8189dc --- /dev/null +++ b/scribble-test/src/test/resources/bad/syntax/consistentchoicesubj/Test06a.scr @@ -0,0 +1,18 @@ +module bad.syntax.consistentchoicesubj.Test06a; + + +global protocol Proto1(role A, role B, role C) +{ + choice at A // Would be OK without local choice subject checking (and a multi-queue input branch primitive) + { + 1() from A to B; + 2() from B to C; + 3() from C to B; + } + or + { + 4() from A to C; + 5() from C to B; + } +} + diff --git a/scribble-test/src/test/resources/bad/syntax/consistentchoicesubj/Test06b.scr b/scribble-test/src/test/resources/bad/syntax/consistentchoicesubj/Test06b.scr new file mode 100644 index 000000000..845c59d18 --- /dev/null +++ b/scribble-test/src/test/resources/bad/syntax/consistentchoicesubj/Test06b.scr @@ -0,0 +1,22 @@ +module bad.syntax.consistentchoicesubj.Test06b; + + +global protocol Proto1(role A, role B, role C) +{ + rec X + { + choice at A // Morally bad, even without local choice subject checking (and a multi-queue input branch primitive, etc.) + { + 1() from A to B; + 2() from B to C; + 3() from C to B; + } + or + { + 4() from A to C; + 5() from C to B; + } + continue X; + } +} + diff --git a/scribble-test/src/test/resources/bad/syntax/consistentchoicesubj/Test07a.scr b/scribble-test/src/test/resources/bad/syntax/consistentchoicesubj/Test07a.scr new file mode 100644 index 000000000..e06b40670 --- /dev/null +++ b/scribble-test/src/test/resources/bad/syntax/consistentchoicesubj/Test07a.scr @@ -0,0 +1,23 @@ +module bad.syntax.consistentchoicesubj.Test07a; + + +global protocol Proto1(role A, role B, role C) +{ + rec X + { + choice at A + { + 1() from A to B; + 1() from A to C; + 4() from C to B; // Bad.. (apart from inconsistent choice subjects) + continue X; + } + or + { + 2() from A to B; + 3() from B to C; + 5() from C to B; + //continue X; // ..but OK if this continue commented -- is that correct? + } + } +} diff --git a/scribble-test/src/test/resources/bad/syntax/consistentchoicesubj/Test07b.scr b/scribble-test/src/test/resources/bad/syntax/consistentchoicesubj/Test07b.scr new file mode 100644 index 000000000..e6cf84254 --- /dev/null +++ b/scribble-test/src/test/resources/bad/syntax/consistentchoicesubj/Test07b.scr @@ -0,0 +1,23 @@ +module bad.syntax.consistentchoicesubj.Test07b; + + +global protocol Proto1(role A, role B, role C) +{ + rec X + { + choice at A + { + 1() from A to B; + 1() from A to C; + 4() from C to B; + // OK if -nolocalchoicecheck, and morally OK (no recursion, cf. bad.syntax.consistentchoicesubj.Test07a) + } + or + { + 2() from A to B; + 3() from B to C; + 5() from C to B; + } + } +} + diff --git a/scribble-test/src/test/resources/bad/syntax/consistentchoicesubj/Test07c.scr b/scribble-test/src/test/resources/bad/syntax/consistentchoicesubj/Test07c.scr new file mode 100644 index 000000000..256c33c0b --- /dev/null +++ b/scribble-test/src/test/resources/bad/syntax/consistentchoicesubj/Test07c.scr @@ -0,0 +1,24 @@ +module bad.syntax.consistentchoicesubj.Test07b; + + +global protocol Proto1(role A, role B, role C) +{ + rec X + { + choice at A + { + 1() from A to B; + 1() from A to C; + 4() from C to A; // OK by -nolocalchoicecheck, and also morally OK because A receives from C (no asynchronous "iteration ambiguity" -- cf. 07a/07b) + continue X; + } + or + { + 2() from A to B; + 3() from B to C; + 5() from C to A; + continue X; + } + } +} + diff --git a/scribble-test/src/test/resources/bad/syntax/consistentchoicesubj/Test08.scr b/scribble-test/src/test/resources/bad/syntax/consistentchoicesubj/Test08.scr new file mode 100644 index 000000000..e7c0fa980 --- /dev/null +++ b/scribble-test/src/test/resources/bad/syntax/consistentchoicesubj/Test08.scr @@ -0,0 +1,22 @@ +module bad.syntax.consistentchoicesubj.Test08; + + +global protocol Proto1(role A, role B, role C) +{ + rec X + { + choice at A + { + 1() from A to B; + 1() from A to C; + 1() from C to B; + } + or + { + 2() from A to C; + 2() from C to B; // B enabled by A/C + } + continue X; + } +} + diff --git a/scribble-test/src/test/resources/bad/syntax/disamb/Test01.scr b/scribble-test/src/test/resources/bad/syntax/disamb/Test01.scr new file mode 100644 index 000000000..70fdc6e08 --- /dev/null +++ b/scribble-test/src/test/resources/bad/syntax/disamb/Test01.scr @@ -0,0 +1,14 @@ +module bad.syntax.disamb.Test01; + + +sig "foo" from "bar" as M1; + + +global protocol Foo(role A, role B) +{ + () from A to B; + M from A to B; + M1 from A to B; + M2 from A to B; +} + diff --git a/scribble-test/src/test/resources/bad/syntax/disamb/doarglistdel/DoArgList01.scr b/scribble-test/src/test/resources/bad/syntax/disamb/doarglistdel/DoArgList01.scr new file mode 100644 index 000000000..311f987bc --- /dev/null +++ b/scribble-test/src/test/resources/bad/syntax/disamb/doarglistdel/DoArgList01.scr @@ -0,0 +1,14 @@ +module bad.syntax.disamb.doarglist.DoArgList01; + + +global protocol Foo(role A, role B, role C) +{ + 1() from A to B; + 1() from A to C; + do Bar(A, B, C); +} + +global protocol Bar(role D, role E) +{ + 2() from D to E; +} diff --git a/scribble-test/src/test/resources/bad/syntax/disamb/doarglistdel/DoArgList02.scr b/scribble-test/src/test/resources/bad/syntax/disamb/doarglistdel/DoArgList02.scr new file mode 100644 index 000000000..22bdafca4 --- /dev/null +++ b/scribble-test/src/test/resources/bad/syntax/disamb/doarglistdel/DoArgList02.scr @@ -0,0 +1,14 @@ +module bad.syntax.disamb.doarglist.DoArgList02; + + +global protocol Foo(role A, role B) +{ + 1() from A to B; + do Bar(A, B); +} + +global protocol Bar(role C, role D, role E) +{ + 1() from C to D; + 2() from D to E; +} diff --git a/scribble-test/src/test/resources/bad/syntax/disamb/doarglistdel/DoArgList03.scr b/scribble-test/src/test/resources/bad/syntax/disamb/doarglistdel/DoArgList03.scr new file mode 100644 index 000000000..9c5e43f42 --- /dev/null +++ b/scribble-test/src/test/resources/bad/syntax/disamb/doarglistdel/DoArgList03.scr @@ -0,0 +1,14 @@ +module bad.syntax.disamb.doarglist.DoArgList03; + + +global protocol Foo(role A, role B) +{ + 1() from A to B; + do Bar<2()>(A, B); +} + +global protocol Bar(role C, role D) +{ + M1 from C to D; + M2 from D to C; +} diff --git a/scribble-test/src/test/resources/bad/syntax/disamb/doarglistdel/DoArgList04.scr b/scribble-test/src/test/resources/bad/syntax/disamb/doarglistdel/DoArgList04.scr new file mode 100644 index 000000000..dfc6093c7 --- /dev/null +++ b/scribble-test/src/test/resources/bad/syntax/disamb/doarglistdel/DoArgList04.scr @@ -0,0 +1,13 @@ +module bad.syntax.disamb.doarglist.DoArgList04; + + +global protocol Foo(role A, role B) +{ + 1() from A to B; + do Bar<2(), 3()>(A, B); +} + +global protocol Bar(role C, role D) +{ + M1 from C to D; +} diff --git a/scribble-test/src/test/resources/bad/syntax/disamb/doarglistdel/DoArgList05.scr b/scribble-test/src/test/resources/bad/syntax/disamb/doarglistdel/DoArgList05.scr new file mode 100644 index 000000000..68255b7bf --- /dev/null +++ b/scribble-test/src/test/resources/bad/syntax/disamb/doarglistdel/DoArgList05.scr @@ -0,0 +1,13 @@ +module bad.syntax.disamb.doarglist.DoArgList05; + + +global protocol Foo(role A, role B) +{ + 1() from A to B; + do Bar<2()>(A, B); +} + +global protocol Bar(role C, role D) +{ + 2() from C to D; +} diff --git a/scribble-test/src/test/resources/bad/syntax/disamb/doarglistdel/DoArgList06.scr b/scribble-test/src/test/resources/bad/syntax/disamb/doarglistdel/DoArgList06.scr new file mode 100644 index 000000000..41098fc49 --- /dev/null +++ b/scribble-test/src/test/resources/bad/syntax/disamb/doarglistdel/DoArgList06.scr @@ -0,0 +1,13 @@ +module bad.syntax.disamb.doarglist.DoArgList06; + + +global protocol Foo(role A, role B) +{ + 1() from A to B; + do Bar(A, B); +} + +global protocol Bar(role C, role D) +{ + M1 from C to D; +} diff --git a/scribble-test/src/test/resources/bad/syntax/disamb/globals/gmessagetransfer/GMessageTransfer01.scr b/scribble-test/src/test/resources/bad/syntax/disamb/globals/gmessagetransfer/GMessageTransfer01.scr new file mode 100644 index 000000000..ada699bfa --- /dev/null +++ b/scribble-test/src/test/resources/bad/syntax/disamb/globals/gmessagetransfer/GMessageTransfer01.scr @@ -0,0 +1,7 @@ +module bad.syntax.disamb.globals.gmessagetransfer.GMessageTransfer01; + + +global protocol Foo(role A) +{ + 1() from A to A; // TODO: should be good +} diff --git a/scribble-test/src/test/resources/bad/syntax/disamb/globals/gprotocoldecl/GProtocolDecl01.scr b/scribble-test/src/test/resources/bad/syntax/disamb/globals/gprotocoldecl/GProtocolDecl01.scr new file mode 100644 index 000000000..e7899ed40 --- /dev/null +++ b/scribble-test/src/test/resources/bad/syntax/disamb/globals/gprotocoldecl/GProtocolDecl01.scr @@ -0,0 +1,7 @@ +module bad.syntax.disamb.globals.gprotocoldecl.GProtocolDecl01; + + +global protocol Foo(role A, role B, role C) +{ + +} diff --git a/scribble-test/src/test/resources/bad/syntax/disamb/globals/gprotocoldecl/GProtocolDecl02.scr b/scribble-test/src/test/resources/bad/syntax/disamb/globals/gprotocoldecl/GProtocolDecl02.scr new file mode 100644 index 000000000..f8e600ae6 --- /dev/null +++ b/scribble-test/src/test/resources/bad/syntax/disamb/globals/gprotocoldecl/GProtocolDecl02.scr @@ -0,0 +1,7 @@ +module bad.syntax.disamb.globals.gprotocoldecl.GProtocolDecl02; + + +global protocol GProtocolDecl2(role A, role B, role C) +{ + 1() from A to B; +} diff --git a/scribble-test/src/test/resources/bad/syntax/disamb/globals/gprotocoldecl/GProtocolDecl03.scr b/scribble-test/src/test/resources/bad/syntax/disamb/globals/gprotocoldecl/GProtocolDecl03.scr new file mode 100644 index 000000000..8b2bad3d9 --- /dev/null +++ b/scribble-test/src/test/resources/bad/syntax/disamb/globals/gprotocoldecl/GProtocolDecl03.scr @@ -0,0 +1,12 @@ +module bad.syntax.disamb.globals.protocoldecl.GProtocolDecl03; + + +global protocol GProtocolDecl3a(role D, role E) +{ + do GProtocolDecl3b(D, E); +} + +global protocol GProtocolDecl3b(role D, role E) +{ + do GProtocolDecl3a(D, E); +} diff --git a/scribble-test/src/test/resources/bad/syntax/disamb/globals/gprotocoldecl/GProtocolDecl04.scr b/scribble-test/src/test/resources/bad/syntax/disamb/globals/gprotocoldecl/GProtocolDecl04.scr new file mode 100644 index 000000000..0fabd2a86 --- /dev/null +++ b/scribble-test/src/test/resources/bad/syntax/disamb/globals/gprotocoldecl/GProtocolDecl04.scr @@ -0,0 +1,18 @@ +module bad.syntax.disamb.globals.protocoldecl.GProtocolDecl04; + + +global protocol GProtocolDecl4(role A, role B, role C) +{ + do GProtocolDecl4a(A, B); +} + +global protocol GProtocolDecl4a(role B, role C) +{ + do GProtocolDecl4b(B, C); +} + +global protocol GProtocolDecl4b(role D, role E) +{ + 1() from D to E; + do GProtocolDecl4a(D, E); +} diff --git a/scribble-test/src/test/resources/bad/syntax/disamb/headerparamdecllist/HeaderParamDeclList03.scr b/scribble-test/src/test/resources/bad/syntax/disamb/headerparamdecllist/HeaderParamDeclList03.scr new file mode 100644 index 000000000..a84d6b509 --- /dev/null +++ b/scribble-test/src/test/resources/bad/syntax/disamb/headerparamdecllist/HeaderParamDeclList03.scr @@ -0,0 +1,7 @@ +module bad.syntax.disamb.headerparamdecllist.HeaderParamDeclList03; + + +global protocol Foo(role A, role A) +{ + 1() from A to A; +} diff --git a/scribble-test/src/test/resources/bad/syntax/disamb/imports/Import02.scr b/scribble-test/src/test/resources/bad/syntax/disamb/imports/Import02.scr new file mode 100644 index 000000000..0c2d171c6 --- /dev/null +++ b/scribble-test/src/test/resources/bad/syntax/disamb/imports/Import02.scr @@ -0,0 +1,4 @@ +module bad.syntax.disamb.imports.Import02; + + +import bad.syntax.disamb.imports.Import02; diff --git a/scribble-test/src/test/resources/bad/syntax/disamb/imports/Import03.scr b/scribble-test/src/test/resources/bad/syntax/disamb/imports/Import03.scr new file mode 100644 index 000000000..05c54e1ae --- /dev/null +++ b/scribble-test/src/test/resources/bad/syntax/disamb/imports/Import03.scr @@ -0,0 +1,4 @@ +module bad.syntax.disamb.imports.Import03; + + +import bad.syntax.disamb.imports.Import03 as Import03; // The simple name Import03 is implicitly visible from moduledecl diff --git a/scribble-test/src/test/resources/bad/syntax/disamb/imports/Import06.scr b/scribble-test/src/test/resources/bad/syntax/disamb/imports/Import06.scr new file mode 100644 index 000000000..e72d3feac --- /dev/null +++ b/scribble-test/src/test/resources/bad/syntax/disamb/imports/Import06.scr @@ -0,0 +1,9 @@ +//Raymond@HZHL2 ~/code/python/scribble-tools +//$ PYTHONPATH='lib/:bin/' python src/scribble/Main.py -ip test/ test/base/impourt/Import6.scr + +// Possiblty good for testing for potential loops in recursive imports when a module is bad? -- could allow this as a special case? (import self) + +module bad.parsing.imports.Import06; + +import bad.parsing.imports.Import06; + diff --git a/scribble-test/src/test/resources/bad/syntax/disamb/imports/Import17.scr b/scribble-test/src/test/resources/bad/syntax/disamb/imports/Import17.scr new file mode 100644 index 000000000..211903022 --- /dev/null +++ b/scribble-test/src/test/resources/bad/syntax/disamb/imports/Import17.scr @@ -0,0 +1,7 @@ +//Raymond@HZHL2 ~/code/python/scribble-tools +//$ PYTHONPATH='lib/:bin/' python src/scribble/Main.py -ip test/ test/base/impourt/Import17.scr + +module bad.parsing.imports.Import17; + + +import bad.parsing.imports.Import17; // Old: OK because full name is a "compound" name -- old: if simple and full names coincide for a module, self import is not OK diff --git a/scribble-test/src/test/resources/bad/syntax/disamb/imports/Import18.scr b/scribble-test/src/test/resources/bad/syntax/disamb/imports/Import18.scr new file mode 100644 index 000000000..5e83c0dfa --- /dev/null +++ b/scribble-test/src/test/resources/bad/syntax/disamb/imports/Import18.scr @@ -0,0 +1,12 @@ +module good.syntax.disamb.imports.Import18; + + +import bad.syntax.disamb.imports.pack1.Import18b as Bar; + + +global protocol Foo(role A, role B) +{ + do good.syntax.disamb.imports.pack1.Import18b.Proto2(A, B); +} + + diff --git a/scribble-test/src/test/resources/bad/syntax/disamb/imports/Import19.scr b/scribble-test/src/test/resources/bad/syntax/disamb/imports/Import19.scr new file mode 100644 index 000000000..92c1cf171 --- /dev/null +++ b/scribble-test/src/test/resources/bad/syntax/disamb/imports/Import19.scr @@ -0,0 +1,7 @@ +module good.syntax.disamb.imports.Import19; + + +import bad.syntax.disamb.imports.pack1.Import19b; + + + diff --git a/scribble-test/src/test/resources/bad/syntax/disamb/imports/pack1/IGNORE b/scribble-test/src/test/resources/bad/syntax/disamb/imports/pack1/IGNORE new file mode 100644 index 000000000..e69de29bb diff --git a/scribble-test/src/test/resources/bad/syntax/disamb/imports/pack1/Import19b.scr b/scribble-test/src/test/resources/bad/syntax/disamb/imports/pack1/Import19b.scr new file mode 100644 index 000000000..1ecfdc4b8 --- /dev/null +++ b/scribble-test/src/test/resources/bad/syntax/disamb/imports/pack1/Import19b.scr @@ -0,0 +1,8 @@ +module bad.syntax.disamb.imports.pack1.Import19b; + + +global protocol Proto1(role C, role D) +{ + () from C to A; +} + diff --git a/scribble-test/src/test/resources/bad/syntax/disamb/modules/Modules01.scr b/scribble-test/src/test/resources/bad/syntax/disamb/modules/Modules01.scr new file mode 100644 index 000000000..d83bb4de4 --- /dev/null +++ b/scribble-test/src/test/resources/bad/syntax/disamb/modules/Modules01.scr @@ -0,0 +1,13 @@ +module bad.syntax.disamb.modules.Modules01; + + +// FIXME: inconsistent classification of diamb tests, e.g. modules vs protocoldecl, imports, etc +global protocol Foo(role A, role B) +{ + +} + +global protocol Foo(role A, role B) +{ + +} diff --git a/scribble-test/src/test/resources/bad/syntax/disamb/modules/Modules02.scr b/scribble-test/src/test/resources/bad/syntax/disamb/modules/Modules02.scr new file mode 100644 index 000000000..30eac000e --- /dev/null +++ b/scribble-test/src/test/resources/bad/syntax/disamb/modules/Modules02.scr @@ -0,0 +1,5 @@ +module bad.syntax.disamb.modules.Modules02; + + +type "java.lang.String" from "rt.jar" as String; +type "java.lang.String" from "rt.jar" as String; diff --git a/scribble-test/src/test/resources/bad/syntax/disamb/modules/Modules03.scr b/scribble-test/src/test/resources/bad/syntax/disamb/modules/Modules03.scr new file mode 100644 index 000000000..0f02a88f4 --- /dev/null +++ b/scribble-test/src/test/resources/bad/syntax/disamb/modules/Modules03.scr @@ -0,0 +1,5 @@ +module bad.syntax.disamb.modules.Modules03; + + +type "java.lang.String" from "rt.jar" as String; +sig "java.lang.String" from "rt.jar" as String; diff --git a/scribble-test/src/test/resources/bad/syntax/disamb/modules/Modules04a.scr b/scribble-test/src/test/resources/bad/syntax/disamb/modules/Modules04a.scr new file mode 100644 index 000000000..565880ee3 --- /dev/null +++ b/scribble-test/src/test/resources/bad/syntax/disamb/modules/Modules04a.scr @@ -0,0 +1,4 @@ +module bad.syntax.disamb.modules.Modules04a; + +import bad.syntax.disamb.modules.Modules04a; + diff --git a/scribble-test/src/test/resources/bad/syntax/disamb/modules/Modules04b.scr b/scribble-test/src/test/resources/bad/syntax/disamb/modules/Modules04b.scr new file mode 100644 index 000000000..b3c2af706 --- /dev/null +++ b/scribble-test/src/test/resources/bad/syntax/disamb/modules/Modules04b.scr @@ -0,0 +1,4 @@ +module bad.syntax.disamb.modules.Modules04b; + +import bad.syntax.disamb.modules.Modules04b as Modules04b; // Simple name coincides with full name + diff --git a/scribble-test/src/test/resources/bad/syntax/disamb/modules/Modules04c.scr b/scribble-test/src/test/resources/bad/syntax/disamb/modules/Modules04c.scr new file mode 100644 index 000000000..9bd34473f --- /dev/null +++ b/scribble-test/src/test/resources/bad/syntax/disamb/modules/Modules04c.scr @@ -0,0 +1,11 @@ +module bad.syntax.disamb.modules.Modules04c; + + +import bad.syntax.disamb.modules.pack1.Foo1 as Modules04c; + + +global protocol Proto(role A, role B) +{ + 1() from A to B; + do Modules04c.Proto(A, B); +} diff --git a/scribble-test/src/test/resources/bad/syntax/disamb/modules/Modules04d.scr b/scribble-test/src/test/resources/bad/syntax/disamb/modules/Modules04d.scr new file mode 100644 index 000000000..e2c63fbfe --- /dev/null +++ b/scribble-test/src/test/resources/bad/syntax/disamb/modules/Modules04d.scr @@ -0,0 +1,7 @@ +module bad.syntax.disamb.modules.Modules04d; + + +import bad.syntax.disamb.modules.pack1.Foo1 as Foo; +import bad.syntax.disamb.modules.pack1.Foo2 as Foo; + + diff --git a/scribble-test/src/test/resources/bad/syntax/disamb/modules/Modules04e.scr b/scribble-test/src/test/resources/bad/syntax/disamb/modules/Modules04e.scr new file mode 100644 index 000000000..73444b86f --- /dev/null +++ b/scribble-test/src/test/resources/bad/syntax/disamb/modules/Modules04e.scr @@ -0,0 +1,4 @@ +module bad.syntax.disamb.modules.Modules04e; + +import bad.syntax.disamb.modules.pack1.Foo1 as Modules04e; + diff --git a/scribble-test/src/test/resources/bad/syntax/disamb/modules/pack1/Foo1.scr b/scribble-test/src/test/resources/bad/syntax/disamb/modules/pack1/Foo1.scr new file mode 100644 index 000000000..533686da4 --- /dev/null +++ b/scribble-test/src/test/resources/bad/syntax/disamb/modules/pack1/Foo1.scr @@ -0,0 +1,7 @@ +module bad.syntax.disamb.modules.pack1.Foo1; + + +global protocol Proto(role A, role B) +{ + 2() from A to B; +} diff --git a/scribble-test/src/test/resources/bad/syntax/disamb/modules/pack1/Foo2.scr b/scribble-test/src/test/resources/bad/syntax/disamb/modules/pack1/Foo2.scr new file mode 100644 index 000000000..2d1ac71ab --- /dev/null +++ b/scribble-test/src/test/resources/bad/syntax/disamb/modules/pack1/Foo2.scr @@ -0,0 +1,7 @@ +module bad.syntax.disamb.modules.pack1.Foo2; + + +global protocol Proto(role A, role B) +{ + 2() from A to B; +} diff --git a/scribble-test/src/test/resources/bad/syntax/disamb/modules/pack1/IGNORE b/scribble-test/src/test/resources/bad/syntax/disamb/modules/pack1/IGNORE new file mode 100644 index 000000000..e69de29bb diff --git a/scribble-test/src/test/resources/bad/syntax/disamb/nonrolearglist/NonRoleArgList01.scr b/scribble-test/src/test/resources/bad/syntax/disamb/nonrolearglist/NonRoleArgList01.scr new file mode 100644 index 000000000..018a05b52 --- /dev/null +++ b/scribble-test/src/test/resources/bad/syntax/disamb/nonrolearglist/NonRoleArgList01.scr @@ -0,0 +1,15 @@ +module bad.syntax.disamb.rolearglist.NonRoleArgList01; + + +type "..." from "..." as TTT; + + +global protocol Foo(role A, role B) +{ + do Bar(A, B); +} + +global protocol Bar(role C, role D) +{ + M1 from C to D; +} diff --git a/scribble-test/src/test/resources/bad/syntax/disamb/nonrolearglist/NonRoleArgList02.scr b/scribble-test/src/test/resources/bad/syntax/disamb/nonrolearglist/NonRoleArgList02.scr new file mode 100644 index 000000000..8a3149138 --- /dev/null +++ b/scribble-test/src/test/resources/bad/syntax/disamb/nonrolearglist/NonRoleArgList02.scr @@ -0,0 +1,12 @@ +module bad.syntax.disamb.rolearglist.NonRoleArgList02; + + +global protocol Foo(role A, role B) +{ + do Bar<1()>(A, B); +} + +global protocol Bar(role C, role D) +{ + 2(T) from C to D; +} diff --git a/scribble-test/src/test/resources/bad/syntax/disamb/protocoldecl/Test01.scr b/scribble-test/src/test/resources/bad/syntax/disamb/protocoldecl/Test01.scr new file mode 100644 index 000000000..14074a6f1 --- /dev/null +++ b/scribble-test/src/test/resources/bad/syntax/disamb/protocoldecl/Test01.scr @@ -0,0 +1,15 @@ +module bad.syntax.disamb.protocoldecl.Test01; + + +global protocol Proto1(role A, role B) +{ + 1() from A to B; + do Proto1(A, B); +} + + +global protocol Proto1(role A, role B) // Testing disamb +{ + 2() from A to B; +} + diff --git a/scribble-test/src/test/resources/bad/syntax/disamb/protocoldecl/Test02.scr b/scribble-test/src/test/resources/bad/syntax/disamb/protocoldecl/Test02.scr new file mode 100644 index 000000000..6bf106d07 --- /dev/null +++ b/scribble-test/src/test/resources/bad/syntax/disamb/protocoldecl/Test02.scr @@ -0,0 +1,9 @@ +module bad.syntax.disamb.protocoldecl.Test02; + + +global protocol Proto1(role A, role B) +{ + 1() from A to B; + do Proto2(A, B); // Testing disamb +} + diff --git a/scribble-test/src/test/resources/bad/syntax/disamb/recvarnode/Recursion01a.scr b/scribble-test/src/test/resources/bad/syntax/disamb/recvarnode/Recursion01a.scr new file mode 100644 index 000000000..3a7bbeb78 --- /dev/null +++ b/scribble-test/src/test/resources/bad/syntax/disamb/recvarnode/Recursion01a.scr @@ -0,0 +1,16 @@ +module bad.syntax.disamb.recvarnode.Recursion01a; + + +global protocol Recursion1a(role A, role B) +{ + //rec A { } // Currently OK. Disallow? + + rec X + { + l1() from A to B; + //continue X; + continue Y; // Uncomment bad, even if above line is commented + //l2() from A to B; // Uncomment bad + } +} + diff --git a/scribble-test/src/test/resources/bad/syntax/disamb/recvarnode/Recursion05b.scr b/scribble-test/src/test/resources/bad/syntax/disamb/recvarnode/Recursion05b.scr new file mode 100644 index 000000000..0f7e4adfc --- /dev/null +++ b/scribble-test/src/test/resources/bad/syntax/disamb/recvarnode/Recursion05b.scr @@ -0,0 +1,18 @@ +module bad.syntax.disamb.recvarnode.Recursion05b; + + +global protocol Recursion5b(role A, role B) +{ + rec X + { + l1() from A to B; + //continue X; // Uncomment makes the below rec bad + continue Y; // Uncomment bad + } + rec Y + { + l2() from B to A; + continue Y; // A bad "continue X" here tested in Recursion11 + } +} + diff --git a/scribble-test/src/test/resources/bad/syntax/disamb/recvarnode/Recursion05c.scr b/scribble-test/src/test/resources/bad/syntax/disamb/recvarnode/Recursion05c.scr new file mode 100644 index 000000000..feecdca7c --- /dev/null +++ b/scribble-test/src/test/resources/bad/syntax/disamb/recvarnode/Recursion05c.scr @@ -0,0 +1,19 @@ +module bad.syntax.disamb.recvarnode.Recursion05c; + + +global protocol Recursion5c(role A, role B) +{ + rec X + { + l1() from A to B; + //continue X; // Uncomment makes the below rec bad + //continue Y; // Uncomment bad + } + rec Y + { + l2() from B to A; + //continue Y; // A bad "continue X" here tested in Recursion11 + continue X; // A bad "continue X" here tested in Recursion11 + } +} + diff --git a/scribble-test/src/test/resources/bad/syntax/disamb/recvarnode/Recursion11.scr b/scribble-test/src/test/resources/bad/syntax/disamb/recvarnode/Recursion11.scr new file mode 100644 index 000000000..549cbc492 --- /dev/null +++ b/scribble-test/src/test/resources/bad/syntax/disamb/recvarnode/Recursion11.scr @@ -0,0 +1,17 @@ +module bad.syntax.disamb.recvarnode.Recursion11; + + +global protocol Recursion11(role A, role B) +{ + rec X + { + l1() from A to B; + } + rec Y + { + l2() from B to A; + //continue Y; + continue X; // Uncomment bad, even if above line is commented + } +} + diff --git a/scribble-test/src/test/resources/bad/syntax/disamb/rolearglist/RoleArgList02.scr b/scribble-test/src/test/resources/bad/syntax/disamb/rolearglist/RoleArgList02.scr new file mode 100644 index 000000000..dfbc07b3a --- /dev/null +++ b/scribble-test/src/test/resources/bad/syntax/disamb/rolearglist/RoleArgList02.scr @@ -0,0 +1,12 @@ +module bad.syntax.disamb.rolearglist.RoleArgList02; + + +global protocol Foo(role A, role B) +{ + do Bar(A, A); +} + +global protocol Bar(role C, role D) +{ + 1() from C to D; +} diff --git a/scribble-test/src/test/resources/bad/syntax/disamb/roledecl/Do13a.scr b/scribble-test/src/test/resources/bad/syntax/disamb/roledecl/Do13a.scr new file mode 100644 index 000000000..5304dfe5b --- /dev/null +++ b/scribble-test/src/test/resources/bad/syntax/disamb/roledecl/Do13a.scr @@ -0,0 +1,9 @@ +module bad.syntax.disamb.roledecl.Do13a; + + +global protocol Do13a(role A, role B) +{ + //l1() from A to B; // Uncomment is OK + do Do13a(A, B); + //l1() from A to B; // Uncomment is bad +} diff --git a/scribble-test/src/test/resources/bad/syntax/disamb/roledecl/Do23a.scr b/scribble-test/src/test/resources/bad/syntax/disamb/roledecl/Do23a.scr new file mode 100644 index 000000000..c648acf71 --- /dev/null +++ b/scribble-test/src/test/resources/bad/syntax/disamb/roledecl/Do23a.scr @@ -0,0 +1,22 @@ +module bad.syntax.disamb.roledecl.Do23a; + + +type "java.lang.String" from "rt.jar" as String; + + +// Overlaps with Do25? +global protocol Do23a(role A, role B) +{ + do Do23aux(A, B); +} + +global protocol Do23aux(role C, role D) +{ + do Do23a2(C, D); +} + +global protocol Do23a2(role E, role F) +//global protocol Do23a2(role E, role F) +{ + //X from E to F; // Uncomment OK +} diff --git a/scribble-test/src/test/resources/bad/syntax/disamb/rolenode/Test02.scr b/scribble-test/src/test/resources/bad/syntax/disamb/rolenode/Test02.scr new file mode 100644 index 000000000..13b0ce4da --- /dev/null +++ b/scribble-test/src/test/resources/bad/syntax/disamb/rolenode/Test02.scr @@ -0,0 +1,17 @@ +module bad.syntax.disamb.rolenode.Test02; + + +global protocol Proto1(role A, role B) +{ + choice at A + { + 1() from A to B; + 1() from A to C; + } + or + { + 2() from A to B; + 2() from B to C; + } +} + diff --git a/scribble-test/src/test/resources/bad/syntax/enabling/Test01.scr b/scribble-test/src/test/resources/bad/syntax/enabling/Test01.scr new file mode 100644 index 000000000..3b87de4a9 --- /dev/null +++ b/scribble-test/src/test/resources/bad/syntax/enabling/Test01.scr @@ -0,0 +1,21 @@ +module bad.syntax.enabling.Test02; + + +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + 1() from A to B; + 1() from B to C; + } + or + { + 2() from A to B; + } + or + { + 1() from B to C; + } +} + + diff --git a/scribble-test/src/test/resources/bad/syntax/enabling/Test02.scr b/scribble-test/src/test/resources/bad/syntax/enabling/Test02.scr new file mode 100644 index 000000000..3dbd21ffe --- /dev/null +++ b/scribble-test/src/test/resources/bad/syntax/enabling/Test02.scr @@ -0,0 +1,20 @@ +module bad.syntax.enabling.Test01; + + +global protocol Proto1(role A, role B, role C) +{ + //0() from B to C; + choice at A + { + 0() from B to C; + 1() from A to B; + 1() from B to C; + } + or + { + 0() from B to C; + 2() from A to B; + 2() from B to C; + } +} + diff --git a/scribble-test/src/test/resources/bad/syntax/rolecollection/gprotocoldecl/Test01.scr b/scribble-test/src/test/resources/bad/syntax/rolecollection/gprotocoldecl/Test01.scr new file mode 100644 index 000000000..585d1cd00 --- /dev/null +++ b/scribble-test/src/test/resources/bad/syntax/rolecollection/gprotocoldecl/Test01.scr @@ -0,0 +1,15 @@ +module bad.syntax.rolecollection.gprotocoldecl.Test01; + + +global protocol Foo(role A, role B) +{ + 1() from A to B; + do Bar(A, B); + 2() from A to B; +} + +aux global protocol Bar(role A, role B) // Testing bad unused role decls (wrt. subprotocol collected role occurrences) -- actually, allow due to aux? +{ + +} + diff --git a/scribble-test/src/test/resources/bad/todo/Choice07a.scr b/scribble-test/src/test/resources/bad/todo/Choice07a.scr new file mode 100644 index 000000000..3487c422a --- /dev/null +++ b/scribble-test/src/test/resources/bad/todo/Choice07a.scr @@ -0,0 +1,25 @@ +module bad.wfchoice.gchoice.Choice07a; + + +global protocol Choice7a(role A, role B) +{ + choice at A + { + /*// TODO + par + { + l1() from A to B; + } + and + { + l2() from B to A; // Uncomment is bad + l2() from A to B; + }*/ + } + or + { + //l2() from A to B; // Uncomment is bad + l3() from A to B; + } +} + diff --git a/scribble-test/src/test/resources/bad/todo/Choice07b.scr b/scribble-test/src/test/resources/bad/todo/Choice07b.scr new file mode 100644 index 000000000..23d613da7 --- /dev/null +++ b/scribble-test/src/test/resources/bad/todo/Choice07b.scr @@ -0,0 +1,25 @@ +module bad.wfchoice.gchoice.Choice07b; + + +global protocol Choice7b(role A, role B) +{ + choice at A + { + /*//TODO + par + { + l1() from A to B; + } + and + { + //l2() from B to A; // Uncomment is bad + l2() from A to B; + }*/ + } + or + { + l2() from A to B; // Uncomment is bad + l3() from A to B; + } +} + diff --git a/scribble-test/src/test/resources/bad/todo/IGNORE b/scribble-test/src/test/resources/bad/todo/IGNORE new file mode 100644 index 000000000..e69de29bb diff --git a/scribble-test/src/test/resources/bad/todo/Modules02.scr b/scribble-test/src/test/resources/bad/todo/Modules02.scr new file mode 100644 index 000000000..e6414d690 --- /dev/null +++ b/scribble-test/src/test/resources/bad/todo/Modules02.scr @@ -0,0 +1,12 @@ +module bad.syntax.disamb.modules.Modules02; + + +global protocol Foo(role A, role B) +{ + +} + +local protocol Foo(role A, role B) // TODO: local not parsed +{ + +} diff --git a/scribble-test/src/test/resources/bad/todo/Recursion12.scr b/scribble-test/src/test/resources/bad/todo/Recursion12.scr new file mode 100644 index 000000000..6a042547f --- /dev/null +++ b/scribble-test/src/test/resources/bad/todo/Recursion12.scr @@ -0,0 +1,21 @@ +module base.recursion.Recursion12; + + +global protocol Recursion12(role A, role B) +{ + /*// TODO + par + { + rec X + { + l1() from A to B; + continue X; + } + } + and + { + l2() from B to A; + }*/ + l3() from B to A; // Uncommented bad +} + diff --git a/scribble-test/src/test/resources/bad/todo/Recursion14a.scr b/scribble-test/src/test/resources/bad/todo/Recursion14a.scr new file mode 100644 index 000000000..744ae9c2c --- /dev/null +++ b/scribble-test/src/test/resources/bad/todo/Recursion14a.scr @@ -0,0 +1,23 @@ +module base.recursion.Recursion14a; + + +global protocol Recursion14a(role A, role B) +{ + rec X + { + l1() from A to B; + do Y: base.recursion.Recursion14.Recursion14a(A, B); // TODO + do X: base.recursion.Recursion14.Recursion14a(A, B); // Uncomment OK if above line is commented // TODO + //do base.recursion.Recursion14.Recursion14a(A, B); // Uncomment bad, even if above two lines are commented + } +} + +global protocol Recursion14a(role A, role B) +{ + rec X + { + l1() from A to B; + continue X; + } +} + diff --git a/scribble-test/src/test/resources/bad/todo/Recursion19b.scr b/scribble-test/src/test/resources/bad/todo/Recursion19b.scr new file mode 100644 index 000000000..b7568a80b --- /dev/null +++ b/scribble-test/src/test/resources/bad/todo/Recursion19b.scr @@ -0,0 +1,22 @@ +module bad.reach.globals.grecursion.Recursion19b; + + +global protocol Proto1(role A, role B) +{ + rec X + { + choice at A + { + continue X; + // CHECKME: was previously considered bad -- but now, projection implicitly removes this continue so the 1() is not a bad continuation any more... + // TODO: check as global WF instead? unguarded continue? (cf. reachability) + // Or consider good? maybe consistent with, e.g., rec X { continue X; }, already being discarded + } + or + { + 2() from A to B; + } + 1() from A to B; // Reachability error -- comes out as a global model error if that pass is done first (tail recursion needed as syntactic check prior to model checking) // Reachability now done before model check + } +} + diff --git a/scribble-test/src/test/resources/bad/wfchoice/enabling/fourparty/Test01.scr b/scribble-test/src/test/resources/bad/wfchoice/enabling/fourparty/Test01.scr new file mode 100644 index 000000000..e3fcacddb --- /dev/null +++ b/scribble-test/src/test/resources/bad/wfchoice/enabling/fourparty/Test01.scr @@ -0,0 +1,28 @@ +module bad.wfchoice.enabling.fourparty.Test01; + + +// Under -f17, the original choice subject problem is gone, but we get a role-progress error instead (without fairness) +global protocol Proto1(role A, role B, role C, role D) +{ + choice at A + { + 1() from A to B; + rec X + { + 2() from B to C; + choice at C + { + 2() from C to A; + continue X; // Enabling error, with the continue inside this choice scope (continue factored out after choice is not enabling error) + } + or + { + () from C to A; + () from C to D; + continue X; + } + } + } +} + + diff --git a/scribble-test/src/test/resources/bad/wfchoice/enabling/threeparty/Test01.scr b/scribble-test/src/test/resources/bad/wfchoice/enabling/threeparty/Test01.scr new file mode 100644 index 000000000..12e5ab764 --- /dev/null +++ b/scribble-test/src/test/resources/bad/wfchoice/enabling/threeparty/Test01.scr @@ -0,0 +1,17 @@ +module bad.wfchoice.enabling.threeparty.Test01; + + +global protocol Proto1(role A, role B, role C) +{ + 1() from A to B; + 2() from A to C; + choice at A + { + do Proto1(A, B, C); + } + or + { + 2() from A to B; + 2() from A to C; + } +} diff --git a/scribble-test/src/test/resources/bad/wfchoice/enabling/threeparty/Test02.scr b/scribble-test/src/test/resources/bad/wfchoice/enabling/threeparty/Test02.scr new file mode 100644 index 000000000..e8c6a7485 --- /dev/null +++ b/scribble-test/src/test/resources/bad/wfchoice/enabling/threeparty/Test02.scr @@ -0,0 +1,23 @@ +module bad.wfchoice.enabling.threeparty.Test02; + + +// Cf. good.wfchoice.gchoice.Choice11; +global protocol Proto1(role A, role B, role C) +{ + rec X + { + 1() from B to C; // bad enabling + choice at A + { + 1() from A to C; + continue X; + } + or + { + 2() from A to B; + 2() from A to C; + } + } +} + + diff --git a/scribble-test/src/test/resources/bad/wfchoice/enabling/threeparty/Test03a.scr b/scribble-test/src/test/resources/bad/wfchoice/enabling/threeparty/Test03a.scr new file mode 100644 index 000000000..54c18699f --- /dev/null +++ b/scribble-test/src/test/resources/bad/wfchoice/enabling/threeparty/Test03a.scr @@ -0,0 +1,28 @@ +module bad.wfchoice.enabling.threeparty.Test03a; + + +global protocol Proto1(role A, role B, role C) +{ + rec X + { + choice at A + { + 1() from A to B; + choice at B + { + 1() from B to C; + continue X; // choice at A, but A not enabled + } + or + { + 3() from B to C; + } + } + or + { + 2() from A to B; + 2() from B to C; + } + } +} + diff --git a/scribble-test/src/test/resources/bad/wfchoice/enabling/threeparty/Test03b.scr b/scribble-test/src/test/resources/bad/wfchoice/enabling/threeparty/Test03b.scr new file mode 100644 index 000000000..53548657b --- /dev/null +++ b/scribble-test/src/test/resources/bad/wfchoice/enabling/threeparty/Test03b.scr @@ -0,0 +1,31 @@ +module bad.wfchoice.enabling.threeparty.Test03b; + + +// Cf. module good.wfchoice.enabling.threeparty.Test03b; +global protocol Proto1(role A, role B, role C) +{ + rec X + { + choice at A + { + 1() from A to B; + choice at B + { + 1() from B to C; + continue X; + } + or + { + 3() from B to C; + continue X; + } + //continue X; + } + or + { + 2() from A to B; + 2() from B to C; + } + } +} + diff --git a/scribble-test/src/test/resources/bad/wfchoice/enabling/twoparty/Test01a.scr b/scribble-test/src/test/resources/bad/wfchoice/enabling/twoparty/Test01a.scr new file mode 100644 index 000000000..940aec221 --- /dev/null +++ b/scribble-test/src/test/resources/bad/wfchoice/enabling/twoparty/Test01a.scr @@ -0,0 +1,16 @@ +module bad.wfchoice.enabling.twoparty.Test01a; + + +global protocol Proto1(role A, role B, role C, role D) +{ + rec X + { + choice at A + { + 1() from A to B; + continue X; + } + 1() from C to D; // Enabled violation once unfolded + } +} + diff --git a/scribble-test/src/test/resources/bad/wfchoice/enabling/twoparty/Test01b.scr b/scribble-test/src/test/resources/bad/wfchoice/enabling/twoparty/Test01b.scr new file mode 100644 index 000000000..08f86130f --- /dev/null +++ b/scribble-test/src/test/resources/bad/wfchoice/enabling/twoparty/Test01b.scr @@ -0,0 +1,16 @@ +module bad.wfchoice.enabling.twoparty.Test01b; + + +global protocol Proto1(role A, role B, role C, role D) +{ + rec X + { + 1() from C to D; // Enabled violation once unfolded + choice at A + { + 1() from A to B; + continue X; + } + } +} + diff --git a/scribble-test/src/test/resources/bad/wfchoice/enabling/twoparty/Test01c.scr b/scribble-test/src/test/resources/bad/wfchoice/enabling/twoparty/Test01c.scr new file mode 100644 index 000000000..77cfc4127 --- /dev/null +++ b/scribble-test/src/test/resources/bad/wfchoice/enabling/twoparty/Test01c.scr @@ -0,0 +1,21 @@ +module bad.wfchoice.enabling.twoparty.Test01c; + + +global protocol Proto1(role A, role B, role C, role D) +{ + rec X + { + choice at A + { + 1() from A to B; + continue X; + } + or + { + 2() from A to B; + continue X; + } + 3() from C to D; // Enabled violation once unfolded + } +} + diff --git a/scribble-test/src/test/resources/bad/wfchoice/gchoice/Choice01.scr b/scribble-test/src/test/resources/bad/wfchoice/gchoice/Choice01.scr new file mode 100644 index 000000000..aff45c614 --- /dev/null +++ b/scribble-test/src/test/resources/bad/wfchoice/gchoice/Choice01.scr @@ -0,0 +1,14 @@ +module bad.wfchoice.gchoice.Choice01; + +global protocol Choice1(role A, role B) +{ + choice at A + { + l1() from A to B; + } + or + { + l1() from A to B; // Uncomment is bad + l2() from A to B; + } +} diff --git a/scribble-test/src/test/resources/bad/wfchoice/gchoice/Choice02.scr b/scribble-test/src/test/resources/bad/wfchoice/gchoice/Choice02.scr new file mode 100644 index 000000000..a05c1efbb --- /dev/null +++ b/scribble-test/src/test/resources/bad/wfchoice/gchoice/Choice02.scr @@ -0,0 +1,10 @@ +module bad.wfchoice.gchoice.Choice02; + +global protocol Choice2(role A, role B) +{ + choice at A + { + l1() from B to A; // Uncomment is bad + l1() from A to B; + } +} diff --git a/scribble-test/src/test/resources/bad/wfchoice/gchoice/Choice05a.scr b/scribble-test/src/test/resources/bad/wfchoice/gchoice/Choice05a.scr new file mode 100644 index 000000000..1ee8b348a --- /dev/null +++ b/scribble-test/src/test/resources/bad/wfchoice/gchoice/Choice05a.scr @@ -0,0 +1,32 @@ +module bad.wfchoice.gchoice.Choice05a; + + +global protocol Choice5a(role A, role B) +{ + choice at B + { + //l1() from B to A; // Comment is bad + choice at A + { + l1() from A to B; + } + or + { + l2() from A to B; + } + } + or + { + choice at B + { + l2() from B to A; + } + or + { + l3() from B to A; + //l2() from B to A; // Uncomment OK unless l3() is commented + //l1() from B to A; // Uncomment OK unless l3() is commented + } + } +} + diff --git a/scribble-test/src/test/resources/bad/wfchoice/gchoice/Choice05b.scr b/scribble-test/src/test/resources/bad/wfchoice/gchoice/Choice05b.scr new file mode 100644 index 000000000..daf3d5900 --- /dev/null +++ b/scribble-test/src/test/resources/bad/wfchoice/gchoice/Choice05b.scr @@ -0,0 +1,34 @@ +module bad.wfchoice.gchoice.Choice05b; + + +global protocol Choice5b(role A, role B) +{ + choice at B + { + l1() from B to A; // Comment is bad + choice at A + { + l1() from A to B; + } + or + { + l2() from A to B; + } + } + or + { + choice at B + { + l2() from B to A; + l3() from B to A; // Comment is still bad + } + or + { + //l3() from B to A; + l2() from B to A; // Uncomment OK unless l3() is commented + l4() from B to A; + //l1() from B to A; // Uncomment OK unless l3() is commented + } + } +} + diff --git a/scribble-test/src/test/resources/bad/wfchoice/gchoice/Choice05c.scr b/scribble-test/src/test/resources/bad/wfchoice/gchoice/Choice05c.scr new file mode 100644 index 000000000..1557e3fa9 --- /dev/null +++ b/scribble-test/src/test/resources/bad/wfchoice/gchoice/Choice05c.scr @@ -0,0 +1,32 @@ +module bad.wfchoice.gchoice.Choice05c; + + +global protocol Choice5c(role A, role B) +{ + choice at B + { + l1() from B to A; // Comment is bad + choice at A + { + l1() from A to B; + } + or + { + l2() from A to B; + } + } + or + { + choice at B + { + l2() from B to A; + } + or + { + //l3() from B to A; + //l2() from B to A; // Uncomment OK unless l3() is commented + l1() from B to A; // Uncomment OK unless l3() is commented + } + } +} + diff --git a/scribble-test/src/test/resources/bad/wfchoice/gchoice/Choice06.scr b/scribble-test/src/test/resources/bad/wfchoice/gchoice/Choice06.scr new file mode 100644 index 000000000..a8d23ffb3 --- /dev/null +++ b/scribble-test/src/test/resources/bad/wfchoice/gchoice/Choice06.scr @@ -0,0 +1,28 @@ +module bad.wfchoice.gchoice.Choice06; + + +global protocol Choice6(role A, role B) +{ + choice at A + { + l1() from A to B; + } + or + { + () from A to B; + } + l1() from A to B; + () from A to B; + choice at A + { + //l1() from A to B; // Comment is bad + () from A to B; + 2() from A to B; + } + or + { + () from A to B; + 3() from B to A; + } +} + diff --git a/scribble-test/src/test/resources/bad/wfchoice/gchoice/Choice08.scr b/scribble-test/src/test/resources/bad/wfchoice/gchoice/Choice08.scr new file mode 100644 index 000000000..a1261bbbe --- /dev/null +++ b/scribble-test/src/test/resources/bad/wfchoice/gchoice/Choice08.scr @@ -0,0 +1,21 @@ +module bad.wfchoice.gchoice.Choice08; + + +global protocol Choice8(role A, role B, role C) +{ + choice at A + { + l1() from A to B; + l2() from B to C; + //l4() from C to A; // Uncomment makes it OK + } + or + { + l2() from A to B; + //l1() from B to C; // Comment is bad + l2() from B to C; + l4() from C to A; + } + l4() from A to C; +} + diff --git a/scribble-test/src/test/resources/bad/wfchoice/gchoice/Choice09a.scr b/scribble-test/src/test/resources/bad/wfchoice/gchoice/Choice09a.scr new file mode 100644 index 000000000..7f719485a --- /dev/null +++ b/scribble-test/src/test/resources/bad/wfchoice/gchoice/Choice09a.scr @@ -0,0 +1,30 @@ +module bad.wfchoice.gchoice.Choice09a; + + +global protocol Proto1(role A, role B, role C) +{ + 3() from A to C; + rec Y + { + 2() from A to B; // Uncomment is bad (non-enabled B / non-disjoint labels) + 2a() from B to A; + rec X + { + 1() from A to B; + choice at A + { + 2() from A to B; + continue X; // Testing project choice subject "inference", and testing continue-only choice block + } + or + { + continue Y; // Different continue-only-blocks, tests FSM building + } + or + { + 4() from A to B; + } + } + } +} + diff --git a/scribble-test/src/test/resources/bad/wfchoice/gchoice/Choice09b.scr b/scribble-test/src/test/resources/bad/wfchoice/gchoice/Choice09b.scr new file mode 100644 index 000000000..4174eb06d --- /dev/null +++ b/scribble-test/src/test/resources/bad/wfchoice/gchoice/Choice09b.scr @@ -0,0 +1,34 @@ +module bad.wfchoice.gchoice.Choice09b; + + +global protocol Proto1(role A, role B, role C) +{ + 3() from A to C; + rec Y + { + 2() from A to B; // Uncomment is bad (non-enabled B / non-disjoint labels) + 2a() from B to A; + rec X + { + 1() from A to B; + choice at A + { + 2() from A to B; + continue X; // Testing project choice subject "inference", and testing continue-only choice block + } + or + { + continue X; + } + or + { + continue Y; // Different continue-only-blocks, tests FSM building + } + or + { + 4() from A to B; + } + } + } +} + diff --git a/scribble-test/src/test/resources/bad/wfchoice/gchoice/Choice09c.scr b/scribble-test/src/test/resources/bad/wfchoice/gchoice/Choice09c.scr new file mode 100644 index 000000000..c93ea8b2d --- /dev/null +++ b/scribble-test/src/test/resources/bad/wfchoice/gchoice/Choice09c.scr @@ -0,0 +1,34 @@ +module bad.wfchoice.gchoice.Choice09c; + + +global protocol Proto1(role A, role B, role C) +{ + 3() from A to C; + rec Y + { + 2() from A to B; // Uncomment is bad (non-enabled B / non-disjoint labels) + 2a() from B to A; + rec X + { + 1() from A to B; + choice at A + { + continue Y; // Different continue-only-blocks, tests FSM building + } + or + { + 2() from A to B; + continue X; // Testing project choice subject "inference", and testing continue-only choice block + } + or + { + continue X; + } + or + { + 4() from A to B; + } + } + } +} + diff --git a/scribble-test/src/test/resources/bad/wfchoice/gchoice/Choice10a.scr b/scribble-test/src/test/resources/bad/wfchoice/gchoice/Choice10a.scr new file mode 100644 index 000000000..af2cab667 --- /dev/null +++ b/scribble-test/src/test/resources/bad/wfchoice/gchoice/Choice10a.scr @@ -0,0 +1,32 @@ +module bad.wfchoice.gchoice.Choice10a; + + +global protocol Proto1(role A, role B) +{ + rec X + { + 1() from A to B; + choice at A + { + continue X; + } + or + { + rec Y + { + 2() from A to B; + choice at A + { + //continue X; + continue Y; + } + or + { + 2() from A to B; + } + } + } + } +} + + diff --git a/scribble-test/src/test/resources/bad/wfchoice/gchoice/Choice10b.scr b/scribble-test/src/test/resources/bad/wfchoice/gchoice/Choice10b.scr new file mode 100644 index 000000000..714fe692b --- /dev/null +++ b/scribble-test/src/test/resources/bad/wfchoice/gchoice/Choice10b.scr @@ -0,0 +1,31 @@ +module bad.wfchoice.gchoice.Choice10b; + + +global protocol Proto1(role A, role B) +{ + rec X + { + //1() from A to B; + choice at A + { + continue X; + } + or + { + rec Y + { + 2() from A to B; + choice at A + { + continue X; + } + or + { + 2() from A to B; + } + } + } + } +} + + diff --git a/scribble-test/src/test/resources/bad/wfchoice/gdo/params/Test01.scr b/scribble-test/src/test/resources/bad/wfchoice/gdo/params/Test01.scr new file mode 100644 index 000000000..d870c4ec2 --- /dev/null +++ b/scribble-test/src/test/resources/bad/wfchoice/gdo/params/Test01.scr @@ -0,0 +1,23 @@ +module bad.wfchoice.gdo.params.Test01; + + +global protocol Foo(role A, role B) +{ + choice at A + { + M1 from A to B; + 1() from A to B; + } + or + { + do Bar(A, B); + 2() from A to B; + } +} + + +aux global protocol Bar(role C, role D) +{ + M2 from C to D; +} + diff --git a/scribble-test/src/test/resources/bad/wfchoice/gdo/params/Test02.scr b/scribble-test/src/test/resources/bad/wfchoice/gdo/params/Test02.scr new file mode 100644 index 000000000..0d95bbf07 --- /dev/null +++ b/scribble-test/src/test/resources/bad/wfchoice/gdo/params/Test02.scr @@ -0,0 +1,23 @@ +module bad.wfchoice.gdo.params.Test02; + + +global protocol Foo(role A, role B) +{ + choice at A + { + 1() from A to B; + 2() from B to A; + } + or + { + do Bar<1()>(A, B); + 3() from B to A; + } +} + + +aux global protocol Bar(role C, role D) +{ + M from C to D; +} + diff --git a/scribble-test/src/test/resources/bad/wfchoice/gdo/params/Test03.scr b/scribble-test/src/test/resources/bad/wfchoice/gdo/params/Test03.scr new file mode 100644 index 000000000..0ab414bae --- /dev/null +++ b/scribble-test/src/test/resources/bad/wfchoice/gdo/params/Test03.scr @@ -0,0 +1,25 @@ +module bad.wfchoice.gdo.params.Test03; + + +sig "foo" from "bar" as M1; + + +global protocol Foo(role A, role B) +{ + choice at A + { + M1 from A to B; + } + or + { + do Bar(A, B); + do Bar<1()>(A, B); + } +} + + +aux global protocol Bar(role A, role B) +{ + M from A to B; +} +//*/ diff --git a/scribble-test/src/test/resources/bad/wfchoice/merge/Test01.scr b/scribble-test/src/test/resources/bad/wfchoice/merge/Test01.scr new file mode 100644 index 000000000..33640a0c4 --- /dev/null +++ b/scribble-test/src/test/resources/bad/wfchoice/merge/Test01.scr @@ -0,0 +1,21 @@ +module bad.wfchoice.merge.Test01; + + +global protocol Proto1(role A, role B, role C) +{ + // Would be OK with "syntactic merge", but currently bad wrt. basic non-det interpretation + choice at A + { + 1() from A to B; + 2() from B to C; + 4() from A to C; + } + or + { + 3() from A to B; + 2() from B to C; + 5() from A to C; + } +} + + diff --git a/scribble-test/src/test/resources/bad/wfchoice/oldwfchoice/IGNORE b/scribble-test/src/test/resources/bad/wfchoice/oldwfchoice/IGNORE new file mode 100644 index 000000000..e69de29bb diff --git a/scribble-test/src/test/resources/bad/wfchoice/oldwfchoice/globals/gchoice/Choice05b.scr b/scribble-test/src/test/resources/bad/wfchoice/oldwfchoice/globals/gchoice/Choice05b.scr new file mode 100644 index 000000000..0777ac447 --- /dev/null +++ b/scribble-test/src/test/resources/bad/wfchoice/oldwfchoice/globals/gchoice/Choice05b.scr @@ -0,0 +1,35 @@ +module bad.oldwfchoice.gchoice.Choice05b; + + +// Bad only for -oldwf; good by default +global protocol Choice5b(role A, role B) +{ + choice at B + { + l1() from B to A; // Comment is bad + choice at A + { + l1() from A to B; + } + or + { + l2() from A to B; + } + } + or + { + choice at B + { + l2() from B to A; + //l3() from B to A; // Comment is still bad + } + or + { + ////l3() from B to A; + l2() from B to A; // Uncomment OK unless l3() is commented + //l4() from B to A; + ////l1() from B to A; // Uncomment OK unless l3() is commented + } + } +} + diff --git a/scribble-test/src/test/resources/bad/wfchoice/oldwfchoice/globals/gchoice/Choice06.scr b/scribble-test/src/test/resources/bad/wfchoice/oldwfchoice/globals/gchoice/Choice06.scr new file mode 100644 index 000000000..13610941c --- /dev/null +++ b/scribble-test/src/test/resources/bad/wfchoice/oldwfchoice/globals/gchoice/Choice06.scr @@ -0,0 +1,28 @@ +module bad.wfchoice.oldwfchoice.gchoice.Choice06; + + +global protocol Choice6(role A, role B) +{ + choice at A + { + l1() from A to B; + } + or + { + () from A to B; + } + l1() from A to B; + () from A to B; + choice at A + { + ////l1() from A to B; // Comment is bad + () from A to B; + //2() from A to B; + } + or + { + () from A to B; + //3() from B to A; + } +} + diff --git a/scribble-test/src/test/resources/bad/wfchoice/oldwfchoice/globals/gchoice/Choice08.scr b/scribble-test/src/test/resources/bad/wfchoice/oldwfchoice/globals/gchoice/Choice08.scr new file mode 100644 index 000000000..e6b108450 --- /dev/null +++ b/scribble-test/src/test/resources/bad/wfchoice/oldwfchoice/globals/gchoice/Choice08.scr @@ -0,0 +1,21 @@ +module bad.wfchoice.oldwfchoice.gchoice.Choice08; + + +global protocol Choice8(role A, role B, role C) +{ + choice at A + { + l1() from A to B; + l2() from B to C; + ////l4() from C to A; // Uncomment makes it OK + } + or + { + l2() from A to B; + ////l1() from B to C; // Comment is bad + l2() from B to C; + //l4() from C to A; + } + l2() from C to A; +} + diff --git a/scribble-test/src/test/resources/bad/wfchoice/oldwfchoice/globals/gchoice/Choice09.scr b/scribble-test/src/test/resources/bad/wfchoice/oldwfchoice/globals/gchoice/Choice09.scr new file mode 100644 index 000000000..20c262d3f --- /dev/null +++ b/scribble-test/src/test/resources/bad/wfchoice/oldwfchoice/globals/gchoice/Choice09.scr @@ -0,0 +1,19 @@ +module bad.wfchoice.oldwfchoice.gchoice.Choice09; + + +global protocol Foo(role A, role B) +{ + choice at A + { + 1() from A to B; + } + or + { + 2() from A to B; + } + or + { + 2() from A to B; + } +} + diff --git a/scribble-test/src/test/resources/bad/wfchoice/oldwfchoice/globals/gchoice/Choice10.scr b/scribble-test/src/test/resources/bad/wfchoice/oldwfchoice/globals/gchoice/Choice10.scr new file mode 100644 index 000000000..be27df308 --- /dev/null +++ b/scribble-test/src/test/resources/bad/wfchoice/oldwfchoice/globals/gchoice/Choice10.scr @@ -0,0 +1,34 @@ +module bad.wfchoice.oldwfchoice.gchoice.Choice10; + + +global protocol Proto1(role A, role B, role C) +{ + 3() from A to C; + rec Y + { + () from A to B; + 2a() from B to A; + rec X + { + 1() from A to B; + choice at A + { + //2() from A to B; + continue X; // Testing project choice subject "inference", and testing continue-only choice block + } + or + { + continue X; + } + or + { + continue Y; // Different continue-only-blocks, tests FSM building + } + or + { + 4() from A to B; + } + } + } +} + diff --git a/scribble-test/src/test/resources/good/efsm/gchoice/Test02.scr b/scribble-test/src/test/resources/good/efsm/gchoice/Test02.scr new file mode 100644 index 000000000..e9b379c7b --- /dev/null +++ b/scribble-test/src/test/resources/good/efsm/gchoice/Test02.scr @@ -0,0 +1,18 @@ +module good.efsm.gchoice.Test02; + + +global protocol Foo(role A, role B) +{ + 0() from A to B; + choice at A + { + 1a() from A to B; + } + or + { + 2a() from A to B; + 2b() from B to A; + } + 3() from B to A; +} + diff --git a/scribble-test/src/test/resources/good/efsm/gchoice/Test03.scr b/scribble-test/src/test/resources/good/efsm/gchoice/Test03.scr new file mode 100644 index 000000000..ebd95ff38 --- /dev/null +++ b/scribble-test/src/test/resources/good/efsm/gchoice/Test03.scr @@ -0,0 +1,22 @@ +module good.efsm.gchoice.Test03; + + +global protocol Foo(role A, role B) +{ + choice at A // unary choice with continuation + { + 1() from A to B; + } + rec X + { + choice at A + { + 2() from A to B; + continue X; + } + or + { + 3() from A to B; + } + } +} diff --git a/scribble-test/src/test/resources/good/efsm/gchoice/Test09.scr b/scribble-test/src/test/resources/good/efsm/gchoice/Test09.scr new file mode 100644 index 000000000..c67f743bb --- /dev/null +++ b/scribble-test/src/test/resources/good/efsm/gchoice/Test09.scr @@ -0,0 +1,22 @@ +//$ bin/scribblec.sh scribble-test/src/test/resources/good/efsm/gchoice/Test09.scr + +module good.efsm.gchoice.Test09; + + +global protocol Foo(role A, role B) +{ + rec X + { + choice at A + { + 1() from A to B; + } + or + { + 1() from A to B; + } + continue X; // Testing recursion edge replacement cornercase (length 1 non-det choice paths are merged as a single case) + } +} + + diff --git a/scribble-test/src/test/resources/good/efsm/gchoice/Test10.scr b/scribble-test/src/test/resources/good/efsm/gchoice/Test10.scr new file mode 100644 index 000000000..478ad2ac0 --- /dev/null +++ b/scribble-test/src/test/resources/good/efsm/gchoice/Test10.scr @@ -0,0 +1,39 @@ +module good.efsm.gchoice.Test10; + + +global protocol Proto1(role A, role B) +{ + rec X + { + choice at A + { + 1() from A to B; + } + or + { + 2() from A to B; + choice at B + { + 2() from B to A; + continue X; + } + or + { + 4a() from B to A; + } + or + { + 4b() from B to A; + } + } + } + choice at A + { + 3a() from A to B; + } + or { + 3b() from A to B; + } +} + + diff --git a/scribble-test/src/test/resources/good/efsm/gchoice/Test11.scr b/scribble-test/src/test/resources/good/efsm/gchoice/Test11.scr new file mode 100644 index 000000000..e7ca4ccd1 --- /dev/null +++ b/scribble-test/src/test/resources/good/efsm/gchoice/Test11.scr @@ -0,0 +1,16 @@ +module good.efsm.gchoice.Test11; + + +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + 1() from A to B; + choice at B + { + 2() from B to C; // Graph building (popping choice block into a null parent choice block context) + } + } +} + + diff --git a/scribble-test/src/test/resources/good/efsm/gchoice/Test12a.scr b/scribble-test/src/test/resources/good/efsm/gchoice/Test12a.scr new file mode 100644 index 000000000..d7a3d130a --- /dev/null +++ b/scribble-test/src/test/resources/good/efsm/gchoice/Test12a.scr @@ -0,0 +1,20 @@ +module good.efsm.gchoice.Test12a; + + +global protocol Proto1(role A, role B) +{ + rec X + { + choice at A + { + 1() from A to B; + } + or + { + 2() from A to B; + } + continue X; // EFSM building -- multiple predecessors for continue-edge replacement + } +} + + diff --git a/scribble-test/src/test/resources/good/efsm/gchoice/Test12b.scr b/scribble-test/src/test/resources/good/efsm/gchoice/Test12b.scr new file mode 100644 index 000000000..37ef3ac75 --- /dev/null +++ b/scribble-test/src/test/resources/good/efsm/gchoice/Test12b.scr @@ -0,0 +1,23 @@ +module good.efsm.gchoice.Test12b; + + +global protocol Proto1(role A, role B, role C) +{ + rec X + { + 0() from A to B; + 0() from B to C; + choice at A + { + 1() from A to B; + 1() from B to C; + } + or + { + 2() from A to B; + 2() from B to C; + } + continue X; // EFSM building -- multiple predecessors for continue-edge replacement + } +} + diff --git a/scribble-test/src/test/resources/good/efsm/gchoice/Test13.scr b/scribble-test/src/test/resources/good/efsm/gchoice/Test13.scr new file mode 100644 index 000000000..46be3d259 --- /dev/null +++ b/scribble-test/src/test/resources/good/efsm/gchoice/Test13.scr @@ -0,0 +1,30 @@ +module good.efsm.gchoice.Test13; + + +global protocol Proto1(role A, role B, role C) +{ + rec X + { + choice at A + { + 1() from A to B; + choice at B + { + 1() from B to A; + 1() from A to C; + } + } + or + { + 2() from A to B; + choice at B + { + 2() from B to A; + 2() from A to C; + } + } + continue X; // EFSM building -- multiple predecessors for continue-edge replacement + } +} + + diff --git a/scribble-test/src/test/resources/good/efsm/gcontinue/choiceunguarded/Test01a.scr b/scribble-test/src/test/resources/good/efsm/gcontinue/choiceunguarded/Test01a.scr new file mode 100644 index 000000000..ba6f3a0eb --- /dev/null +++ b/scribble-test/src/test/resources/good/efsm/gcontinue/choiceunguarded/Test01a.scr @@ -0,0 +1,21 @@ +module good.efsm.gcontinue.choiceunguarded.Test01a; + + +// Cf. -minfsm +global protocol Proto1(role A, role B) +{ + rec X + { + 1() from A to B; + choice at A + { + continue X; // Not "isomorphic" to a single continue X, because (in general) non-det not bisim equiv (cf. language equiv) -- so no "syntatic collapse" to single case + } + or + { + continue X; + } + } +} + + diff --git a/scribble-test/src/test/resources/good/efsm/gcontinue/choiceunguarded/Test01b.scr b/scribble-test/src/test/resources/good/efsm/gcontinue/choiceunguarded/Test01b.scr new file mode 100644 index 000000000..e004a283c --- /dev/null +++ b/scribble-test/src/test/resources/good/efsm/gcontinue/choiceunguarded/Test01b.scr @@ -0,0 +1,22 @@ +module good.efsm.gcontinue.choiceunguarded.Test01b; + + +// Cf. -minfsm +global protocol Proto1(role A, role B) +{ + rec X + { + 1() from A to B; + choice at A + { + continue X; + } + or + { + 2() from A to B; + continue X; + } + } +} + + diff --git a/scribble-test/src/test/resources/good/efsm/gcontinue/choiceunguarded/Test01c.scr b/scribble-test/src/test/resources/good/efsm/gcontinue/choiceunguarded/Test01c.scr new file mode 100644 index 000000000..ddbbe13b2 --- /dev/null +++ b/scribble-test/src/test/resources/good/efsm/gcontinue/choiceunguarded/Test01c.scr @@ -0,0 +1,15 @@ +module good.efsm.gcontinue.choiceunguarded.Test01c; + + +global protocol Proto1(role A, role B) +{ + rec X + { + 1() from A to B; + choice at A + { + continue X; + } + } +} + diff --git a/scribble-test/src/test/resources/good/efsm/gcontinue/choiceunguarded/Test02a.scr b/scribble-test/src/test/resources/good/efsm/gcontinue/choiceunguarded/Test02a.scr new file mode 100644 index 000000000..fdd63ed7d --- /dev/null +++ b/scribble-test/src/test/resources/good/efsm/gcontinue/choiceunguarded/Test02a.scr @@ -0,0 +1,23 @@ +module good.efsm.gcontinue.choiceunguarded.Test02a; + + +global protocol Proto1(role A, role B) +{ + rec Y + { + 0() from A to B; + rec X + { + 1() from A to B; + choice at A // Testing multi-rec enacting states in intermediate continue-edge fixing + { + continue X; + } + or + { + continue Y; + } + } + } +} + diff --git a/scribble-test/src/test/resources/good/efsm/gcontinue/choiceunguarded/Test02b.scr b/scribble-test/src/test/resources/good/efsm/gcontinue/choiceunguarded/Test02b.scr new file mode 100644 index 000000000..22ca333c7 --- /dev/null +++ b/scribble-test/src/test/resources/good/efsm/gcontinue/choiceunguarded/Test02b.scr @@ -0,0 +1,23 @@ +module good.efsm.gcontinue.choiceunguarded.Test02b; + + +global protocol Proto1(role A, role B) +{ + rec Y + { + 0() from A to B; + rec X + { + 1() from A to B; + choice at A // Testing multi-rec enacting states in intermediate continue-edge fixing + { + continue Y; + } + or + { + continue X; + } + } + } +} + diff --git a/scribble-test/src/test/resources/good/efsm/gcontinue/choiceunguarded/Test02c.scr b/scribble-test/src/test/resources/good/efsm/gcontinue/choiceunguarded/Test02c.scr new file mode 100644 index 000000000..a8baec5ea --- /dev/null +++ b/scribble-test/src/test/resources/good/efsm/gcontinue/choiceunguarded/Test02c.scr @@ -0,0 +1,27 @@ +module good.efsm.gcontinue.choiceunguarded.Test02c; + + +global protocol Proto1(role A, role B) +{ + rec Y + { + 0() from A to B; + rec X + { + 1() from A to B; + choice at A // Testing multi-rec enacting states in intermediate continue-edge fixing + { + continue X; + } + or + { + continue X; + } + or + { + continue Y; + } + } + } +} + diff --git a/scribble-test/src/test/resources/good/efsm/gcontinue/choiceunguarded/Test02d.scr b/scribble-test/src/test/resources/good/efsm/gcontinue/choiceunguarded/Test02d.scr new file mode 100644 index 000000000..2bc56c1ac --- /dev/null +++ b/scribble-test/src/test/resources/good/efsm/gcontinue/choiceunguarded/Test02d.scr @@ -0,0 +1,27 @@ +module good.efsm.gcontinue.choiceunguarded.Test02d; + + +global protocol Proto1(role A, role B) +{ + rec Y + { + 0() from A to B; + rec X + { + 1() from A to B; + choice at A // Testing multi-rec enacting states in intermediate continue-edge fixing + { + continue X; + } + or + { + continue Y; + } + or + { + continue X; + } + } + } +} + diff --git a/scribble-test/src/test/resources/good/efsm/gcontinue/choiceunguarded/Test03.scr b/scribble-test/src/test/resources/good/efsm/gcontinue/choiceunguarded/Test03.scr new file mode 100644 index 000000000..393a754ee --- /dev/null +++ b/scribble-test/src/test/resources/good/efsm/gcontinue/choiceunguarded/Test03.scr @@ -0,0 +1,27 @@ +module good.efsm.gcontinue.choiceunguarded.Test03; + + +global protocol Proto1(role A, role B) +{ + rec Y + { + 0() from A to B; + rec X + { + 1() from A to B; + choice at A + { + continue X; // Check FSM building + } + or + { + 2() from A to B; + } + or + { + continue Y; + } + } + } +} + diff --git a/scribble-test/src/test/resources/good/efsm/gcontinue/choiceunguarded/Test04.scr b/scribble-test/src/test/resources/good/efsm/gcontinue/choiceunguarded/Test04.scr new file mode 100644 index 000000000..178dfa1cc --- /dev/null +++ b/scribble-test/src/test/resources/good/efsm/gcontinue/choiceunguarded/Test04.scr @@ -0,0 +1,23 @@ +module good.efsm.gcontinue.choiceunguarded.Test04; + + +global protocol Proto1(role A, role B) +{ + rec X + { + 0() from A to B; + choice at A + { + //1() from A to B; + continue X; + } + or + { + 2() from A to B; + //continue X; + } + } + 3() from A to B; +} + + diff --git a/scribble-test/src/test/resources/good/efsm/gcontinue/choiceunguarded/Test05a.scr b/scribble-test/src/test/resources/good/efsm/gcontinue/choiceunguarded/Test05a.scr new file mode 100644 index 000000000..509665050 --- /dev/null +++ b/scribble-test/src/test/resources/good/efsm/gcontinue/choiceunguarded/Test05a.scr @@ -0,0 +1,23 @@ +module good.efsm.gcontinue.choiceunguarded.Test05a; + + +global protocol Proto1(role A, role B, role C) +{ + rec X + { + 1() from A to B; + 2() from B to C; + choice at C + { + 3() from C to A; + continue X; // Projected as recursive non-det choice for B + } + or + { + 4() from C to A; + continue X; + } + } +} + + diff --git a/scribble-test/src/test/resources/good/efsm/gcontinue/choiceunguarded/Test05b.scr b/scribble-test/src/test/resources/good/efsm/gcontinue/choiceunguarded/Test05b.scr new file mode 100644 index 000000000..d1985ba0a --- /dev/null +++ b/scribble-test/src/test/resources/good/efsm/gcontinue/choiceunguarded/Test05b.scr @@ -0,0 +1,26 @@ +module good.efsm.gcontinue.choiceunguarded.Test05b; + + +global protocol Proto1(role A, role B, role C) +{ + rec X + { + rec Y + { + 1() from A to B; + 2() from B to C; + choice at C + { + 3() from C to A; + continue X; + } + or + { + 4() from C to A; + continue Y; + } + } + } +} + + diff --git a/scribble-test/src/test/resources/good/efsm/gcontinue/choiceunguarded/Test06.scr b/scribble-test/src/test/resources/good/efsm/gcontinue/choiceunguarded/Test06.scr new file mode 100644 index 000000000..9120b3691 --- /dev/null +++ b/scribble-test/src/test/resources/good/efsm/gcontinue/choiceunguarded/Test06.scr @@ -0,0 +1,21 @@ +module good.efsm.gcontinue.choiceungaurded.Test06; + + +global protocol Proto1(role A, role B) +{ + 1() from A to B; + rec X + { + 2() from A to B; + 3() from A to B; + choice at A + { + continue X; + } + or + { + 4() from A to B; + } + } +} + diff --git a/scribble-test/src/test/resources/good/efsm/gcontinue/choiceunguarded/Test07a.scr b/scribble-test/src/test/resources/good/efsm/gcontinue/choiceunguarded/Test07a.scr new file mode 100644 index 000000000..6a6edba32 --- /dev/null +++ b/scribble-test/src/test/resources/good/efsm/gcontinue/choiceunguarded/Test07a.scr @@ -0,0 +1,27 @@ +module good.efsm.gcontinue.choiceungaurded.Test07a; + + +global protocol Proto1(role A, role B) +{ + rec X + { + choice at A // Testing EFSM building rec with multiple "enactings" + { + 3() from A to B; + choice at A + { + //1() from A to B; + continue X; // (and choice-unguarded continue) + } + or + { + 6() from A to B; + } + } + or + { + 4() from A to B; + } + } +} + diff --git a/scribble-test/src/test/resources/good/efsm/gcontinue/choiceunguarded/Test07b.scr b/scribble-test/src/test/resources/good/efsm/gcontinue/choiceunguarded/Test07b.scr new file mode 100644 index 000000000..09f123b1e --- /dev/null +++ b/scribble-test/src/test/resources/good/efsm/gcontinue/choiceunguarded/Test07b.scr @@ -0,0 +1,35 @@ +module good.efsm.gcontinue.choiceungaurded.Test07b; + + +global protocol Proto1(role A, role B) +{ + rec X + { + choice at A // Testing EFSM building rec with multiple "enactings" + { + 3() from A to B; + choice at A + { + choice at A + { + 1() from A to B; + continue X; + } + or + { + //2() from A to B; + continue X; // (and choice-unguarded continue) + } + } + or + { + 6() from A to B; + } + } + or + { + 4() from A to B; + } + } +} + diff --git a/scribble-test/src/test/resources/good/efsm/gcontinue/choiceunguarded/Test07c.scr b/scribble-test/src/test/resources/good/efsm/gcontinue/choiceunguarded/Test07c.scr new file mode 100644 index 000000000..e07d2042c --- /dev/null +++ b/scribble-test/src/test/resources/good/efsm/gcontinue/choiceunguarded/Test07c.scr @@ -0,0 +1,35 @@ +module good.efsm.gcontinue.choiceungaurded.Test07c; + + +global protocol Proto1(role A, role B) +{ + rec X + { + choice at A // Testing EFSM building rec with multiple "enactings" + { + 3() from A to B; + choice at A + { + choice at A + { + 1() from A to B; + continue X; + } + or + { + 2() from A to B; + continue X; + } + } + or + { + 6() from A to B; + } + } + or + { + 4() from A to B; + } + } +} + diff --git a/scribble-test/src/test/resources/good/efsm/gcontinue/choiceunguarded/Test08.scr b/scribble-test/src/test/resources/good/efsm/gcontinue/choiceunguarded/Test08.scr new file mode 100644 index 000000000..dc22bfe00 --- /dev/null +++ b/scribble-test/src/test/resources/good/efsm/gcontinue/choiceunguarded/Test08.scr @@ -0,0 +1,26 @@ +module good.efsm.gcontinue.choiceungaurded.Test08; + + +global protocol Proto1(role A, role B) +{ + rec X + { + choice at A + { + 1() from A to B; + choice at A + { + continue X; + } + or + { + 3() from A to B; + } + } + or + { + 2() from A to B; // Testing EFSM building: multiple "enacting" + } + } +} + diff --git a/scribble-test/src/test/resources/good/efsm/gdo/Test01.scr b/scribble-test/src/test/resources/good/efsm/gdo/Test01.scr new file mode 100644 index 000000000..1ffe8e88c --- /dev/null +++ b/scribble-test/src/test/resources/good/efsm/gdo/Test01.scr @@ -0,0 +1,34 @@ +//$ bin/scribblec.sh -ip modules/core/src/test/scrib/ modules/cli/src/test/resources/good/efsm/gdo/Test01.scr -fsm Bar1 C + +module good.efsm.gdo.Test01; + + +// Test inlined protocol unfolding -- unguarded rec and continue under choice +global protocol Foo(role A, role B) +{ + 1() from A to B; + choice at A + { + do Bar1(A, B); + } + or + { + do Bar2(A, B); + } + or + { + 4() from A to B; + } +} + +global protocol Bar1(role C, role D) // <- As root, check choice inside Foo is unfolded correctly wrt. unguarded continue for Bar1 case +{ + 2() from C to D; + do Foo(C, D); +} + +global protocol Bar2(role C, role D) +{ + 5() from C to D; + do Bar2(C, D); +} diff --git a/scribble-test/src/test/resources/good/efsm/gdo/Test04.scr b/scribble-test/src/test/resources/good/efsm/gdo/Test04.scr new file mode 100644 index 000000000..5c1c00460 --- /dev/null +++ b/scribble-test/src/test/resources/good/efsm/gdo/Test04.scr @@ -0,0 +1,24 @@ +module good.efsm.gdo.Test04; + + +global protocol Foo(role A, role B) +{ + 1() from A to B; + choice at A + { + 2() from A to B; + do Bar(A, B); + } + or + { + 4() from A to B; + } +} + + +aux global protocol Bar(role A, role B) +{ + 3() from B to A; + do Foo(B, A); // Roles reversed +} + diff --git a/scribble-test/src/test/resources/good/efsm/gdo/Test06.scr b/scribble-test/src/test/resources/good/efsm/gdo/Test06.scr new file mode 100644 index 000000000..68db9cdb6 --- /dev/null +++ b/scribble-test/src/test/resources/good/efsm/gdo/Test06.scr @@ -0,0 +1,26 @@ +module good.efsm.gdo.Test06; + + +global protocol Foo(role A, role B) +{ + 2() from A to B; + choice at A + { + 1() from A to B; + } + or + { + do Foo2(A, B); // Direct result is non-minimal EFSM + } +} + +global protocol Foo2(role A, role B) +{ + do Foo3(A, B); +} + +global protocol Foo3(role A, role B) +{ + do Foo(A, B); +} + diff --git a/scribble-test/src/test/resources/good/efsm/gdo/Test07.scr b/scribble-test/src/test/resources/good/efsm/gdo/Test07.scr new file mode 100644 index 000000000..331f29fb1 --- /dev/null +++ b/scribble-test/src/test/resources/good/efsm/gdo/Test07.scr @@ -0,0 +1,36 @@ +module good.efsm.gdo.Test07; + + +// Similar to good.efsm.gdo.Test01 +global protocol Foo(role A, role B) +{ + 1() from A to B; + choice at A + { + do Bar1(A, B); + } + or + { + do Bar2(A, B); // Graph building done on unfolded-inlined (the static unfolding -- here: Bar2 rec is unguarded) // Cf. not the "dynamic" unfolding visiting + } + or + { + 5() from A to B; + } +} + +// The Bar1 inlined rec for root Foo gets "dropped" by unguarded unfolding because no continue for this rec +aux global protocol Bar1(role A, role B) +{ + 2() from A to B; + 3() from B to A; + do Foo(A, B); +} + +// For root Foo, Bar2 inlined as unguarded rec, then gets unfolded +aux global protocol Bar2(role A, role B) +{ + 4() from A to B; + do Bar2(A, B); +} + diff --git a/scribble-test/src/test/resources/good/efsm/gdo/Test08a.scr b/scribble-test/src/test/resources/good/efsm/gdo/Test08a.scr new file mode 100644 index 000000000..555096fc2 --- /dev/null +++ b/scribble-test/src/test/resources/good/efsm/gdo/Test08a.scr @@ -0,0 +1,24 @@ +module good.efsm.gdo.Test08a; + + +global protocol Foo(role A, role B) +{ + 1() from A to B; + choice at A + { + 2() from A to B; + do Bar(A, B); + } + or + { + 1() from A to B; + 2() from A to B; + } +} + + +aux global protocol Bar(role A, role B) +{ + //3() from A to B; + do Foo(A, B); +} diff --git a/scribble-test/src/test/resources/good/efsm/gdo/Test08b.scr b/scribble-test/src/test/resources/good/efsm/gdo/Test08b.scr new file mode 100644 index 000000000..b59bf424b --- /dev/null +++ b/scribble-test/src/test/resources/good/efsm/gdo/Test08b.scr @@ -0,0 +1,21 @@ +module good.efsm.gdo.Test08b; + + +global protocol Foo(role A, role B) +{ + 1() from A to B; + choice at A + { + do Bar(A, B); + } + or + { + 2() from A to B; + } +} + + +aux global protocol Bar(role A, role B) +{ + do Foo(A, B); +} diff --git a/scribble-test/src/test/resources/good/efsm/gdo/Test10.scr b/scribble-test/src/test/resources/good/efsm/gdo/Test10.scr new file mode 100644 index 000000000..7955f57e7 --- /dev/null +++ b/scribble-test/src/test/resources/good/efsm/gdo/Test10.scr @@ -0,0 +1,34 @@ +module good.efsm.gdo.Test10; + + +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + do Proto1Aux1(A, B, C); + } + or + { + do Proto1Aux2(A, B, C); + } +} + +aux global protocol Proto1Aux1(role A, role B, role C) +{ + choice at A + { + 3() from A to B; + 3() from A to C; + do Proto1Aux1(A, B, C); + } +} + +aux global protocol Proto1Aux2(role A, role B, role C) +{ + choice at A + { + 2() from A to B; + do Proto1Aux1(A, B, C); + } +} + diff --git a/scribble-test/src/test/resources/good/efsm/gdo/Test11.scr b/scribble-test/src/test/resources/good/efsm/gdo/Test11.scr new file mode 100644 index 000000000..482f910a5 --- /dev/null +++ b/scribble-test/src/test/resources/good/efsm/gdo/Test11.scr @@ -0,0 +1,38 @@ +module good.efsm.gdo.Test11; + + +global protocol Proto1(role A, role B, role C) +{ + 1() from A to B; + do Proto1Aux1(A, B, C); +} + +aux global protocol Proto1Aux1(role A, role B, role C) +{ + choice at A + { + 3() from A to B; + 3() from B to C; + do Proto1Aux2(A, B, C); + } + or + { + 4() from A to B; + 4() from B to C; + } +} + +aux global protocol Proto1Aux2(role A, role B, role C) +{ + choice at A + { + 5() from A to B; + do Proto1Aux1(A, B, C); // Testing graph building (C vs. A/B) + } + or + { + 6() from A to B; + 6() from B to C; + } +} + diff --git a/scribble-test/src/test/resources/good/efsm/gdo/Test12.scr b/scribble-test/src/test/resources/good/efsm/gdo/Test12.scr new file mode 100644 index 000000000..fdb90c64e --- /dev/null +++ b/scribble-test/src/test/resources/good/efsm/gdo/Test12.scr @@ -0,0 +1,21 @@ +module good.efsm.gdo.Test12; + + +global protocol Proto1(role A, role B) +{ + 1() from A to B; + do Proto1Aux1(A, B); +} + + +aux global protocol Proto1Aux1(role A, role B) +{ + choice at A + { + do Proto1(A, B); + } + or + { + 2() from A to B; + } +} diff --git a/scribble-test/src/test/resources/good/efsm/gdo/Test13a.scr b/scribble-test/src/test/resources/good/efsm/gdo/Test13a.scr new file mode 100644 index 000000000..625d60a84 --- /dev/null +++ b/scribble-test/src/test/resources/good/efsm/gdo/Test13a.scr @@ -0,0 +1,33 @@ +module good.efsm.gdo.Test13a; + + +global protocol Proto1(role A, role B) +{ + 1() from A to B; + choice at B + { + do Proto1Aux1(A, B); + } + or + { + do Proto1Aux2(A, B); + } + or + { + 4() from B to A; + } +} + +global protocol Proto1Aux1(role A, role B) +{ + 2() from B to A; + do Proto1(A, B); +} + +aux global protocol Proto1Aux2(role A, role B) +{ + 3() from B to A; + //do Proto1(A, B); + do Proto1Aux2(A, B); +} + diff --git a/scribble-test/src/test/resources/good/efsm/gdo/Test13b.scr b/scribble-test/src/test/resources/good/efsm/gdo/Test13b.scr new file mode 100644 index 000000000..5228ddf4b --- /dev/null +++ b/scribble-test/src/test/resources/good/efsm/gdo/Test13b.scr @@ -0,0 +1,32 @@ +module good.efsm.gdo.Test13b; + + +global protocol Proto1(role A, role B) +{ + 1() from A to B; + choice at B + { + do Proto1Aux1(A, B); + } + or + { + do Proto1Aux2(A, B); + } + or + { + 4() from B to A; + } +} + +global protocol Proto1Aux1(role A, role B) +{ + 2() from B to A; + do Proto1(A, B); +} + +aux global protocol Proto1Aux2(role A, role B) +{ + 3() from B to A; + do Proto1(A, B); +} + diff --git a/scribble-test/src/test/resources/good/efsm/grecursion/Test03.scr b/scribble-test/src/test/resources/good/efsm/grecursion/Test03.scr new file mode 100644 index 000000000..e2b4a2380 --- /dev/null +++ b/scribble-test/src/test/resources/good/efsm/grecursion/Test03.scr @@ -0,0 +1,22 @@ +module good.efsm.grecursion.Test03; + + +global protocol Foo(role A, role B) +{ + 0() from A to B; + rec X + { + choice at A + { + 1() from A to B; + 2() from B to A; + continue X; + } + or + { + 3() from A to B; + } + } + 4() from A to B; +} + diff --git a/scribble-test/src/test/resources/good/efsm/grecursion/Test05.scr b/scribble-test/src/test/resources/good/efsm/grecursion/Test05.scr new file mode 100644 index 000000000..be489440d --- /dev/null +++ b/scribble-test/src/test/resources/good/efsm/grecursion/Test05.scr @@ -0,0 +1,30 @@ +module good.efsm.grecursion.Test05; + + +global protocol Foo(role A, role B) +{ + 1() from A to B; + 2() from B to A; + choice at B + { + 3() from B to A; + } + or + { + 4() from B to A; + } + rec X + { + choice at A + { + 5() from A to B; + 6() from B to A; + continue X; + } + or + { + 6() from A to B; + } + } +} + diff --git a/scribble-test/src/test/resources/good/efsm/grecursion/Test06b.scr b/scribble-test/src/test/resources/good/efsm/grecursion/Test06b.scr new file mode 100644 index 000000000..f5584dfbc --- /dev/null +++ b/scribble-test/src/test/resources/good/efsm/grecursion/Test06b.scr @@ -0,0 +1,24 @@ +module good.efsm.grecursion.Test06b; + + +global protocol Foo(role A, role B) +{ + rec X + { + 1() from A to B; + choice at A + { + 4() from A to B; + rec Y + { + 3() from A to B; + continue X; + } + } + or + { + 2() from A to B; + } + } +} + diff --git a/scribble-test/src/test/resources/good/efsm/grecursion/Test07.scr b/scribble-test/src/test/resources/good/efsm/grecursion/Test07.scr new file mode 100644 index 000000000..70df9b0c6 --- /dev/null +++ b/scribble-test/src/test/resources/good/efsm/grecursion/Test07.scr @@ -0,0 +1,40 @@ +module good.efsm.grecursion.Test07; + + +global protocol Foo(role C, role S) +{ + rec XXX + { + choice at C + { + 1() from C to S; + } + or + { + LIST() from C to S; + choice at S + { + OK() from S to C; + rec summary_choice_list + { + choice at S + { + DOT() from S to C; + } + or + { + SUM() from S to C; + continue summary_choice_list; + } + } + } + or + { + ERR() from S to C; + } + continue XXX; // Testing graph building (updating predecessor state, when edges removed to be replaced by actual recursion edge) -- continue sequenced after a nested choice-continue: removing prev edge needs to remove pred state, and adding recursion edge should not add pred state + } + } +} + + diff --git a/scribble-test/src/test/resources/good/efsm/grecursion/Test08.scr b/scribble-test/src/test/resources/good/efsm/grecursion/Test08.scr new file mode 100644 index 000000000..ad96db7bf --- /dev/null +++ b/scribble-test/src/test/resources/good/efsm/grecursion/Test08.scr @@ -0,0 +1,23 @@ +module good.efsm.grecursion.Test08; + + +global protocol Foo(role A, role B) +{ + rec X + { + rec Y + { + choice at A + { + 1() from A to B; + } + or + { + 2() from A to B; + continue Y; // Testing graph building (updating predecessor state, when edges removed to be replaced by actual recursion edge) -- continue sequenced after a nested choice-continue: removing prev edge needs to remove pred state, and adding recursion edge should not add pred state + } + } + continue X; + } +} + diff --git a/scribble-test/src/test/resources/good/efsm/grecursion/Test09.scr b/scribble-test/src/test/resources/good/efsm/grecursion/Test09.scr new file mode 100644 index 000000000..901da6aaa --- /dev/null +++ b/scribble-test/src/test/resources/good/efsm/grecursion/Test09.scr @@ -0,0 +1,39 @@ +//$ bin/scribblec.sh scribble-test/src/test/resources/good/efsm/grecursion/Test09.scr -project Proto1 C + + +module good.efsm.grecursion.Test09; + + +global protocol Proto1(role A, role B, role C) +{ + 1() from A to B; + 2() from A to C; + rec X + { + choice at A + { + 3() from A to B; + } + choice at A + { + rec Y + { + choice at A + { + 3() from A to B; + continue X; + } + or + { + 4() from A to B; + continue Y; + } + or + { + 5() from A to B; + } + } + } + } +} + diff --git a/scribble-test/src/test/resources/good/efsm/grecursion/Test10.scr b/scribble-test/src/test/resources/good/efsm/grecursion/Test10.scr new file mode 100644 index 000000000..9cbcfbfa0 --- /dev/null +++ b/scribble-test/src/test/resources/good/efsm/grecursion/Test10.scr @@ -0,0 +1,16 @@ +module good.efsm.grecursion.Test10; + + +global protocol Proto1(role A, role B) +{ + choice at A + { + 1() from A to B; + rec X // Testing EFSM building, "enabling" stack push/pop for rec inside choice + { + 2() from B to A; + continue X; + } + } +} + diff --git a/scribble-test/src/test/resources/good/efsm/grecursion/Test11a.scr b/scribble-test/src/test/resources/good/efsm/grecursion/Test11a.scr new file mode 100644 index 000000000..f72d61dba --- /dev/null +++ b/scribble-test/src/test/resources/good/efsm/grecursion/Test11a.scr @@ -0,0 +1,26 @@ +module good.efsm.grecursion.Test11a; + + +global protocol Proto1(role A, role B, role C) +{ + rec X + { + choice at A + { + 1() from A to B; + choice at B + { + 2() from B to A; + 4() from B to C; // Testing EFSM building + continue X; + } + or + { + 3() from B to A; + 4() from B to C; + continue X; + } + } + } +} + diff --git a/scribble-test/src/test/resources/good/efsm/grecursion/Test12.scr b/scribble-test/src/test/resources/good/efsm/grecursion/Test12.scr new file mode 100644 index 000000000..55463b8b6 --- /dev/null +++ b/scribble-test/src/test/resources/good/efsm/grecursion/Test12.scr @@ -0,0 +1,12 @@ +module good.efsm.grecursion.Test12; + + +global protocol Proto1(role A, role B) +{ + rec X + { + 1() from A to B; + continue X; // Test graph building: EndpointGraph null exit (no term) + } +} + diff --git a/scribble-test/src/test/resources/good/efsm/grecursion/choiceunguarded/Test04.scr b/scribble-test/src/test/resources/good/efsm/grecursion/choiceunguarded/Test04.scr new file mode 100644 index 000000000..86671dc16 --- /dev/null +++ b/scribble-test/src/test/resources/good/efsm/grecursion/choiceunguarded/Test04.scr @@ -0,0 +1,25 @@ +module good.efsm.grecursion.choiceunguarded.Test04; + + +// Same as good.syntax.inlinedunfolding.grecursion.Test04; +global protocol Proto4(role A, role B) +{ + choice at A + { + rec X + { + choice at A + { + 1() from A to B; + continue X; + } + or + { + 2() from A to B; + continue X; + } + } + } +} + + diff --git a/scribble-test/src/test/resources/good/efsm/grecursion/choiceunguarded/Test06a.scr b/scribble-test/src/test/resources/good/efsm/grecursion/choiceunguarded/Test06a.scr new file mode 100644 index 000000000..fdcafb08c --- /dev/null +++ b/scribble-test/src/test/resources/good/efsm/grecursion/choiceunguarded/Test06a.scr @@ -0,0 +1,23 @@ +module good.efsm.grecursion.choiceunguarded.Test06a; + + +global protocol Foo(role A, role B) +{ + rec X + { + 1() from A to B; + choice at A + { + rec Y + { + 3() from A to B; + continue X; + } + } + or + { + 2() from A to B; + } + } +} + diff --git a/scribble-test/src/test/resources/good/efsm/grecursion/choiceunguarded/Test07.scr b/scribble-test/src/test/resources/good/efsm/grecursion/choiceunguarded/Test07.scr new file mode 100644 index 000000000..4f5773ff8 --- /dev/null +++ b/scribble-test/src/test/resources/good/efsm/grecursion/choiceunguarded/Test07.scr @@ -0,0 +1,24 @@ +module good.efsm.grecursion.choiceunguarded.Test07; + + +global protocol Proto1(role A, role B) +{ + rec X + { + 0() from A to B; + choice at A + { + rec X // Checking FSM generation -- unfolding of unguarded shadowed choice-rec + { + 1() from A to B; + continue X; + } + } + or + { + 2() from A to B; + } + } +} + + diff --git a/scribble-test/src/test/resources/good/liveness/Test01.scr b/scribble-test/src/test/resources/good/liveness/Test01.scr new file mode 100644 index 000000000..f590489b2 --- /dev/null +++ b/scribble-test/src/test/resources/good/liveness/Test01.scr @@ -0,0 +1,23 @@ +module good.liveness.Test01; + + +global protocol Proto1(role A, role B, role C, role D) +{ + choice at A + { + 1() from A to B; + 2() from B to A; + } + or + { + 2() from A to B; + 3() from B to A; + } + rec X // Testing terminal set building + { + 4() from C to D; + continue X; + } +} + + diff --git a/scribble-test/src/test/resources/good/liveness/Test02.scr b/scribble-test/src/test/resources/good/liveness/Test02.scr new file mode 100644 index 000000000..46e9addbc --- /dev/null +++ b/scribble-test/src/test/resources/good/liveness/Test02.scr @@ -0,0 +1,14 @@ +module good.liveness.Test02; + + +global protocol Proto1(role A, role B, role C, role D) +{ + rec X // Testing terminal set building + { + 1() from A to B; + 2() from B to A; + continue X; + } + 3() from C to D; +} + diff --git a/scribble-test/src/test/resources/good/liveness/roleprog/Test03.scr b/scribble-test/src/test/resources/good/liveness/roleprog/Test03.scr new file mode 100644 index 000000000..16e2418f8 --- /dev/null +++ b/scribble-test/src/test/resources/good/liveness/roleprog/Test03.scr @@ -0,0 +1,24 @@ +module good.liveness.roleprog.Test03; + + +// Same as good.safety.stuckmsg.threeparty.Test03 +global protocol Proto1(role A, role B, role C) +{ + rec X + { + 1() from A to B; + 1() from B to C; + choice at B + { + 2() from B to A; + continue X; // No C in this choice case, but fine + } + or + { + 3() from B to A; + 1() from B to C; + continue X; + } + } +} + diff --git a/scribble-test/src/test/resources/good/liveness/roleprog/Test10.scr b/scribble-test/src/test/resources/good/liveness/roleprog/Test10.scr new file mode 100644 index 000000000..d31f71b4d --- /dev/null +++ b/scribble-test/src/test/resources/good/liveness/roleprog/Test10.scr @@ -0,0 +1,35 @@ +module good.efsm.gdo.Test10; + + +// Duplicate of good.efsm.gdo.Test10 +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + do Proto1Aux1(A, B, C); + } + or + { + do Proto1Aux2(A, B, C); + } +} + +aux global protocol Proto1Aux1(role A, role B, role C) +{ + choice at A + { + 3() from A to B; + 3() from A to C; + do Proto1Aux1(A, B, C); + } +} + +aux global protocol Proto1Aux2(role A, role B, role C) +{ + choice at A + { + 2() from A to B; + do Proto1Aux1(A, B, C); + } +} + diff --git a/scribble-test/src/test/resources/good/misc/globals/gchoice/Choice01.scr b/scribble-test/src/test/resources/good/misc/globals/gchoice/Choice01.scr new file mode 100644 index 000000000..96c3fa9d3 --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/globals/gchoice/Choice01.scr @@ -0,0 +1,15 @@ +module good.misc.globals.gchoice.Choice01; + +// FIXME: not really about parsing, refactor +global protocol Choice1(role A, role B) +{ + choice at A + { + l1() from A to B; + } + or + { + //l1() from A to B; // Uncomment is bad + l2() from A to B; + } +} diff --git a/scribble-test/src/test/resources/good/misc/globals/gchoice/Choice02.scr b/scribble-test/src/test/resources/good/misc/globals/gchoice/Choice02.scr new file mode 100644 index 000000000..ff486bd8f --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/globals/gchoice/Choice02.scr @@ -0,0 +1,11 @@ +module good.misc.globals.gchoice.Choice02; + +global protocol Choice2(role A, role B) +{ + choice at A + { + //l1() from B to A; // Uncomment is bad + l1() from A to B; + } +} + diff --git a/scribble-test/src/test/resources/good/misc/globals/gchoice/Choice03.scr b/scribble-test/src/test/resources/good/misc/globals/gchoice/Choice03.scr new file mode 100644 index 000000000..2cdac2747 --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/globals/gchoice/Choice03.scr @@ -0,0 +1,15 @@ +module good.misc.globals.gchoice.Choice03; + +global protocol Choice3(role A, role B) +{ + l1() from A to B; + choice at B + { + l1() from B to A; + } + or + { + l2() from B to A; + } +} + diff --git a/scribble-test/src/test/resources/good/misc/globals/gchoice/Choice04.scr b/scribble-test/src/test/resources/good/misc/globals/gchoice/Choice04.scr new file mode 100644 index 000000000..c8881e533 --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/globals/gchoice/Choice04.scr @@ -0,0 +1,17 @@ +module good.misc.globals.gchoice.Choice04; + +global protocol Choice4(role A, role B) +{ + choice at B + { + l1() from B to A; + l2() from A to B; + } + or + { + l2() from B to A; + l1() from A to B; + l2() from A to B; // same label OK because B is the subject (TODO: should be generalised for all roles already enabled) + } +} + diff --git a/scribble-test/src/test/resources/good/misc/globals/gchoice/Choice05a.scr b/scribble-test/src/test/resources/good/misc/globals/gchoice/Choice05a.scr new file mode 100644 index 000000000..ff42e36a6 --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/globals/gchoice/Choice05a.scr @@ -0,0 +1,32 @@ +module good.misc.globals.gchoice.Choice05a; + + +global protocol Choice5a(role A, role B) +{ + choice at B + { + l1() from B to A; // Comment is bad + choice at A + { + l1() from A to B; + } + or + { + l2() from A to B; + } + } + or + { + choice at B + { + l2() from B to A; + } + or + { + l3() from B to A; + //l2() from B to A; // Uncomment OK unless l3() is commented + //l1() from B to A; // Uncomment OK unless l3() is commented + } + } +} + diff --git a/scribble-test/src/test/resources/good/misc/globals/gchoice/Choice05b.scr b/scribble-test/src/test/resources/good/misc/globals/gchoice/Choice05b.scr new file mode 100644 index 000000000..1a683ff67 --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/globals/gchoice/Choice05b.scr @@ -0,0 +1,32 @@ +module good.misc.globals.gchoice.Choice05b; + + +global protocol Choice5b(role A, role B) +{ + choice at B + { + l1() from B to A; // Comment is bad + choice at A + { + l1() from A to B; + } + or + { + l2() from A to B; + } + } + or + { + choice at B + { + l2() from B to A; + } + or + { + l3() from B to A; + //l2() from B to A; // Uncomment OK unless l3() is commented + //l1() from B to A; // Uncomment OK unless l3() is commented + } + } +} + diff --git a/scribble-test/src/test/resources/good/misc/globals/gchoice/Choice05c.scr b/scribble-test/src/test/resources/good/misc/globals/gchoice/Choice05c.scr new file mode 100644 index 000000000..5b11c1dc8 --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/globals/gchoice/Choice05c.scr @@ -0,0 +1,32 @@ +module good.misc.globals.gchoice.Choice05c; + + +global protocol Choice5c(role A, role B) +{ + choice at B + { + l1() from B to A; // Comment is bad + choice at A + { + l1() from A to B; + } + or + { + l2() from A to B; + } + } + or + { + choice at B + { + l2() from B to A; + } + or + { + l3() from B to A; + //l2() from B to A; // Uncomment OK unless l3() is commented + //l1() from B to A; // Uncomment OK unless l3() is commented + } + } +} + diff --git a/scribble-test/src/test/resources/good/misc/globals/gchoice/Choice06.scr b/scribble-test/src/test/resources/good/misc/globals/gchoice/Choice06.scr new file mode 100644 index 000000000..604751a2a --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/globals/gchoice/Choice06.scr @@ -0,0 +1,27 @@ +module good.misc.globals.gchoice.Choice06; + + +global protocol Choice6(role A, role B) +{ + choice at A + { + l1() from A to B; + } + or + { + () from A to B; + } + l1() from A to B; + () from A to B; + choice at A + { + l1() from A to B; // Comment is bad + () from A to B; + } + or + { + () from A to B; + } + 2() from A to B; +} + diff --git a/scribble-test/src/test/resources/good/misc/globals/gchoice/Choice08.scr b/scribble-test/src/test/resources/good/misc/globals/gchoice/Choice08.scr new file mode 100644 index 000000000..d0c2ae850 --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/globals/gchoice/Choice08.scr @@ -0,0 +1,19 @@ +module good.misc.globals.gchoice.Choice08; + + +global protocol Choice8(role A, role B, role C) +{ + choice at A + { + l1() from A to B; + l2() from B to C; + } + or + { + l2() from A to B; + l1() from B to C; // Comment is bad + l2() from B to C; + } + l2() from A to C; +} + diff --git a/scribble-test/src/test/resources/good/misc/globals/gdo/Do01a.scr b/scribble-test/src/test/resources/good/misc/globals/gdo/Do01a.scr new file mode 100644 index 000000000..9f34e7453 --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/globals/gdo/Do01a.scr @@ -0,0 +1,17 @@ +module good.misc.globals.gdo.Do01a; + + +global protocol Do1a(role A, role B) +{ + do Do1aux(A, B); + //do good.misc.globals.gdo.Do01a.Do1aux(A, B); // Uncomment is OK + //do X: Do1aux(A, B); // Uncomment is OK // TODO + //do Do1aux(A, B); // Uncomment is bad + //do Do1aux(A, A); // Uncomment is bad +} + +global protocol Do1aux(role C, role D) +{ + l1() from C to D; +} + diff --git a/scribble-test/src/test/resources/good/misc/globals/gdo/Do01b.scr b/scribble-test/src/test/resources/good/misc/globals/gdo/Do01b.scr new file mode 100644 index 000000000..c0a423d3c --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/globals/gdo/Do01b.scr @@ -0,0 +1,17 @@ +module good.misc.globals.gdo.Do01b; + + +global protocol Do1b(role A, role B) +{ + do Do1aux(A, B); + do good.misc.globals.gdo.Do01b.Do1aux(A, B); // Uncomment is OK + //do X: Do1aux(A, B); // Uncomment is OK // TODO + //do Do1aux(A, B); // Uncomment is bad + //do Do1aux(A, A); // Uncomment is bad +} + +global protocol Do1aux(role C, role D) +{ + l1() from C to D; +} + diff --git a/scribble-test/src/test/resources/good/misc/globals/gdo/Do02.scr b/scribble-test/src/test/resources/good/misc/globals/gdo/Do02.scr new file mode 100644 index 000000000..8bdf16d9f --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/globals/gdo/Do02.scr @@ -0,0 +1,13 @@ +module good.misc.globals.gdo.Do02; + + +global protocol Do2(role A, role B) +{ + do Do2a(B, A); +} + +global protocol Do2a(role A, role B) +{ + l1() from A to B; +} + diff --git a/scribble-test/src/test/resources/good/misc/globals/gdo/Do03.scr b/scribble-test/src/test/resources/good/misc/globals/gdo/Do03.scr new file mode 100644 index 000000000..a64f10472 --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/globals/gdo/Do03.scr @@ -0,0 +1,20 @@ +module good.misc.globals.gdo.Do03; + + +global protocol Do3(role A, role B) +{ + l1() from A to B; + do Do3a(A, B); +} + +global protocol Do3a(role C, role D) +{ + l2() from C to D; + do Do3b(C, D); +} + +global protocol Do3b(role E, role F) +{ + //l3() from A to B; // Uncomment is bad + l3() from E to F; +} diff --git a/scribble-test/src/test/resources/good/misc/globals/gdo/Do04a.scr b/scribble-test/src/test/resources/good/misc/globals/gdo/Do04a.scr new file mode 100644 index 000000000..812f03c7a --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/globals/gdo/Do04a.scr @@ -0,0 +1,27 @@ +module good.misc.globals.gdo.Do04a; + + +global protocol Do4a(role A, role B) +{ + choice at A + { + l1() from A to B; + } + or + { + do Do4_1(A, B); + //do X: Do4_1(A as C, B as D); // Uncomment is OK // TODO + } +} + +global protocol Do4_1(role C, role D) +{ + do Do4_2(C, D); +} + +global protocol Do4_2(role E, role F) +{ + //l1() from E to F; // Uncomment OK for the X-do only, not the unscoped one + l2() from E to F; +} + diff --git a/scribble-test/src/test/resources/good/misc/globals/gdo/Do05.scr b/scribble-test/src/test/resources/good/misc/globals/gdo/Do05.scr new file mode 100644 index 000000000..392efbb41 --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/globals/gdo/Do05.scr @@ -0,0 +1,20 @@ +module good.misc.globals.gdo.Do05; + + +global protocol Do5(role A, role B) +{ + choice at A + { + l1() from A to B; + } + or + { + do Do5a(A, B); // Comment is bad + l3() from B to A; + } +} + +global protocol Do5a(role C, role D) +{ + l2() from C to D; +} diff --git a/scribble-test/src/test/resources/good/misc/globals/gdo/Do06a.scr b/scribble-test/src/test/resources/good/misc/globals/gdo/Do06a.scr new file mode 100644 index 000000000..95623cad8 --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/globals/gdo/Do06a.scr @@ -0,0 +1,22 @@ +module good.misc.globals.gdo.Do06a; + + +type "java.lang.String" from "rt.jar" as String; + + +global protocol Do6a(role A, role B) +{ + do Do6_1(A, B); + //do Do6_1(A, B); // Uncomment is OK + //do Do6_1<(String)>(A, B); // Uncomment is OK + //do Do6_1<()>(A, B); // Uncomment is OK + //do Do6_1(A, B); // Uncomment is bad + //do Do6_1(A, B); // Uncomment is bad +} + +global protocol Do6_1(role C, role D) +//global protocol Do6_1(role C, role D) // Makes all above bad +{ + X from C to D; +} + diff --git a/scribble-test/src/test/resources/good/misc/globals/gdo/Do06b.scr b/scribble-test/src/test/resources/good/misc/globals/gdo/Do06b.scr new file mode 100644 index 000000000..44366f75a --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/globals/gdo/Do06b.scr @@ -0,0 +1,22 @@ +module good.misc.globals.gdo.Do06b; + + +type "java.lang.String" from "rt.jar" as String; + + +global protocol Do6b(role A, role B) +{ + do Do6_1(A, B); + do Do6_1(A, B); // Uncomment is OK + //do Do6_1<(String)>(A, B); // Uncomment is OK + //do Do6_1<()>(A, B); // Uncomment is OK + //do Do6_1(A, B); // Uncomment is bad + //do Do6_1(A, B); // Uncomment is bad +} + +global protocol Do6_1(role C, role D) +//global protocol Do6_1(role C, role D) // Makes all above bad +{ + X from C to D; +} + diff --git a/scribble-test/src/test/resources/good/misc/globals/gdo/Do06c.scr b/scribble-test/src/test/resources/good/misc/globals/gdo/Do06c.scr new file mode 100644 index 000000000..9ea22f584 --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/globals/gdo/Do06c.scr @@ -0,0 +1,22 @@ +module good.misc.globals.gdo.Do06c; + + +type "java.lang.String" from "rt.jar" as String; + + +global protocol Do6c(role A, role B) +{ + do Do6_1(A, B); + do Do6_1(A, B); // Uncomment is OK + do Do6_1<(String)>(A, B); // Uncomment is OK + //do Do6_1<()>(A, B); // Uncomment is OK + //do Do6_1(A, B); // Uncomment is bad + //do Do6_1(A, B); // Uncomment is bad +} + +global protocol Do6_1(role C, role D) +//global protocol Do6_1(role C, role D) // Makes all above bad +{ + X from C to D; +} + diff --git a/scribble-test/src/test/resources/good/misc/globals/gdo/Do06d.scr b/scribble-test/src/test/resources/good/misc/globals/gdo/Do06d.scr new file mode 100644 index 000000000..310e03133 --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/globals/gdo/Do06d.scr @@ -0,0 +1,22 @@ +module good.misc.globals.gdo.Do06d; + + +type "java.lang.String" from "rt.jar" as String; + + +global protocol Do6d(role A, role B) +{ + do Do6_1(A, B); + do Do6_1(A, B); // Uncomment is OK + do Do6_1<(String)>(A, B); // Uncomment is OK + do Do6_1<()>(A, B); // Uncomment is OK + //do Do6_1(A, B); // Uncomment is bad + //do Do6_1(A, B); // Uncomment is bad +} + +global protocol Do6_1(role C, role D) +//global protocol Do6_1(role C, role D) // Makes all above bad +{ + X from C to D; +} + diff --git a/scribble-test/src/test/resources/good/misc/globals/gdo/Do07.scr b/scribble-test/src/test/resources/good/misc/globals/gdo/Do07.scr new file mode 100644 index 000000000..13f7e070e --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/globals/gdo/Do07.scr @@ -0,0 +1,16 @@ +module good.misc.globals.gdo.Do07; + + +type "MyExternalType" from "MyExternalType.blah" as MyType; + + +global protocol Do7(role A, role B) +{ + do Do7a(A, B); +} + +global protocol Do7a(role C, role D) +{ + X from C to D; +} + diff --git a/scribble-test/src/test/resources/good/misc/globals/gdo/Do08.scr b/scribble-test/src/test/resources/good/misc/globals/gdo/Do08.scr new file mode 100644 index 000000000..4fd171cea --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/globals/gdo/Do08.scr @@ -0,0 +1,14 @@ +module good.misc.globals.gdo.Do08; + + +global protocol Do8(role A, role B) +{ + do Do8Aux(A, B); + do Do8Aux(B, A); +} + +global protocol Do8Aux(role C, role D) +{ + X from C to D; +} + diff --git a/scribble-test/src/test/resources/good/misc/globals/gdo/Do09.scr b/scribble-test/src/test/resources/good/misc/globals/gdo/Do09.scr new file mode 100644 index 000000000..a3c5ceedf --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/globals/gdo/Do09.scr @@ -0,0 +1,22 @@ +module good.misc.globals.gdo.Do09; + + +global protocol Do9(role A, role B) +{ + choice at A + { + do Do9Aux(A, B); + } + or + { + do Do9Aux(A, B); + //do Do9Aux(B, A); // Uncomment bad if the first line in this block is commented + //do Do9Aux(A, B); // Uncomment bad if the first line in this block is commented + } +} + +global protocol Do9Aux(role C, role D) +{ + X from C to D; +} + diff --git a/scribble-test/src/test/resources/good/misc/globals/gdo/Do10.scr b/scribble-test/src/test/resources/good/misc/globals/gdo/Do10.scr new file mode 100644 index 000000000..08c294ff3 --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/globals/gdo/Do10.scr @@ -0,0 +1,15 @@ +module good.misc.globals.gdo.Do10; + + +global protocol Do10(role A, role B) +{ + do Do10a(A, B); + //do Do10a(A, B); // Uncomment is bad +} + +global protocol Do10a(role C, role D) +{ + X from C to D; + //Y from C to D; // Uncomment is bad +} + diff --git a/scribble-test/src/test/resources/good/misc/globals/gdo/Do11.scr b/scribble-test/src/test/resources/good/misc/globals/gdo/Do11.scr new file mode 100644 index 000000000..bd789a828 --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/globals/gdo/Do11.scr @@ -0,0 +1,25 @@ +module good.misc.globals.gdo.Do11; + + +global protocol Do11(role A, role B) +{ + /*choice at A // Uncomment (with below) is bad + {*/ + do Do11Aux1(A, B); + /*} + or + { + l1() from A to B; + }*/ +} + +global protocol Do11Aux1(role C, role D) +{ + do Do11Aux2(C, D); +} + +global protocol Do11Aux2(role E, role F) +{ + X from E to F; +} + diff --git a/scribble-test/src/test/resources/good/misc/globals/gdo/Do12a.scr b/scribble-test/src/test/resources/good/misc/globals/gdo/Do12a.scr new file mode 100644 index 000000000..6a00ed933 --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/globals/gdo/Do12a.scr @@ -0,0 +1,23 @@ +module good.misc.globals.gdo.Do12a; + + +global protocol Do12a(role A, role B) +{ + choice at A + { + do Do12_1(A, B); + } + or + { + //do Do12_1(A, B); // Uncomment is bad + //do X: Do12_1(A, B); // Uncomment is OK + do Do12_1(A, B); + } +} + +global protocol Do12_1(role C, role D) +{ + X from C to D; +} + + diff --git a/scribble-test/src/test/resources/good/misc/globals/gdo/Do13b.scr b/scribble-test/src/test/resources/good/misc/globals/gdo/Do13b.scr new file mode 100644 index 000000000..9316afbb7 --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/globals/gdo/Do13b.scr @@ -0,0 +1,9 @@ +module good.misc.globals.gdo.Do13b; + + +global protocol Do13b(role A, role B) +{ + l1() from A to B; // Uncomment is OK + do Do13b(A, B); + //l1() from A to B; // Uncomment is bad +} diff --git a/scribble-test/src/test/resources/good/misc/globals/gdo/Do14.scr b/scribble-test/src/test/resources/good/misc/globals/gdo/Do14.scr new file mode 100644 index 000000000..bbf7a9c42 --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/globals/gdo/Do14.scr @@ -0,0 +1,22 @@ +module good.misc.globals.gdo.Do14; + + +global protocol Do14(role A, role B) +{ + choice at A + { + l1() from A to B; + do Do14a(A, B); + } + or + { + l2() from A to B; + } + //l1() from A to B; // Uncomment is bad +} + +global protocol Do14a(role C, role D) +{ + do Do14(D, C); +} + diff --git a/scribble-test/src/test/resources/good/misc/globals/gdo/Do15.scr b/scribble-test/src/test/resources/good/misc/globals/gdo/Do15.scr new file mode 100644 index 000000000..12b3ea42e --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/globals/gdo/Do15.scr @@ -0,0 +1,17 @@ +module good.misc.globals.gdo.Do15; + + +global protocol Do15(role A, role B) +{ + choice at A + { + l1() from A to B; + do Do15(A, B); + } + or + { + l2() from A to B; + } + //l3() from A to B; // Uncomment is bad +} + diff --git a/scribble-test/src/test/resources/good/misc/globals/gdo/Do17.scr b/scribble-test/src/test/resources/good/misc/globals/gdo/Do17.scr new file mode 100644 index 000000000..bbfec2492 --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/globals/gdo/Do17.scr @@ -0,0 +1,21 @@ +module good.misc.globals.gdo.Do17; + + +global protocol Do17(role A, role B) +{ + do Do17a(A, B); + //do Do17a(A, B); // Uncomment is bad +} + +global protocol Do17a(role C, role D) +{ + choice at C + { + X from C to D; + } + or + { + Y from C to D; + } +} + diff --git a/scribble-test/src/test/resources/good/misc/globals/gdo/Do19.scr b/scribble-test/src/test/resources/good/misc/globals/gdo/Do19.scr new file mode 100644 index 000000000..8885481a4 --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/globals/gdo/Do19.scr @@ -0,0 +1,18 @@ +module good.misc.globals.gdo.Do19; + + +global protocol Do19(role A, role B) +{ + do Do19a(A, B); + //l1() from A to B; // Uncomment is bad +} + +global protocol Do19a(role C, role D) +{ + rec X + { + l1() from C to D; + continue X; + } +} + diff --git a/scribble-test/src/test/resources/good/misc/globals/gdo/Do21.scr b/scribble-test/src/test/resources/good/misc/globals/gdo/Do21.scr new file mode 100644 index 000000000..37e9b42bb --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/globals/gdo/Do21.scr @@ -0,0 +1,18 @@ +module good.misc.globals.gdo.Do21; + + +type "java.lang.String" from "rt.jar" as String; + + +global protocol Do6(role A, role B) +{ + do Do6a(A, B); + //do Do6a(A, B); // Uncomment is bad +} + +global protocol Do6a(role C, role D) +//global protocol Do6a(role C, role D) +{ + (X) from C to D; +} + diff --git a/scribble-test/src/test/resources/good/misc/globals/gdo/Do23b.scr b/scribble-test/src/test/resources/good/misc/globals/gdo/Do23b.scr new file mode 100644 index 000000000..edbf5f933 --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/globals/gdo/Do23b.scr @@ -0,0 +1,23 @@ +module good.misc.globals.gdo.Do23b; + + +type "java.lang.String" from "rt.jar" as String; + + +// Overlaps with Do25 +global protocol Do23b(role A, role B) +{ + do Do23aux(A, B); +} + +global protocol Do23aux(role C, role D) +{ + do Do23a2(C, D); +} + +global protocol Do23a2(role E, role F) +//global protocol Do23a2(role E, role F) +{ + X from E to F; // Uncomment OK +} + diff --git a/scribble-test/src/test/resources/good/misc/globals/gdo/Do25.scr b/scribble-test/src/test/resources/good/misc/globals/gdo/Do25.scr new file mode 100644 index 000000000..b66991357 --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/globals/gdo/Do25.scr @@ -0,0 +1,22 @@ +module good.misc.globals.gdo.Do25; + + +type "java.lang.String" from "rt.jar" as String; + + +global protocol Do25(role A, role B) +{ + do Do25a(A, B); + //do Do25a(A, B); // Uncomment is bad + //do Do25a(A, B); // Uncomment is bad + //do Do25a(A, B); // Uncomment is bad + //do Do25a(A, B); // Uncomment is bad + //do Do25a<(), String, ()>(A, B); // Uncomment is bad +} + +global protocol Do25a(role C, role D) +{ + X from C to D; + (Y) from D to C; +} + diff --git a/scribble-test/src/test/resources/good/misc/globals/gdo/Do26.scr b/scribble-test/src/test/resources/good/misc/globals/gdo/Do26.scr new file mode 100644 index 000000000..7cf357db7 --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/globals/gdo/Do26.scr @@ -0,0 +1,16 @@ +module good.misc.globals.gdo.Do26; + + +global protocol Do26(role A, role B) +{ + m() from A to B; + choice at A + { + m1() from A to B; // Comment bad (similar to an unguarded continue in a choice in a rec) + do Do26(A, B); + } + or + { + m2() from A to B; + } +} diff --git a/scribble-test/src/test/resources/good/misc/globals/gdo/Do27.scr b/scribble-test/src/test/resources/good/misc/globals/gdo/Do27.scr new file mode 100644 index 000000000..0c249b935 --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/globals/gdo/Do27.scr @@ -0,0 +1,26 @@ +module good.misc.globals.gdo.Do27; + + +global protocol Do27(role A, role B) +{ + choice at A + { + m1() from A to B; + } + or + { + m2() from A to B; + //do Do27(A, B); // Uncomment bad + do Do27a(A, B); + } + m3() from A to B; +} + +global protocol Do27a(role C, role D) +{ + rec X + { + m4() from C to D; + //continue X; // Uncomment bad + } +} diff --git a/scribble-test/src/test/resources/good/misc/globals/gprotocoldecl/GProtocolDecl02.scr b/scribble-test/src/test/resources/good/misc/globals/gprotocoldecl/GProtocolDecl02.scr new file mode 100644 index 000000000..03d2b29fd --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/globals/gprotocoldecl/GProtocolDecl02.scr @@ -0,0 +1,13 @@ +module good.misc.globals.protocoldecl.GProtocolDecl02; + + +global protocol GProtocolDecl2(role A, role B, role C) +{ + 1() from A to B; + do GProtocolDecl2a(A, C); +} + +global protocol GProtocolDecl2a(role D, role E) +{ + 2() from D to E; +} \ No newline at end of file diff --git a/scribble-test/src/test/resources/good/misc/globals/gprotocoldecl/GProtocolDecl03.scr b/scribble-test/src/test/resources/good/misc/globals/gprotocoldecl/GProtocolDecl03.scr new file mode 100644 index 000000000..0b6eb7c4d --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/globals/gprotocoldecl/GProtocolDecl03.scr @@ -0,0 +1,18 @@ +module good.misc.globals.protocoldecl.GProtocolDecl03; + + +global protocol GProtocolDecl3(role A, role B, role C) +{ + 1() from A to B; + do GProtocolDecl3a(A, C); +} + +global protocol GProtocolDecl3a(role D, role E) +{ + do GProtocolDecl3b(D, E); +} + +global protocol GProtocolDecl3b(role D, role E) +{ + 2() from D to E; +} diff --git a/scribble-test/src/test/resources/good/misc/globals/gprotocoldecl/GProtocolDecl04.scr b/scribble-test/src/test/resources/good/misc/globals/gprotocoldecl/GProtocolDecl04.scr new file mode 100644 index 000000000..fef370911 --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/globals/gprotocoldecl/GProtocolDecl04.scr @@ -0,0 +1,13 @@ +module good.misc.globals.protocoldecl.GProtocolDecl04; + + +global protocol GProtocolDecl4a(role D, role E) +{ + do GProtocolDecl4b(D, E); +} + +global protocol GProtocolDecl4b(role D, role E) +{ + 2() from D to E; + do GProtocolDecl4a(D, E); +} diff --git a/scribble-test/src/test/resources/good/misc/globals/grecursion/Recursion01.scr b/scribble-test/src/test/resources/good/misc/globals/grecursion/Recursion01.scr new file mode 100644 index 000000000..9d5962366 --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/globals/grecursion/Recursion01.scr @@ -0,0 +1,16 @@ +module good.misc.globals.grecursion.Recursion01; + + +global protocol Recursion1(role A, role B) +{ + //rec A { } // Currently OK. Disallow? + + rec X + { + l1() from A to B; + continue X; + //continue Y; // Uncomment bad, even if above line is commented + //l2() from A to B; // Uncomment bad + } +} + diff --git a/scribble-test/src/test/resources/good/misc/globals/grecursion/Recursion02.scr b/scribble-test/src/test/resources/good/misc/globals/grecursion/Recursion02.scr new file mode 100644 index 000000000..040bcf51d --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/globals/grecursion/Recursion02.scr @@ -0,0 +1,11 @@ +module good.misc.globals.grecursion.Recursion02; + + +global protocol Recursion2(role A, role B) +{ + rec X + { + l1() from A to B; // Comment is OK + } +} + diff --git a/scribble-test/src/test/resources/good/misc/globals/grecursion/Recursion03.scr b/scribble-test/src/test/resources/good/misc/globals/grecursion/Recursion03.scr new file mode 100644 index 000000000..80015e702 --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/globals/grecursion/Recursion03.scr @@ -0,0 +1,19 @@ +module good.misc.globals.grecursion.Recursion03; + + +global protocol Recursion3(role A, role B) +{ + rec X + { + l1() from A to B; + rec Y + { + l2() from B to A; + continue Y; + //continue X; // Uncomment OK if above line is commented + } + //l3() from B to A; // Uncommemt bad + } + //l4() from B to A; // Uncomment bad +} + diff --git a/scribble-test/src/test/resources/good/misc/globals/grecursion/Recursion04.scr b/scribble-test/src/test/resources/good/misc/globals/grecursion/Recursion04.scr new file mode 100644 index 000000000..bc3064f90 --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/globals/grecursion/Recursion04.scr @@ -0,0 +1,18 @@ +module good.misc.globals.grecursion.Recursion04; + + +global protocol Recursion4(role A, role B) +{ + rec X + { + l1() from A to B; + rec Y + //rec X // Uncomment bad, even if above line is commented + { + l2() from B to A; + continue X; + //continue Y; // Uncomment OK if the above line is commented + } + } +} + diff --git a/scribble-test/src/test/resources/good/misc/globals/grecursion/Recursion05.scr b/scribble-test/src/test/resources/good/misc/globals/grecursion/Recursion05.scr new file mode 100644 index 000000000..bd56f75ca --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/globals/grecursion/Recursion05.scr @@ -0,0 +1,17 @@ +module good.misc.globals.grecursion.Recursion05; + + +global protocol Recursion5(role A, role B) +{ + rec X + { + l1() from A to B; + //continue X; // Uncomment makes the below rec bad + //continue Y; // Uncomment bad + } + rec Y + { + l2() from B to A; + continue Y; // A bad "continue X" here tested in Recursion11 + } +} diff --git a/scribble-test/src/test/resources/good/misc/globals/grecursion/Recursion06.scr b/scribble-test/src/test/resources/good/misc/globals/grecursion/Recursion06.scr new file mode 100644 index 000000000..1783d13ac --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/globals/grecursion/Recursion06.scr @@ -0,0 +1,22 @@ +module good.misc.globals.grecursion.Recursion06; + + +global protocol Recursion6(role A, role B) +{ + rec X + { + choice at A + { + l1() from A to B; + continue X; + //l1() from A to B; // Uncomment bad + } + or + { + l2() from A to B; + } + //l3() from A to B; // Uncomment bad. "General recursion" issue ("unfold stacking"). Fix is to move inside the second choice block + } + l4() from A to B; +} + diff --git a/scribble-test/src/test/resources/good/misc/globals/grecursion/Recursion07.scr b/scribble-test/src/test/resources/good/misc/globals/grecursion/Recursion07.scr new file mode 100644 index 000000000..3778efcb2 --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/globals/grecursion/Recursion07.scr @@ -0,0 +1,21 @@ +module good.misc.globals.grecursion.Recursion07; + + +global protocol Recursion7(role A, role B) +{ + rec X + { + choice at A + { + l1() from A to B; + } + or + { + l2() from A to B; + } + continue X; + //l3() from A to B; // Uncomment bad + } + //l3() from A to B; // Uncomment bad +} + diff --git a/scribble-test/src/test/resources/good/misc/globals/grecursion/Recursion11.scr b/scribble-test/src/test/resources/good/misc/globals/grecursion/Recursion11.scr new file mode 100644 index 000000000..5593b0255 --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/globals/grecursion/Recursion11.scr @@ -0,0 +1,17 @@ +module parsing.globals.grecursion.Recursion11; + + +global protocol Recursion11(role A, role B) +{ + rec X + { + l1() from A to B; + } + rec Y + { + l2() from B to A; + continue Y; + //continue X; // Uncomment bad, even if above line is commented + } +} + diff --git a/scribble-test/src/test/resources/good/misc/globals/grecursion/Recursion13.scr b/scribble-test/src/test/resources/good/misc/globals/grecursion/Recursion13.scr new file mode 100644 index 000000000..644821811 --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/globals/grecursion/Recursion13.scr @@ -0,0 +1,18 @@ +module parsing.globals.grecursion.Recursion13; + + +global protocol Recursion13(role A, role B) +{ + rec X + { + l1() from A to B; + do parsing.globals.grecursion.Recursion13.Recursion13a(A, B); + continue X; + } +} + +global protocol Recursion13a(role A, role B) +{ + l1() from A to B; +} + diff --git a/scribble-test/src/test/resources/good/misc/globals/grecursion/Recursion15.scr b/scribble-test/src/test/resources/good/misc/globals/grecursion/Recursion15.scr new file mode 100644 index 000000000..69988a1f1 --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/globals/grecursion/Recursion15.scr @@ -0,0 +1,19 @@ +module parsing.globals.grecursion.Recursion15; + + +global protocol Recursion15(role A, role B) +{ + rec X + { + m() from A to B; + choice at A + { + m1() from A to B; // Comment bad + continue X; + } + or + { + m2() from A to B; + } + } +} diff --git a/scribble-test/src/test/resources/good/misc/globals/grecursion/Recursion16.scr b/scribble-test/src/test/resources/good/misc/globals/grecursion/Recursion16.scr new file mode 100644 index 000000000..26db78daf --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/globals/grecursion/Recursion16.scr @@ -0,0 +1,19 @@ +module parsing.globals.grecursion.Recursion16; + + +global protocol Recursion16(role A, role B) +{ + choice at A + { + m1() from A to B; + } + or + { + rec X + { + m2() from A to B; + //continue X; // Uncomment (currently) bad + } + } + m3() from A to B; +} diff --git a/scribble-test/src/test/resources/good/misc/imports/Import01.scr b/scribble-test/src/test/resources/good/misc/imports/Import01.scr new file mode 100644 index 000000000..6a483c7d4 --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/imports/Import01.scr @@ -0,0 +1,11 @@ +//Raymond@HZHL2 ~/code/python/scribble-tools +//$ PYTHONPATH='lib/:bin/' python src/scribble/Main.py -ip test/ test/base/impourt/Import1.scr + +//$ bin/scribblec.sh -ip scribble-test/src/test/resources scribble-test/src/test/resources/good/misc/imports/Import01.scr + +module good.misc.imports.Import01; + + +import good.misc.imports.pack1.Pack01; +//import good.misc.imports.pack1.Pack1; + diff --git a/scribble-test/src/test/resources/good/misc/imports/Import02.scr b/scribble-test/src/test/resources/good/misc/imports/Import02.scr new file mode 100644 index 000000000..2cb33ed2e --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/imports/Import02.scr @@ -0,0 +1,8 @@ +//Raymond@HZHL2 ~/code/python/scribble-tools +//$ PYTHONPATH='lib/:bin/' python src/scribble/Main.py -ip test/ test/base/impourt/Import2.scr + +module good.misc.imports.Import02; + + +import good.misc.imports.pack1.Pack02; + diff --git a/scribble-test/src/test/resources/good/misc/imports/Import03.scr b/scribble-test/src/test/resources/good/misc/imports/Import03.scr new file mode 100644 index 000000000..6741bb146 --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/imports/Import03.scr @@ -0,0 +1,8 @@ +//Raymond@HZHL2 ~/code/python/scribble-tools +//$ PYTHONPATH='lib/:bin/' python src/scribble/Main.py -ip test/ test/base/impourt/Import3.scr + +module good.misc.imports.Import03; + +import good.misc.imports.pack1.Pack03; +import good.misc.imports.pack1.Pack01; + diff --git a/scribble-test/src/test/resources/good/misc/imports/Import04.scr b/scribble-test/src/test/resources/good/misc/imports/Import04.scr new file mode 100644 index 000000000..62bbb529c --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/imports/Import04.scr @@ -0,0 +1,7 @@ +//Raymond@HZHL2 ~/code/python/scribble-tools +//$ PYTHONPATH='lib/:bin/' python src/scribble/Main.py -ip test/ test/base/impourt/Import4.scr + +module good.misc.imports.Import04; + +import good.misc.imports.pack1.Pack04a; +import good.misc.imports.pack1.Pack04b; diff --git a/scribble-test/src/test/resources/good/misc/imports/Import05.scr b/scribble-test/src/test/resources/good/misc/imports/Import05.scr new file mode 100644 index 000000000..21c078990 --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/imports/Import05.scr @@ -0,0 +1,8 @@ +//Raymond@HZHL2 ~/code/python/scribble-tools +//$ PYTHONPATH='lib/:bin/' python src/scribble/Main.py -ip test/ test/base/impourt/Import5.scr + +module good.misc.imports.Import05; + +import good.misc.imports.pack1.Pack05; +import good.misc.imports.pack2.Pack05; + diff --git a/scribble-test/src/test/resources/good/misc/imports/Import07.scr b/scribble-test/src/test/resources/good/misc/imports/Import07.scr new file mode 100644 index 000000000..fafbcfd3e --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/imports/Import07.scr @@ -0,0 +1,11 @@ +//Raymond@HZHL2 ~/code/python/scribble-tools +//$ PYTHONPATH='lib/:bin/' python src/scribble/Main.py -ip test/ test/base/impourt/Import7.scr + +module good.misc.imports.Import07; + +import good.misc.imports.pack1.Pack07; + +import good.misc.imports.Import01; + +//import good.misc.imports.pack1.Pack1; // Uncomment is OK + diff --git a/scribble-test/src/test/resources/good/misc/imports/Import08.scr b/scribble-test/src/test/resources/good/misc/imports/Import08.scr new file mode 100644 index 000000000..18c60d80d --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/imports/Import08.scr @@ -0,0 +1,15 @@ +//Raymond@HZHL2 ~/code/python/scribble-tools +//$ PYTHONPATH='lib/:bin/' python src/scribble/Main.py -ip test/ test/base/impourt/Import8.scr + +//$ bin/scribblec.sh -ip scribble-test/src/test/resources scribble-test/src/test/resources/good/misc/imports/Import08.scr + +module good.misc.imports.Import08; + +import good.misc.imports.pack1.Pack08; + + +global protocol Import8(role A, role B) +{ + do good.misc.imports.pack1.Pack08.Pack8(A, B); +} + diff --git a/scribble-test/src/test/resources/good/misc/imports/Import09.scr b/scribble-test/src/test/resources/good/misc/imports/Import09.scr new file mode 100644 index 000000000..7e63332fc --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/imports/Import09.scr @@ -0,0 +1,21 @@ +//Raymond@HZHL2 ~/code/python/scribble-tools +//$ PYTHONPATH='lib/:bin/' python src/scribble/Main.py -ip test/ test/base/impourt/Import9.scr + +module good.misc.imports.Import09; + +import good.misc.imports.pack1.Pack09; + + +global protocol Import9(role A, role B) +{ + choice at A + { + do good.misc.imports.pack1.Pack09.Pack9(A, B); + } + or + { + l2() from A to B; + //l1() from A to B; + } +} + diff --git a/scribble-test/src/test/resources/good/misc/imports/Import10.scr b/scribble-test/src/test/resources/good/misc/imports/Import10.scr new file mode 100644 index 000000000..e629de4dc --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/imports/Import10.scr @@ -0,0 +1,32 @@ +//Raymond@HZHL2 ~/code/python/scribble-tools +//$ PYTHONPATH='lib/:bin/' python src/scribble/Main.py -ip test/ test/base/impourt/Import10.scr + +module good.misc.imports.Import10; + +import good.misc.imports.pack1.Pack10; +import good.misc.imports.pack2.Pack10; + + +global protocol Import10(role A, role B) +{ + choice at A + { + do good.misc.imports.pack1.Pack10.Pack10(A, B); + } + or + { + do good.misc.imports.pack2.Pack10.Pack10(A, B); + } + or + { + do Pack10(A, B); + } +} + +global protocol Pack10(role C, role D) +{ + l3() from C to D; + //l1() from C to D; // Bad if above line is commented + //l2() from C to D; +} + diff --git a/scribble-test/src/test/resources/good/misc/imports/Import11.scr b/scribble-test/src/test/resources/good/misc/imports/Import11.scr new file mode 100644 index 000000000..baf60d2ef --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/imports/Import11.scr @@ -0,0 +1,26 @@ +//Raymond@HZHL2 ~/code/python/scribble-tools +//$ PYTHONPATH='lib/:bin/' python src/scribble/Main.py -ip test/ test/base/impourt/Import11.scr + +module good.misc.imports.Import11; + +import good.misc.imports.pack1.Pack11; + + +global protocol Import11(role A, role B) +{ + choice at A + { + do good.misc.imports.pack1.Pack11.Pack11(A, B); + } + or + { + l2() from A to B; + } +} + +global protocol Import11Aux(role E, role F) +{ + l1() from E to F; + //l2() from E to F; +} + diff --git a/scribble-test/src/test/resources/good/misc/imports/Import12.scr b/scribble-test/src/test/resources/good/misc/imports/Import12.scr new file mode 100644 index 000000000..2b6c9193a --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/imports/Import12.scr @@ -0,0 +1,15 @@ +//Raymond@HZHL2 ~/code/python/scribble-tools +//$ PYTHONPATH='lib/:bin/' python src/scribble/Main.py -ip test/ test/base/impourt/Import12.scr + +module good.misc.imports.Import12; + +import good.misc.imports.pack1.Pack12; + + +global protocol Import12(role A, role B) +{ + do good.misc.imports.pack1.Pack12.Pack12(A, B); + //do good.misc.imports.pack1.Pack12.Pack12(A, B); // Uncomment is OK + //do good.misc.imports.pack1.Pack12.Pack12(A, B); +} + diff --git a/scribble-test/src/test/resources/good/misc/imports/Import13.scr b/scribble-test/src/test/resources/good/misc/imports/Import13.scr new file mode 100644 index 000000000..7042dec95 --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/imports/Import13.scr @@ -0,0 +1,26 @@ +//Raymond@HZHL2 ~/code/python/scribble-tools +//$ PYTHONPATH='lib/:bin/' python src/scribble/Main.py -ip test/ test/base/impourt/Import13.scr + +module good.misc.imports.Import13; + +import good.misc.imports.pack1.Pack13; + + +global protocol Import13(role A, role B) +{ + choice at A + { + do good.misc.imports.pack1.Pack13.Pack13(A, B); + } + or + { + do Import13Aux(A, B); + //do Import13Aux(A, B); + } +} + +global protocol Import13Aux(role A, role B) +{ + X from A to B; +} + diff --git a/scribble-test/src/test/resources/good/misc/imports/Import14.scr b/scribble-test/src/test/resources/good/misc/imports/Import14.scr new file mode 100644 index 000000000..713e6c460 --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/imports/Import14.scr @@ -0,0 +1,26 @@ +//Raymond@HZHL2 ~/code/python/scribble-tools +//$ PYTHONPATH='lib/:bin/' python src/scribble/Main.py -ip test/ test/base/impourt/Import14.scr + +module good.misc.imports.Import14; + +import good.misc.imports.pack1.Pack14; + + +global protocol Import14(role A, role B) +{ + choice at A + { + do good.misc.imports.pack1.Pack14.Pack14(A, B); + } + or + { + do Import14Aux(A, B); + //do Import14Aux(A, B); + } +} + +global protocol Import14Aux(role A, role B) +{ + X from A to B; +} + diff --git a/scribble-test/src/test/resources/good/misc/imports/Import15.scr b/scribble-test/src/test/resources/good/misc/imports/Import15.scr new file mode 100644 index 000000000..12f5e316e --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/imports/Import15.scr @@ -0,0 +1,7 @@ +//Raymond@HZHL2 ~/code/python/scribble-tools +//$ PYTHONPATH='lib/:bin/' python src/scribble/Main.py -ip test/ test/base/impourt/Import15.scr + +module good.misc.imports.Import15; + +//import Import15; // FIXME: check if simplename should be allowed here (currently implementation doesn't allow) + diff --git a/scribble-test/src/test/resources/good/misc/imports/Import16.scr b/scribble-test/src/test/resources/good/misc/imports/Import16.scr new file mode 100644 index 000000000..3e24c75bc --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/imports/Import16.scr @@ -0,0 +1,14 @@ +//Raymond@HZHL2 ~/code/python/scribble-tools +//$ PYTHONPATH='lib/:bin/' python src/scribble/Main.py -ip test/ test/base/impourt/Import16.scr + +module good.misc.imports.Import16; + +import good.misc.imports.pack1.Pack16 as Pack16; +import good.misc.imports.pack1.Pack16 as Foo; + + +global protocol Import16(role A, role B) +{ + do Pack16.Pack16(A, B); + do Foo.Pack16(A, B); +} diff --git a/scribble-test/src/test/resources/good/misc/imports/pack1/IGNORE b/scribble-test/src/test/resources/good/misc/imports/pack1/IGNORE new file mode 100644 index 000000000..e69de29bb diff --git a/scribble-test/src/test/resources/good/misc/imports/pack1/Pack01.scr b/scribble-test/src/test/resources/good/misc/imports/pack1/Pack01.scr new file mode 100644 index 000000000..b58921b19 --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/imports/pack1/Pack01.scr @@ -0,0 +1,14 @@ +//Raymond@HZHL2 ~/code/python/scribble-tools +//$ PYTHONPATH='lib/:bin/' python src/scribble/Main.py test/base/impourt/pack1/Pack1.scr + +module good.misc.imports.pack1.Pack01; +//package good.misc.imports.pack1.X; +//package good.misc.imports.X.Pack1; + + +global protocol Pack1(role A, role B) +{ + l1() from A to B; + //l1() from A to C; +} + diff --git a/scribble-test/src/test/resources/good/misc/imports/pack1/Pack02.scr b/scribble-test/src/test/resources/good/misc/imports/pack1/Pack02.scr new file mode 100644 index 000000000..ea7bfe99e --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/imports/pack1/Pack02.scr @@ -0,0 +1,17 @@ +//Raymond@HZHL2 ~/code/python/scribble-tools +//$ PYTHONPATH='lib/:bin/' python src/scribble/Main.py test/base/impourt/pack1/Pack2.scr + +module good.misc.imports.pack1.Pack02; + + +global protocol Pack2a(role A, role B) +{ + l1() from A to B; +} + +global protocol Pack2b(role A, role B) +//global protocol Pack2a(role A, role B) +{ + l1() from A to B; +} + diff --git a/scribble-test/src/test/resources/good/misc/imports/pack1/Pack03.scr b/scribble-test/src/test/resources/good/misc/imports/pack1/Pack03.scr new file mode 100644 index 000000000..94d45bc33 --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/imports/pack1/Pack03.scr @@ -0,0 +1,10 @@ +//Raymond@HZHL2 ~/code/python/scribble-tools +//$ PYTHONPATH='lib/:bin/' python src/scribble/Main.py test/base/impourt/pack1/Pack3.scr + +module good.misc.imports.pack1.Pack03; + +global protocol Pack1(role A, role B) +{ + l1() from A to B; +} + diff --git a/scribble-test/src/test/resources/good/misc/imports/pack1/Pack04a.scr b/scribble-test/src/test/resources/good/misc/imports/pack1/Pack04a.scr new file mode 100644 index 000000000..536faebbf --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/imports/pack1/Pack04a.scr @@ -0,0 +1,13 @@ +//Raymond@HZHL2 ~/code/python/scribble-tools +//$ PYTHONPATH='lib/:bin/' python src/scribble/Main.py test/base/impourt/pack1/Pack4a.scr + +module good.misc.imports.pack1.Pack04a; + +import good.misc.imports.pack1.Pack04b; + + +global protocol Pack4(role A, role B) +{ + l1() from A to B; +} + diff --git a/scribble-test/src/test/resources/good/misc/imports/pack1/Pack04b.scr b/scribble-test/src/test/resources/good/misc/imports/pack1/Pack04b.scr new file mode 100644 index 000000000..c9122edef --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/imports/pack1/Pack04b.scr @@ -0,0 +1,13 @@ +//Raymond@HZHL2 ~/code/python/scribble-tools +//$ PYTHONPATH='lib/:bin/' python src/scribble/Main.py test/base/impourt/pack1/Pack4b.scr + +module good.misc.imports.pack1.Pack04b; + +import good.misc.imports.pack1.Pack04a; + + +global protocol Pack4(role A, role B) +{ + l1() from A to B; +} + diff --git a/scribble-test/src/test/resources/good/misc/imports/pack1/Pack05.scr b/scribble-test/src/test/resources/good/misc/imports/pack1/Pack05.scr new file mode 100644 index 000000000..c2935c206 --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/imports/pack1/Pack05.scr @@ -0,0 +1,13 @@ +//Raymond@HZHL2 ~/code/python/scribble-tools +//$ PYTHONPATH='lib/:bin/' python src/scribble/Main.py test/base/impourt/pack1/Pack5.scr + +module good.misc.imports.pack1.Pack05; + +import good.misc.imports.pack2.Pack05; + + +global protocol Pack5(role A, role B) +{ + l1() from A to B; +} + diff --git a/scribble-test/src/test/resources/good/misc/imports/pack1/Pack07.scr b/scribble-test/src/test/resources/good/misc/imports/pack1/Pack07.scr new file mode 100644 index 000000000..d13ee27f2 --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/imports/pack1/Pack07.scr @@ -0,0 +1,11 @@ +//Raymond@HZHL2 ~/code/python/scribble-tools +//$ PYTHONPATH='lib/:bin/' python src/scribble/Main.py test/base/impourt/pack1/Pack7.scr + +module good.misc.imports.pack1.Pack07; + + +global protocol Pack7(role A, role B) +{ + l1() from A to B; +} + diff --git a/scribble-test/src/test/resources/good/misc/imports/pack1/Pack08.scr b/scribble-test/src/test/resources/good/misc/imports/pack1/Pack08.scr new file mode 100644 index 000000000..51343c7e8 --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/imports/pack1/Pack08.scr @@ -0,0 +1,12 @@ +//Raymond@HZHL2 ~/code/python/scribble-tools +//$ PYTHONPATH='lib/:bin/' python src/scribble/Main.py test/base/impourt/pack1/Pack8.scr + +module good.misc.imports.pack1.Pack08; + + +global protocol Pack8(role C, role D) +{ + l1() from C to D; + //l1() from A to D; +} + diff --git a/scribble-test/src/test/resources/good/misc/imports/pack1/Pack09.scr b/scribble-test/src/test/resources/good/misc/imports/pack1/Pack09.scr new file mode 100644 index 000000000..094b3d166 --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/imports/pack1/Pack09.scr @@ -0,0 +1,12 @@ +//Raymond@HZHL2 ~/code/python/scribble-tools +//$ PYTHONPATH='lib/:bin/' python src/scribble/Main.py test/base/impourt/pack1/Pack9.scr + +module good.misc.imports.pack1.Pack09; + + +global protocol Pack9(role C, role D) +{ + l1() from C to D; + //l2() from C to D; // Uncomment is OK; with above commented not OK +} + diff --git a/scribble-test/src/test/resources/good/misc/imports/pack1/Pack10.scr b/scribble-test/src/test/resources/good/misc/imports/pack1/Pack10.scr new file mode 100644 index 000000000..30848a913 --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/imports/pack1/Pack10.scr @@ -0,0 +1,10 @@ +//Raymond@HZHL2 ~/code/python/scribble-tools +//$ PYTHONPATH='lib/:bin/' python src/scribble/Main.py test/base/impourt/pack1/Pack10.scr + +module good.misc.imports.pack1.Pack10; + +global protocol Pack10(role C, role D) +{ + l1() from C to D; +} + diff --git a/scribble-test/src/test/resources/good/misc/imports/pack1/Pack11.scr b/scribble-test/src/test/resources/good/misc/imports/pack1/Pack11.scr new file mode 100644 index 000000000..351d52762 --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/imports/pack1/Pack11.scr @@ -0,0 +1,15 @@ +//Raymond@HZHL2 ~/code/python/scribble-tools +//$ PYTHONPATH='lib/:bin/' python src/scribble/Main.py -ip test/ test/base/impourt/pack1/Pack11.scr + +module good.misc.imports.pack1.Pack11; + +import good.misc.imports.pack2.Pack11; +//import good.misc.imports.Import11; // OK + + +global protocol Pack11(role C, role D) +{ + do good.misc.imports.pack2.Pack11.Pack11(C, D); + //do good.misc.imports.Import11.Import11Aux(C, D); // OK +} + diff --git a/scribble-test/src/test/resources/good/misc/imports/pack1/Pack12.scr b/scribble-test/src/test/resources/good/misc/imports/pack1/Pack12.scr new file mode 100644 index 000000000..c97285164 --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/imports/pack1/Pack12.scr @@ -0,0 +1,11 @@ +//Raymond@HZHL2 ~/code/python/scribble-tools +//$ PYTHONPATH='lib/:bin/' python src/scribble/Main.py test/base/impourt/pack1/Pack12.scr + +module good.misc.imports.pack1.Pack12; + + +global protocol Pack12(role C, role D) +{ + X from C to D; +} + diff --git a/scribble-test/src/test/resources/good/misc/imports/pack1/Pack13.scr b/scribble-test/src/test/resources/good/misc/imports/pack1/Pack13.scr new file mode 100644 index 000000000..bb2c2da6d --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/imports/pack1/Pack13.scr @@ -0,0 +1,20 @@ +//Raymond@HZHL2 ~/code/python/scribble-tools +//$ PYTHONPATH='lib/:bin/' python src/scribble/Main.py -ip test/ test/base/impourt/pack1/Pack13.scr + +module good.misc.imports.pack1.Pack13; + +import good.misc.imports.Import13; + + +global protocol Pack13(role C, role D) +{ + do good.misc.imports.Import13.Import13Aux(C, D); + //do Import13Aux(C, D); + //do ImportAux(C, D); // Uncomment is OK (with below declaration) +} + +/*global protocol ImportAux(role A, role B) // TODO: make separate test for visibility building for do-target +{ + X from A to B; +}*/ + diff --git a/scribble-test/src/test/resources/good/misc/imports/pack1/Pack14.scr b/scribble-test/src/test/resources/good/misc/imports/pack1/Pack14.scr new file mode 100644 index 000000000..367523ddf --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/imports/pack1/Pack14.scr @@ -0,0 +1,13 @@ +//Raymond@HZHL2 ~/code/python/scribble-tools +//$ PYTHONPATH='lib/:bin/' python src/scribble/Main.py -ip test/ test/base/impourt/pack1/Pack14.scr + +module good.misc.imports.pack1.Pack14; + +import good.misc.imports.Import14; + + +global protocol Pack14(role C, role D) +{ + do good.misc.imports.Import14.Import14Aux(C, D); +} + diff --git a/scribble-test/src/test/resources/good/misc/imports/pack1/Pack16.scr b/scribble-test/src/test/resources/good/misc/imports/pack1/Pack16.scr new file mode 100644 index 000000000..9de4f9581 --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/imports/pack1/Pack16.scr @@ -0,0 +1,11 @@ +//Raymond@HZHL2 ~/code/python/scribble-tools +//$ PYTHONPATH='lib/:bin/' python src/scribble/Main.py -ip test/ test/base/impourt/pack1/Pack16.scr + +module good.misc.imports.pack1.Pack16; + + +global protocol Pack16(role C, role D) +{ + l1() from C to D; +} + diff --git a/scribble-test/src/test/resources/good/misc/imports/pack2/IGNORE b/scribble-test/src/test/resources/good/misc/imports/pack2/IGNORE new file mode 100644 index 000000000..e69de29bb diff --git a/scribble-test/src/test/resources/good/misc/imports/pack2/Pack05.scr b/scribble-test/src/test/resources/good/misc/imports/pack2/Pack05.scr new file mode 100644 index 000000000..7e23c9d64 --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/imports/pack2/Pack05.scr @@ -0,0 +1,14 @@ +//Raymond@HZHL2 ~/code/python/scribble-tools +//$ PYTHONPATH='lib/:bin/' python src/scribble/Main.py test/base/impourt/pack2/Pack5.scr + +module good.misc.imports.pack2.Pack05; + +import good.misc.imports.pack1.Pack05; + + +global protocol Pack5(role A, role B) +{ + l1() from A to B; + //l1() from B to C; +} + diff --git a/scribble-test/src/test/resources/good/misc/imports/pack2/Pack10.scr b/scribble-test/src/test/resources/good/misc/imports/pack2/Pack10.scr new file mode 100644 index 000000000..1659787bc --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/imports/pack2/Pack10.scr @@ -0,0 +1,11 @@ +//Raymond@HZHL2 ~/code/python/scribble-tools +//$ PYTHONPATH='lib/:bin/' python src/scribble/Main.py test/base/impourt/pack2/Pack10.scr + +module good.misc.imports.pack2.Pack10; + +global protocol Pack10(role C, role D) +{ + l2() from C to D; + //l1() from C to D; // Bad if above line is commented +} + diff --git a/scribble-test/src/test/resources/good/misc/imports/pack2/Pack11.scr b/scribble-test/src/test/resources/good/misc/imports/pack2/Pack11.scr new file mode 100644 index 000000000..a34a765ca --- /dev/null +++ b/scribble-test/src/test/resources/good/misc/imports/pack2/Pack11.scr @@ -0,0 +1,13 @@ +//Raymond@HZHL2 ~/code/python/scribble-tools +//$ PYTHONPATH='lib/:bin/' python src/scribble/Main.py -ip test/ test/base/impourt/pack2/Pack11.scr + +module good.misc.imports.pack2.Pack11; + +import good.misc.imports.Import11; + + +global protocol Pack11(role C, role D) +{ + do good.misc.imports.Import11.Import11Aux(C, D); +} + diff --git a/scribble-test/src/test/resources/good/reach/globals/gdo/Test06a.scr b/scribble-test/src/test/resources/good/reach/globals/gdo/Test06a.scr new file mode 100644 index 000000000..bfff8c206 --- /dev/null +++ b/scribble-test/src/test/resources/good/reach/globals/gdo/Test06a.scr @@ -0,0 +1,22 @@ +module good.reach.globals.gdo.Test06a; + + +global protocol Foo(role A, role B) +{ + choice at A + { + 1() from A to B; + do Foo(A, B); + } + or + { + do Bar(A, B); + } +} + +global protocol Bar(role C, role D) +{ + 5() from C to D; + do Bar(C, D); +} + diff --git a/scribble-test/src/test/resources/good/reach/globals/gdo/Test06b.scr b/scribble-test/src/test/resources/good/reach/globals/gdo/Test06b.scr new file mode 100644 index 000000000..e96dd06e2 --- /dev/null +++ b/scribble-test/src/test/resources/good/reach/globals/gdo/Test06b.scr @@ -0,0 +1,22 @@ +module good.reach.globals.gdo.Test06b; + + +global protocol Foo(role A, role B) +{ + choice at A + { + 1() from A to B; + do Bar(A, B); + } + or + { + do Bar(A, B); + } +} + +global protocol Bar(role C, role D) +{ + 5() from C to D; + do Bar(C, D); +} + diff --git a/scribble-test/src/test/resources/good/reach/globals/gdo/Test06c.scr b/scribble-test/src/test/resources/good/reach/globals/gdo/Test06c.scr new file mode 100644 index 000000000..652e70ad6 --- /dev/null +++ b/scribble-test/src/test/resources/good/reach/globals/gdo/Test06c.scr @@ -0,0 +1,23 @@ +module good.reach.globals.gdo.Test06c; + + +global protocol Foo(role A, role B) +{ + choice at A + { + 1() from A to B; + do Bar(A, B); + } + or + { + 2() from A to B; + } + 3() from A to B; +} + +global protocol Bar(role C, role D) +{ + 5() from C to D; + do Bar(C, D); +} + diff --git a/scribble-test/src/test/resources/good/reach/globals/grecursion/Recursion08a.scr b/scribble-test/src/test/resources/good/reach/globals/grecursion/Recursion08a.scr new file mode 100644 index 000000000..bee832f00 --- /dev/null +++ b/scribble-test/src/test/resources/good/reach/globals/grecursion/Recursion08a.scr @@ -0,0 +1,20 @@ +module good.reach.globals.grecursion.Recursion08a; + + +global protocol Recursion8a(role A, role B, role C, role D) +{ + rec X + { + choice at A + { + l1() from A to B; + continue X; + } + or + { + l2() from A to B; + continue X; + } + } + l3() from C to D; +} diff --git a/scribble-test/src/test/resources/good/reach/globals/grecursion/Recursion15.scr b/scribble-test/src/test/resources/good/reach/globals/grecursion/Recursion15.scr new file mode 100644 index 000000000..83d1ca6bb --- /dev/null +++ b/scribble-test/src/test/resources/good/reach/globals/grecursion/Recursion15.scr @@ -0,0 +1,19 @@ +module good.reach.globals.grecursion.Recursion15; + + +global protocol Recursion15(role A, role B) +{ + rec X + { + m() from A to B; + choice at A + { + //m1() from A to B; + continue X; + } + or + { + m2() from A to B; + } + } +} diff --git a/scribble-test/src/test/resources/good/reach/globals/grecursion/Recursion16.scr b/scribble-test/src/test/resources/good/reach/globals/grecursion/Recursion16.scr new file mode 100644 index 000000000..09ed53c3c --- /dev/null +++ b/scribble-test/src/test/resources/good/reach/globals/grecursion/Recursion16.scr @@ -0,0 +1,19 @@ +module good.reach.globals.grecursion.Recursion16; + + +global protocol Recursion16(role A, role B) +{ + choice at A + { + m1() from A to B; + } + or + { + rec X + { + m2() from A to B; + continue X; // Uncomment (currently) bad + } + } + m3() from A to B; +} diff --git a/scribble-test/src/test/resources/good/reach/globals/grecursion/Recursion17a.scr b/scribble-test/src/test/resources/good/reach/globals/grecursion/Recursion17a.scr new file mode 100644 index 000000000..cbffaec9a --- /dev/null +++ b/scribble-test/src/test/resources/good/reach/globals/grecursion/Recursion17a.scr @@ -0,0 +1,25 @@ +module good.reach.globals.grecursion.Recursion17a; + + +global protocol Foo(role A, role B) +{ + rec Z + { + choice at A + { + rec X + { + 1() from A to B; + continue X; + } + } + or + { + rec Y + { + 2() from A to B; + } + } + } + 3() from A to B; +} diff --git a/scribble-test/src/test/resources/good/reach/globals/grecursion/Recursion17b.scr b/scribble-test/src/test/resources/good/reach/globals/grecursion/Recursion17b.scr new file mode 100644 index 000000000..76cae73f0 --- /dev/null +++ b/scribble-test/src/test/resources/good/reach/globals/grecursion/Recursion17b.scr @@ -0,0 +1,25 @@ +module good.reach.globals.grecursion.Recursion17b; + + +global protocol Foo(role A, role B) +{ + rec Z + { + choice at A + { + rec X + { + 1() from A to B; + } + } + or + { + rec Y + { + 2() from A to B; + continue Y; + } + } + } + 3() from A to B; +} diff --git a/scribble-test/src/test/resources/good/reach/globals/grecursion/Recursion17e.scr b/scribble-test/src/test/resources/good/reach/globals/grecursion/Recursion17e.scr new file mode 100644 index 000000000..22b911c58 --- /dev/null +++ b/scribble-test/src/test/resources/good/reach/globals/grecursion/Recursion17e.scr @@ -0,0 +1,26 @@ +module good.reach.globals.grecursion.Recursion17e; + + +global protocol Foo(role A, role B) +{ + rec Z + { + choice at A + { + rec X + { + 1() from A to B; + } + } + or + { + rec Y + { + 2() from A to B; + continue Y; + } + } + 4() from A to B; + } + 3() from A to B; +} diff --git a/scribble-test/src/test/resources/good/reach/globals/grecursion/Recursion19.scr b/scribble-test/src/test/resources/good/reach/globals/grecursion/Recursion19.scr new file mode 100644 index 000000000..35fb689ea --- /dev/null +++ b/scribble-test/src/test/resources/good/reach/globals/grecursion/Recursion19.scr @@ -0,0 +1,12 @@ +module good.reach.globals.grecursion.Recursion19; + + +global protocol Foo(role A, role B, role C, role D) +{ + rec X + { + 1() from A to B; + continue X; + } + 2() from C to D; +} diff --git a/scribble-test/src/test/resources/good/reach/globals/grecursion/Recursion20.scr b/scribble-test/src/test/resources/good/reach/globals/grecursion/Recursion20.scr new file mode 100644 index 000000000..b5bcf9680 --- /dev/null +++ b/scribble-test/src/test/resources/good/reach/globals/grecursion/Recursion20.scr @@ -0,0 +1,20 @@ +module good.reach.globals.grecursion.Recursion20; + + +global protocol Proto1(role A, role B) +{ + rec X + { + choice at A + { + 1() from A to B; + continue X; + } + or + { + 2() from A to B; + } + } + 3() from B to A; // Good: choice has an exit path +} + diff --git a/scribble-test/src/test/resources/good/safety/orphan/twoparty/Test01.scr b/scribble-test/src/test/resources/good/safety/orphan/twoparty/Test01.scr new file mode 100644 index 000000000..8382809f8 --- /dev/null +++ b/scribble-test/src/test/resources/good/safety/orphan/twoparty/Test01.scr @@ -0,0 +1,22 @@ +module good.safety.orphan.twoparty.Test01; + + +global protocol Proto1(role A, role B) +{ + rec X + { + choice at A + { + 1() from A to B; + continue X; + } + or + { + 1() from A to B; + 1() from A to B; + continue X; + } + } +} + + diff --git a/scribble-test/src/test/resources/good/safety/stuckmsg/fourparty/Test01.scr b/scribble-test/src/test/resources/good/safety/stuckmsg/fourparty/Test01.scr new file mode 100644 index 000000000..5053cdeec --- /dev/null +++ b/scribble-test/src/test/resources/good/safety/stuckmsg/fourparty/Test01.scr @@ -0,0 +1,38 @@ +module good.safety.stuckmsg.fourparty.Test01; + + +global protocol Proto1(role A, role B, role C, role D) +{ + choice at A + { + 1() from A to B; + rec X + { + 1() from A to B; + choice at B + { + 2() from B to C; + 2() from C to D; + choice at C + { + 2() from C to A; + } + or + { + () from C to A; + 2() from C to D; // Reception error if following is uncommented + //() from C to D; // OK because D only receives 2's + } + continue X; + } + } + } + or + { + 0() from A to B; + 0() from B to C; + 0() from C to D; + } +} + + diff --git a/scribble-test/src/test/resources/good/safety/stuckmsg/threeparty/Test01.scr b/scribble-test/src/test/resources/good/safety/stuckmsg/threeparty/Test01.scr new file mode 100644 index 000000000..0ac3f362d --- /dev/null +++ b/scribble-test/src/test/resources/good/safety/stuckmsg/threeparty/Test01.scr @@ -0,0 +1,18 @@ +module good.safety.stuckmsg.threeparty.Test01; + + +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + 1() from A to B; // Non-det "choice direction message", cf. standard branch/select syntax + 1() from B to C; + } + or + { + 1() from A to B; + 2() from B to C; + } +} + + diff --git a/scribble-test/src/test/resources/good/safety/stuckmsg/threeparty/Test03.scr b/scribble-test/src/test/resources/good/safety/stuckmsg/threeparty/Test03.scr new file mode 100644 index 000000000..829e48bcc --- /dev/null +++ b/scribble-test/src/test/resources/good/safety/stuckmsg/threeparty/Test03.scr @@ -0,0 +1,25 @@ +module good.safety.stuckmsg.threeparty.Test03; + + +// Similar to good.wfchoice.merge.Test04 +global protocol Proto1(role A, role B, role C) +{ + rec X + { + 1() from A to B; + 1() from B to C; + choice at B + { + 2() from B to A; + continue X; + } + or + { + 3() from B to A; + 1() from B to C; + //3() from B to C; + continue X; + } + } +} + diff --git a/scribble-test/src/test/resources/good/safety/stuckmsg/twoparty/Test02.scr b/scribble-test/src/test/resources/good/safety/stuckmsg/twoparty/Test02.scr new file mode 100644 index 000000000..ca0140deb --- /dev/null +++ b/scribble-test/src/test/resources/good/safety/stuckmsg/twoparty/Test02.scr @@ -0,0 +1,15 @@ +module good.safety.stuckmsg.twoparty.Test02; + + +global protocol Proto1(role A, role B) +{ + choice at A + { + 1() from A to B; + } + or + { + 1() from A to B; + } +} + diff --git a/scribble-test/src/test/resources/good/syntax/consistentchoicesubj/Test02.scr b/scribble-test/src/test/resources/good/syntax/consistentchoicesubj/Test02.scr new file mode 100644 index 000000000..43d60af22 --- /dev/null +++ b/scribble-test/src/test/resources/good/syntax/consistentchoicesubj/Test02.scr @@ -0,0 +1,16 @@ +module good.syntax.consistentchoicesubj.Test02; + + +// Maybe refactor as projection +global protocol Proto1(role C, role S) +{ + choice at C + { + 0() from C to S; + choice at S // Fixed peekParentEnv index bug for enabled choice subjs + { + 1() from S to C; + } + } +} + diff --git a/scribble-test/src/test/resources/good/syntax/consistentchoicesubj/Test03.scr b/scribble-test/src/test/resources/good/syntax/consistentchoicesubj/Test03.scr new file mode 100644 index 000000000..930976b01 --- /dev/null +++ b/scribble-test/src/test/resources/good/syntax/consistentchoicesubj/Test03.scr @@ -0,0 +1,19 @@ +module good.syntax.consistentchoicesubj.Test03; + + +// Maybe refactor as projection +global protocol Proto1(role C, role S) +{ + rec X + { + choice at C + { + 0() from C to S; + rec Y + { + 1() from S to C; + } + } + } +} + diff --git a/scribble-test/src/test/resources/good/syntax/disamb/Test01.scr b/scribble-test/src/test/resources/good/syntax/disamb/Test01.scr new file mode 100644 index 000000000..7eccc8639 --- /dev/null +++ b/scribble-test/src/test/resources/good/syntax/disamb/Test01.scr @@ -0,0 +1,14 @@ +module good.syntax.disamb.Test01; + + +sig "foo" from "bar" as M1; + + +global protocol Foo(role A, role B) +{ + () from A to B; + M from A to B; + M1 from A to B; + //M2 from A to B; +} + diff --git a/scribble-test/src/test/resources/good/syntax/disamb/imports/Import01.scr b/scribble-test/src/test/resources/good/syntax/disamb/imports/Import01.scr new file mode 100644 index 000000000..fb8d1507c --- /dev/null +++ b/scribble-test/src/test/resources/good/syntax/disamb/imports/Import01.scr @@ -0,0 +1,15 @@ +//$ bin/scribblec.sh -ip scribble-test/src/test/resources scribble-test/src/test/resources/good/syntax/disamb/imports/Import01.scr + +module good.syntax.disamb.imports.Import01; + + +import good.syntax.disamb.imports.Import01a; +import good.syntax.disamb.imports.pack1.Import01b as Test4; // <- "Test3" as Test4 + + +global protocol Import1(role A, role B) +{ + 1() from A to B; + do good.syntax.disamb.imports.Import01a.Import1a(A, B); + do Test4.Import1b(A, B); +} diff --git a/scribble-test/src/test/resources/good/syntax/disamb/imports/Import01a.scr b/scribble-test/src/test/resources/good/syntax/disamb/imports/Import01a.scr new file mode 100644 index 000000000..6d565efcc --- /dev/null +++ b/scribble-test/src/test/resources/good/syntax/disamb/imports/Import01a.scr @@ -0,0 +1,16 @@ +// bin/scribblec.sh scribble-test/src/test/resources/good/syntax/disamb/imports/Import01a.scr -ip scribble-test/src/test/resources -project Import1a C + +module good.syntax.disamb.imports.Import01a; + +import good.syntax.disamb.imports.pack1.Import01b as Test3; +import good.syntax.disamb.imports.Import01c; +import good.syntax.disamb.imports.Import01c as T4; + +global protocol Import1a(role C, role D) +{ + 2(Test3.TTT) from C to D; + 2() from C to D; + do Test3.Import1b(C, D); + do good.syntax.disamb.imports.Import01c.Import1c(C, D); + do T4.Import1c(C, D); +} diff --git a/scribble-test/src/test/resources/good/syntax/disamb/imports/Import01c.scr b/scribble-test/src/test/resources/good/syntax/disamb/imports/Import01c.scr new file mode 100644 index 000000000..075f02be9 --- /dev/null +++ b/scribble-test/src/test/resources/good/syntax/disamb/imports/Import01c.scr @@ -0,0 +1,7 @@ +module good.syntax.disamb.imports.Import01c; + + +global protocol Import1c(role C, role D) +{ + 4() from C to D; +} diff --git a/scribble-test/src/test/resources/good/syntax/disamb/imports/Import02.scr b/scribble-test/src/test/resources/good/syntax/disamb/imports/Import02.scr new file mode 100644 index 000000000..afb6c13b4 --- /dev/null +++ b/scribble-test/src/test/resources/good/syntax/disamb/imports/Import02.scr @@ -0,0 +1,25 @@ +module good.syntax.disamb.imports.Import02; + + +import good.syntax.disamb.imports.pack1.Import02b; + + +global protocol Foo(role A, role B) +{ + choice at A + { + 1() from A to B; + } + or + { + do good.syntax.disamb.imports.pack1.Import02b.Bar(A, B); + do Bar(A, B); + } +} + + +global protocol Bar(role C, role D) +{ + 2() from C to D; +} + diff --git a/scribble-test/src/test/resources/good/syntax/disamb/imports/Import03.scr b/scribble-test/src/test/resources/good/syntax/disamb/imports/Import03.scr new file mode 100644 index 000000000..cfccdd3c7 --- /dev/null +++ b/scribble-test/src/test/resources/good/syntax/disamb/imports/Import03.scr @@ -0,0 +1,13 @@ +module good.syntax.disamb.imports.Import03; + + +import good.syntax.disamb.imports.pack1.Import02b; + + +global protocol Foo(role A, role B) +{ + 1() from A to B; + do good.syntax.disamb.imports.pack1.Import02b.Bar(A, B); + 2() from A to B; +} + diff --git a/scribble-test/src/test/resources/good/syntax/disamb/imports/Import04.scr b/scribble-test/src/test/resources/good/syntax/disamb/imports/Import04.scr new file mode 100644 index 000000000..7a72abaa7 --- /dev/null +++ b/scribble-test/src/test/resources/good/syntax/disamb/imports/Import04.scr @@ -0,0 +1,11 @@ +module good.syntax.disamb.imports.Import04; + + +import good.syntax.disamb.imports.pack1.Import04b as Bar; + + +global protocol Foo(role A, role B) +{ + do Bar.Proto2(A, B); +} + diff --git a/scribble-test/src/test/resources/good/syntax/disamb/imports/Import05.scr b/scribble-test/src/test/resources/good/syntax/disamb/imports/Import05.scr new file mode 100644 index 000000000..32398d6cc --- /dev/null +++ b/scribble-test/src/test/resources/good/syntax/disamb/imports/Import05.scr @@ -0,0 +1,16 @@ +module good.syntax.disamb.imports.Import05; + + +import good.syntax.disamb.imports.pack1.Test2; +import good.syntax.disamb.imports.pack1.Test3 as Test3; // The name Test3 is test3.Test3 in Test2 +import good.syntax.disamb.imports.pack1.test3.Test3 as Test4; // The name Test4 is actually Test4 in Test2 + + +global protocol Proto1(role A, role B) +{ + 1() from A to B; + do good.syntax.disamb.imports.pack1.Test2.Proto2(A, B); + do Test3.Foo3(A, B); + do Test4.Bar3(A, B); +} + diff --git a/scribble-test/src/test/resources/good/syntax/disamb/imports/pack1/IGNORE b/scribble-test/src/test/resources/good/syntax/disamb/imports/pack1/IGNORE new file mode 100644 index 000000000..e69de29bb diff --git a/scribble-test/src/test/resources/good/syntax/disamb/imports/pack1/Import01b.scr b/scribble-test/src/test/resources/good/syntax/disamb/imports/pack1/Import01b.scr new file mode 100644 index 000000000..6e5f8c283 --- /dev/null +++ b/scribble-test/src/test/resources/good/syntax/disamb/imports/pack1/Import01b.scr @@ -0,0 +1,10 @@ +module good.syntax.disamb.imports.pack1.Import01b; + + +type "..." from "..." as TTT; + + +global protocol Import1b(role A, role B) +{ + 3() from A to B; +} diff --git a/scribble-test/src/test/resources/good/syntax/disamb/imports/pack1/Import02b.scr b/scribble-test/src/test/resources/good/syntax/disamb/imports/pack1/Import02b.scr new file mode 100644 index 000000000..50a9ed5a3 --- /dev/null +++ b/scribble-test/src/test/resources/good/syntax/disamb/imports/pack1/Import02b.scr @@ -0,0 +1,18 @@ +module good.syntax.disamb.imports.pack1.Import02b; + + +import good.syntax.disamb.imports.Import02; + + +global protocol Bar(role C, role D) +{ + 3() from C to D; + do Foo(C, D); +} + + +global protocol Foo(role A, role B) +{ + 4() from A to B; + do good.syntax.disamb.imports.Import02.Bar(B, A); +} diff --git a/scribble-test/src/test/resources/good/syntax/disamb/imports/pack1/Import04b.scr b/scribble-test/src/test/resources/good/syntax/disamb/imports/pack1/Import04b.scr new file mode 100644 index 000000000..e1607d3e6 --- /dev/null +++ b/scribble-test/src/test/resources/good/syntax/disamb/imports/pack1/Import04b.scr @@ -0,0 +1,8 @@ +module good.syntax.disamb.imports.pack1.Import04b; + + +global protocol Proto2(role C, role D) +{ + Import04b() from C to D; +} + diff --git a/scribble-test/src/test/resources/good/syntax/disamb/imports/pack1/Test2.scr b/scribble-test/src/test/resources/good/syntax/disamb/imports/pack1/Test2.scr new file mode 100644 index 000000000..2096388cb --- /dev/null +++ b/scribble-test/src/test/resources/good/syntax/disamb/imports/pack1/Test2.scr @@ -0,0 +1,16 @@ +module good.syntax.disamb.imports.pack1.Test2; + + +import good.syntax.disamb.imports.pack1.test3.Test3 as Test3; // The name Test3 is Test3 in Test1 +import good.syntax.disamb.imports.pack1.Test4 as Test4; // The name Test4 is test3.Test3 in Test1 +import good.syntax.disamb.imports.pack1.Test4 as T4; + + +global protocol Proto2(role C, role D) +{ + 2(Test3.TTT) from C to D; + do Test3.Bar3(C, D); + do Test4.Proto4(C, D); + do T4.Proto4(C, D); +} + diff --git a/scribble-test/src/test/resources/good/syntax/disamb/imports/pack1/Test3.scr b/scribble-test/src/test/resources/good/syntax/disamb/imports/pack1/Test3.scr new file mode 100644 index 000000000..7a6e414d6 --- /dev/null +++ b/scribble-test/src/test/resources/good/syntax/disamb/imports/pack1/Test3.scr @@ -0,0 +1,8 @@ +module good.syntax.disamb.imports.pack1.Test3; + + +global protocol Foo3(role C, role D) +{ + foo3() from C to D; +} + diff --git a/scribble-test/src/test/resources/good/syntax/disamb/imports/pack1/Test4.scr b/scribble-test/src/test/resources/good/syntax/disamb/imports/pack1/Test4.scr new file mode 100644 index 000000000..0f75024eb --- /dev/null +++ b/scribble-test/src/test/resources/good/syntax/disamb/imports/pack1/Test4.scr @@ -0,0 +1,8 @@ +module good.syntax.disamb.imports.pack1.Test4; + + +global protocol Proto4(role C, role D) +{ + 4() from C to D; +} + diff --git a/scribble-test/src/test/resources/good/syntax/disamb/imports/pack1/test3/IGNORE b/scribble-test/src/test/resources/good/syntax/disamb/imports/pack1/test3/IGNORE new file mode 100644 index 000000000..e69de29bb diff --git a/scribble-test/src/test/resources/good/syntax/disamb/imports/pack1/test3/Test3.scr b/scribble-test/src/test/resources/good/syntax/disamb/imports/pack1/test3/Test3.scr new file mode 100644 index 000000000..d74e9c577 --- /dev/null +++ b/scribble-test/src/test/resources/good/syntax/disamb/imports/pack1/test3/Test3.scr @@ -0,0 +1,11 @@ +module good.syntax.disamb.imports.pack1.test3.Test3; + + +type "..." from "..." as TTT; + + +global protocol Bar3(role A, role B) +{ + bar3() from A to B; +} + diff --git a/scribble-test/src/test/resources/good/syntax/disamb/payloads/Test01.scr b/scribble-test/src/test/resources/good/syntax/disamb/payloads/Test01.scr new file mode 100644 index 000000000..a49640676 --- /dev/null +++ b/scribble-test/src/test/resources/good/syntax/disamb/payloads/Test01.scr @@ -0,0 +1,27 @@ +module good.syntax.disamb.payloads.Test01; + + +type "java.lang.String" from "rt.jar" as String; +type "java.lang.String" from "rt.jar" as String2; + + +global protocol Foo(role A, role B) +{ + choice at A + { + 1(String) from A to B; + 2(good.syntax.disamb.payloads.Test01.String) from A to B; + } + or + { + 3(good.syntax.disamb.payloads.Test01.String2) from A to B; + } + do Bar(A, B); + do Bar(A, B); +} + + +aux global protocol Bar(role A, role B) +{ + (T) from A to B; +} diff --git a/scribble-test/src/test/resources/good/syntax/disamb/recvarnode/Recursion01.scr b/scribble-test/src/test/resources/good/syntax/disamb/recvarnode/Recursion01.scr new file mode 100644 index 000000000..bd8b1ac12 --- /dev/null +++ b/scribble-test/src/test/resources/good/syntax/disamb/recvarnode/Recursion01.scr @@ -0,0 +1,11 @@ +module good.syntax.disamb.recvarnode.Recursion01; + + +global protocol Proto1(role A, role B) +{ + rec A // RecVars and roles different kinds of names + { + 1() from A to B; + } +} + diff --git a/scribble-test/src/test/resources/good/syntax/disamb/recvarnode/Recursion04a.scr b/scribble-test/src/test/resources/good/syntax/disamb/recvarnode/Recursion04a.scr new file mode 100644 index 000000000..163fd4f1d --- /dev/null +++ b/scribble-test/src/test/resources/good/syntax/disamb/recvarnode/Recursion04a.scr @@ -0,0 +1,18 @@ +module good.syntax.disamb.recvarnode.Recursion04a; + + +global protocol Recursion4a(role A, role B) +{ + rec X + { + l1() from A to B; + //rec Y + rec X // Uncomment bad, even if above line is commented + { + l2() from B to A; + continue X; + //continue Y; // Uncomment OK if the above line is commented + } + } +} + diff --git a/scribble-test/src/test/resources/good/syntax/disamb/recvarnode/Recursion14b.scr b/scribble-test/src/test/resources/good/syntax/disamb/recvarnode/Recursion14b.scr new file mode 100644 index 000000000..aa2ec09f7 --- /dev/null +++ b/scribble-test/src/test/resources/good/syntax/disamb/recvarnode/Recursion14b.scr @@ -0,0 +1,22 @@ +module good.syntax.disamb.recvarnode.Recursion14b; + + +global protocol Recursion14b(role A, role B) +{ + rec X + { + l1() from A to B; + //do Y: base.recursion.Recursion14.Recursion14a(A, B); + //do X: base.recursion.Recursion14.Recursion14a(A, B); // Uncomment OK if above line is commented + do good.syntax.disamb.recvarnode.Recursion14b.Recursion14a(A, B); // Uncomment bad, even if above two lines are commented + } +} + +global protocol Recursion14a(role A, role B) +{ + rec X + { + l1() from A to B; + continue X; + } +} diff --git a/scribble-test/src/test/resources/good/syntax/inlinedunfolding/gcontinue/Test03.scr b/scribble-test/src/test/resources/good/syntax/inlinedunfolding/gcontinue/Test03.scr new file mode 100644 index 000000000..4598c2715 --- /dev/null +++ b/scribble-test/src/test/resources/good/syntax/inlinedunfolding/gcontinue/Test03.scr @@ -0,0 +1,21 @@ +module good.syntax.inlinedunfolding.gcontinue.Test03; + + +global protocol Proto1(role A, role B) +{ + rec X + { + 1() from A to B; + choice at A + { + continue X; + } + or + { + 2() from A to B; + continue X; + } + } +} + + diff --git a/scribble-test/src/test/resources/good/syntax/inlinedunfolding/gcontinue/Test05.scr b/scribble-test/src/test/resources/good/syntax/inlinedunfolding/gcontinue/Test05.scr new file mode 100644 index 000000000..4334e8c80 --- /dev/null +++ b/scribble-test/src/test/resources/good/syntax/inlinedunfolding/gcontinue/Test05.scr @@ -0,0 +1,19 @@ +module good.syntax.inlinedunfolding.gcontinue.Test05; + + +global protocol Proto1(role A, role B) +{ + rec X + { + 1() from A to B; + choice at A + { + continue X; + } + or + { + 2() from A to B; + } + } +} + diff --git a/scribble-test/src/test/resources/good/syntax/inlinedunfolding/gdo/Test01a.scr b/scribble-test/src/test/resources/good/syntax/inlinedunfolding/gdo/Test01a.scr new file mode 100644 index 000000000..8166eb0ef --- /dev/null +++ b/scribble-test/src/test/resources/good/syntax/inlinedunfolding/gdo/Test01a.scr @@ -0,0 +1,18 @@ +module good.syntax.inlinedunfolding.gdo.Test01a; + + +global protocol Foo(role A, role B) +{ + choice at A + { + do Bar(A, B); + } +} + +// The Bar inlined rec for root Foo gets "dropped" by unguarded unfolding because no continue for this rec +aux global protocol Bar(role A, role B) +{ + 1() from A to B; + do Foo(A, B); +} + diff --git a/scribble-test/src/test/resources/good/syntax/inlinedunfolding/gdo/Test01b.scr b/scribble-test/src/test/resources/good/syntax/inlinedunfolding/gdo/Test01b.scr new file mode 100644 index 000000000..682c5dc74 --- /dev/null +++ b/scribble-test/src/test/resources/good/syntax/inlinedunfolding/gdo/Test01b.scr @@ -0,0 +1,18 @@ +module good.syntax.inlinedunfolding.gdo.Test01b; + + +global protocol Foo(role A, role B) +{ + choice at A + { + do Bar(A, B); + } +} + +// For root Foo, Bar inlined as unguarded rec, then gets unfolded +aux global protocol Bar(role A, role B) +{ + 4() from A to B; + do Bar(A, B); +} + diff --git a/scribble-test/src/test/resources/good/syntax/inlinedunfolding/gdo/Test02.scr b/scribble-test/src/test/resources/good/syntax/inlinedunfolding/gdo/Test02.scr new file mode 100644 index 000000000..56e2353c3 --- /dev/null +++ b/scribble-test/src/test/resources/good/syntax/inlinedunfolding/gdo/Test02.scr @@ -0,0 +1,43 @@ +module good.syntax.inlinedunfolding.gdo.Test02; + + +import good.syntax.inlinedunfolding.gdo.pack1.Test2 as Test2; + + +global protocol Foo(role A, role B) +{ + do Test2.Proto2(A, B); + 1() from A to B; + choice at A + { + //1() from A to B; + do Bar1(A, B); + //1() from A to B; + //do Foo(A, B); + } + or + { + //5() from A to B; + do Bar2(A, B); + } + or + { + //2() from A to B; + 4() from A to B; + } +} + +global protocol Bar1(role C, role D) +{ + 2() from C to D; + 3() from C to D; + do Foo(C, D); + //do Foo(D, C); +} + +global protocol Bar2(role C, role D) +{ + 5() from C to D; + do Bar2(C, D); +} + diff --git a/scribble-test/src/test/resources/good/syntax/inlinedunfolding/gdo/Test03.scr b/scribble-test/src/test/resources/good/syntax/inlinedunfolding/gdo/Test03.scr new file mode 100644 index 000000000..252d6d02e --- /dev/null +++ b/scribble-test/src/test/resources/good/syntax/inlinedunfolding/gdo/Test03.scr @@ -0,0 +1,16 @@ +module good.syntax.inlinedunfolding.gdo.Test03; + + +global protocol Proto1(role A, role B) +{ + choice at A + { + do Proto1Aux1(A, B); // Inlined as rec, then rec "dropped" by unfolding (no continue) + } +} + +aux global protocol Proto1Aux1(role A, role B) +{ + 1() from A to B; +} + diff --git a/scribble-test/src/test/resources/good/syntax/inlinedunfolding/gdo/pack1/IGNORE b/scribble-test/src/test/resources/good/syntax/inlinedunfolding/gdo/pack1/IGNORE new file mode 100644 index 000000000..e69de29bb diff --git a/scribble-test/src/test/resources/good/syntax/inlinedunfolding/gdo/pack1/Test2.scr b/scribble-test/src/test/resources/good/syntax/inlinedunfolding/gdo/pack1/Test2.scr new file mode 100644 index 000000000..995584bed --- /dev/null +++ b/scribble-test/src/test/resources/good/syntax/inlinedunfolding/gdo/pack1/Test2.scr @@ -0,0 +1,16 @@ +module good.syntax.inlinedunfolding.gdo.pack1.Test2; + + +import good.syntax.inlinedunfolding.gdo.pack1.test3.Test3 as Test3; // The name Test3 is Test3 in Test1 +import good.syntax.inlinedunfolding.gdo.pack1.Test4 as Test4; // The name Test4 is test3.Test3 in Test1 +import good.syntax.inlinedunfolding.gdo.pack1.Test4 as T4; + + +global protocol Proto2(role C, role D) +{ + 2(Test3.TTT) from C to D; + do Test3.Bar3(C, D); + do Test4.Proto4(C, D); + do T4.Proto4(C, D); +} + diff --git a/scribble-test/src/test/resources/good/syntax/inlinedunfolding/gdo/pack1/Test3.scr b/scribble-test/src/test/resources/good/syntax/inlinedunfolding/gdo/pack1/Test3.scr new file mode 100644 index 000000000..383d71f1b --- /dev/null +++ b/scribble-test/src/test/resources/good/syntax/inlinedunfolding/gdo/pack1/Test3.scr @@ -0,0 +1,8 @@ +module good.syntax.inlinedunfolding.gdo.pack1.Test3; + + +global protocol Foo3(role C, role D) +{ + foo3() from C to D; +} + diff --git a/scribble-test/src/test/resources/good/syntax/inlinedunfolding/gdo/pack1/Test4.scr b/scribble-test/src/test/resources/good/syntax/inlinedunfolding/gdo/pack1/Test4.scr new file mode 100644 index 000000000..e32912ce9 --- /dev/null +++ b/scribble-test/src/test/resources/good/syntax/inlinedunfolding/gdo/pack1/Test4.scr @@ -0,0 +1,8 @@ +module good.syntax.inlinedunfolding.gdo.pack1.Test4; + + +global protocol Proto4(role C, role D) +{ + 4() from C to D; +} + diff --git a/scribble-test/src/test/resources/good/syntax/inlinedunfolding/gdo/pack1/test3/IGNORE b/scribble-test/src/test/resources/good/syntax/inlinedunfolding/gdo/pack1/test3/IGNORE new file mode 100644 index 000000000..e69de29bb diff --git a/scribble-test/src/test/resources/good/syntax/inlinedunfolding/gdo/pack1/test3/Test3.scr b/scribble-test/src/test/resources/good/syntax/inlinedunfolding/gdo/pack1/test3/Test3.scr new file mode 100644 index 000000000..b8fa4e5f7 --- /dev/null +++ b/scribble-test/src/test/resources/good/syntax/inlinedunfolding/gdo/pack1/test3/Test3.scr @@ -0,0 +1,11 @@ +module good.syntax.inlinedunfolding.gdo.pack1.test3.Test3; + + +type "..." from "..." as TTT; + + +global protocol Bar3(role A, role B) +{ + bar3() from A to B; +} + diff --git a/scribble-test/src/test/resources/good/syntax/inlinedunfolding/grecursion/Test01.scr b/scribble-test/src/test/resources/good/syntax/inlinedunfolding/grecursion/Test01.scr new file mode 100644 index 000000000..a1299129e --- /dev/null +++ b/scribble-test/src/test/resources/good/syntax/inlinedunfolding/grecursion/Test01.scr @@ -0,0 +1,18 @@ +module good.syntax.inlinedunfolding.grecursion.Test01; + + +global protocol Foo(role A, role B) +{ + choice at A + { + rec X // Unguarded rec gets unfolded + { + 1() from A to B; + continue X; + } + } + or + { + 2() from A to B; + } +} diff --git a/scribble-test/src/test/resources/good/syntax/inlinedunfolding/grecursion/Test02a.scr b/scribble-test/src/test/resources/good/syntax/inlinedunfolding/grecursion/Test02a.scr new file mode 100644 index 000000000..cef817c1b --- /dev/null +++ b/scribble-test/src/test/resources/good/syntax/inlinedunfolding/grecursion/Test02a.scr @@ -0,0 +1,23 @@ +module good.syntax.inlinedunfolding.grecursion.Test02a; + + +global protocol Proto1(role A, role B) +{ + rec X + { + 1() from A to B; + choice at A + { + continue X; + } + or + { + rec Y // Testing nested InlinedProtocolUnfolding case + { + 2() from A to B; + continue Y; + } + } + } +} + diff --git a/scribble-test/src/test/resources/good/syntax/inlinedunfolding/grecursion/Test02b.scr b/scribble-test/src/test/resources/good/syntax/inlinedunfolding/grecursion/Test02b.scr new file mode 100644 index 000000000..904028914 --- /dev/null +++ b/scribble-test/src/test/resources/good/syntax/inlinedunfolding/grecursion/Test02b.scr @@ -0,0 +1,23 @@ +module good.syntax.inlinedunfolding.grecursion.Test02b; + + +global protocol Proto1(role A, role B) +{ + rec X + { + choice at A + { + 3() from A to B; + continue X; + } + or + { + rec Y // Testing nested InlinedProtocolUnfolding case + { + 2() from A to B; + continue Y; + } + } + } +} + diff --git a/scribble-test/src/test/resources/good/syntax/inlinedunfolding/grecursion/Test02c.scr b/scribble-test/src/test/resources/good/syntax/inlinedunfolding/grecursion/Test02c.scr new file mode 100644 index 000000000..66f64810e --- /dev/null +++ b/scribble-test/src/test/resources/good/syntax/inlinedunfolding/grecursion/Test02c.scr @@ -0,0 +1,24 @@ +module good.syntax.inlinedunfolding.grecursion.Test02c; + + +global protocol Proto1(role A, role B) +{ + rec X + { + 1() from A to B; + choice at A + { + 3() from A to B; + continue X; + } + or + { + rec Y // Testing nested InlinedProtocolUnfolding case + { + 2() from A to B; + continue Y; + } + } + } +} + diff --git a/scribble-test/src/test/resources/good/syntax/inlinedunfolding/grecursion/Test02d.scr b/scribble-test/src/test/resources/good/syntax/inlinedunfolding/grecursion/Test02d.scr new file mode 100644 index 000000000..c490f433e --- /dev/null +++ b/scribble-test/src/test/resources/good/syntax/inlinedunfolding/grecursion/Test02d.scr @@ -0,0 +1,23 @@ +module good.syntax.inlinedunfolding.grecursion.Test02d; + + +global protocol Proto1(role A, role B) +{ + rec X + { + 1() from A to B; + choice at A + { + continue X; + } + or + { + rec Y // Testing nested InlinedProtocolUnfolding case + { + 2() from A to B; + continue X; + } + } + } +} + diff --git a/scribble-test/src/test/resources/good/syntax/inlinedunfolding/grecursion/Test02e.scr b/scribble-test/src/test/resources/good/syntax/inlinedunfolding/grecursion/Test02e.scr new file mode 100644 index 000000000..54c669477 --- /dev/null +++ b/scribble-test/src/test/resources/good/syntax/inlinedunfolding/grecursion/Test02e.scr @@ -0,0 +1,23 @@ +module good.syntax.inlinedunfolding.grecursion.Test02e; + + +global protocol Proto1(role A, role B) +{ + rec X + { + choice at A + { + 3() from A to B; + continue X; + } + or + { + rec Y // Testing nested InlinedProtocolUnfolding case + { + 2() from A to B; + continue X; + } + } + } +} + diff --git a/scribble-test/src/test/resources/good/syntax/inlinedunfolding/grecursion/Test02f.scr b/scribble-test/src/test/resources/good/syntax/inlinedunfolding/grecursion/Test02f.scr new file mode 100644 index 000000000..c0fd36e4b --- /dev/null +++ b/scribble-test/src/test/resources/good/syntax/inlinedunfolding/grecursion/Test02f.scr @@ -0,0 +1,24 @@ +module good.syntax.inlinedunfolding.grecursion.Test02f; + + +global protocol Proto1(role A, role B) +{ + rec X + { + 1() from A to B; + choice at A + { + 3() from A to B; + continue X; + } + or + { + rec Y // Testing nested InlinedProtocolUnfolding case + { + 2() from A to B; + continue X; + } + } + } +} + diff --git a/scribble-test/src/test/resources/good/syntax/inlinedunfolding/grecursion/Test04.scr b/scribble-test/src/test/resources/good/syntax/inlinedunfolding/grecursion/Test04.scr new file mode 100644 index 000000000..9d3358e85 --- /dev/null +++ b/scribble-test/src/test/resources/good/syntax/inlinedunfolding/grecursion/Test04.scr @@ -0,0 +1,24 @@ +module good.syntax.inlinedunfolding.grecursion.Test04; + + +global protocol Proto4(role A, role B) +{ + choice at A + { + rec X + { + choice at A + { + 1() from A to B; + continue X; + } + or + { + 2() from A to B; + continue X; + } + } + } +} + + diff --git a/scribble-test/src/test/resources/good/syntax/projchoicesubjfix/Test01.scr b/scribble-test/src/test/resources/good/syntax/projchoicesubjfix/Test01.scr new file mode 100644 index 000000000..a2aee86f3 --- /dev/null +++ b/scribble-test/src/test/resources/good/syntax/projchoicesubjfix/Test01.scr @@ -0,0 +1,30 @@ +module good.syntax.projchoicesubjfix.Test01; + + +// Test transitive dependency collection and doarg name subs for projected choice subj inference +global protocol Foo(role A, role B) +{ + 1() from A to B; + choice at A + { + //1() from A to B; + do Bar1(A, B); + } + or + { + do Bar2(A, B); + } +} + +global protocol Bar1(role C, role D) // Test output all projections for transitive dependency collection +{ + 2() from C to D; + do Foo(C, D); +} + +global protocol Bar2(role E, role F) +{ + 3() from E to F; + //do Foo(E, F); +} + diff --git a/scribble-test/src/test/resources/good/syntax/projection/Test01.scr b/scribble-test/src/test/resources/good/syntax/projection/Test01.scr new file mode 100644 index 000000000..c02c6a440 --- /dev/null +++ b/scribble-test/src/test/resources/good/syntax/projection/Test01.scr @@ -0,0 +1,31 @@ +module good.syntax.projection.Test01; + + +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + 1() from A to B; + choice at A // Testing projection (e.g. B) + { + 2() from A to C; + } + or + { + rec X + { + 3() from A to C; + } + } + } + or + { + rec Y + { + 2() from A to B; + } + 4() from A to C; + } +} + + diff --git a/scribble-test/src/test/resources/good/syntax/projection/grecursion/Test01.scr b/scribble-test/src/test/resources/good/syntax/projection/grecursion/Test01.scr new file mode 100644 index 000000000..4f3ca7248 --- /dev/null +++ b/scribble-test/src/test/resources/good/syntax/projection/grecursion/Test01.scr @@ -0,0 +1,13 @@ +module good.syntax.projection.grecursion.Test01; + + +global protocol Proto1(role A, role B) +{ + 1() from A to B; + rec X + { + continue X; // Discarded + } + 2() from B to A; +} + diff --git a/scribble-test/src/test/resources/good/syntax/projection/grecursion/Test02a.scr b/scribble-test/src/test/resources/good/syntax/projection/grecursion/Test02a.scr new file mode 100644 index 000000000..6900df9e2 --- /dev/null +++ b/scribble-test/src/test/resources/good/syntax/projection/grecursion/Test02a.scr @@ -0,0 +1,27 @@ +module good.syntax.projection.grecursion.Test02a; + + +global protocol Proto1(role A, role B) +{ + choice at A + { + rec X // Testing unguarded choice-rec at root... + { + //1() from A to B; + choice at A + { + 2() from A to B; + } + or + { + continue X; // ..in conjunction with unguarded choice-continue -- continue pruned + } + } + } + or + { + 3() from A to B; + } +} + + diff --git a/scribble-test/src/test/resources/good/syntax/projection/grecursion/Test02b.scr b/scribble-test/src/test/resources/good/syntax/projection/grecursion/Test02b.scr new file mode 100644 index 000000000..96de550c5 --- /dev/null +++ b/scribble-test/src/test/resources/good/syntax/projection/grecursion/Test02b.scr @@ -0,0 +1,27 @@ +module good.syntax.projection.grecursion.Test02b; + + +global protocol Proto1(role A, role B) +{ + choice at A + { + rec X // Testing unguarded choice-rec at root.. + { + 1() from A to B; + choice at A + { + 2() from A to B; + } + or + { + continue X; // ..and unfolding + } + } + } + or + { + 3() from A to B; + } +} + + diff --git a/scribble-test/src/test/resources/good/syntax/projection/grecursion/Test03.scr b/scribble-test/src/test/resources/good/syntax/projection/grecursion/Test03.scr new file mode 100644 index 000000000..c70fc142c --- /dev/null +++ b/scribble-test/src/test/resources/good/syntax/projection/grecursion/Test03.scr @@ -0,0 +1,20 @@ +module good.syntax.projection.grecursion.Test03; + + +global protocol Proto1(role A, role B) +{ + rec X + { + m1() from A to B; + choice at A + { + continue X; // Not pruned because not first statement in rec body + // Will be pruned if m1() is commented + } + or + { + m2() from A to B; + } + } +} + diff --git a/scribble-test/src/test/resources/good/syntax/projection/grecursion/Test04a.scr b/scribble-test/src/test/resources/good/syntax/projection/grecursion/Test04a.scr new file mode 100644 index 000000000..345cc51de --- /dev/null +++ b/scribble-test/src/test/resources/good/syntax/projection/grecursion/Test04a.scr @@ -0,0 +1,18 @@ +module good.syntax.projection.grecursion.Test04a; + + +global protocol Proto1(role A, role B) +{ + choice at A + { + 1() from A to B; + rec X + { + choice at A + { + continue X; + } + } + } +} + diff --git a/scribble-test/src/test/resources/good/syntax/projection/grecursion/Test04b.scr b/scribble-test/src/test/resources/good/syntax/projection/grecursion/Test04b.scr new file mode 100644 index 000000000..79ff752c8 --- /dev/null +++ b/scribble-test/src/test/resources/good/syntax/projection/grecursion/Test04b.scr @@ -0,0 +1,26 @@ +module good.syntax.projection.grecursion.Test04b; + + +global protocol Proto1(role A, role B) +{ + choice at A + { + 1() from A to B; + rec Y + { + rec X + { + choice at A + { + continue X; + } + or + { + continue Y; + } + } + } + } +} + + diff --git a/scribble-test/src/test/resources/good/syntax/projection/grecursion/fair/IGNORE b/scribble-test/src/test/resources/good/syntax/projection/grecursion/fair/IGNORE new file mode 100644 index 000000000..e69de29bb diff --git a/scribble-test/src/test/resources/good/syntax/projection/grecursion/fair/Test03.scr b/scribble-test/src/test/resources/good/syntax/projection/grecursion/fair/Test03.scr new file mode 100644 index 000000000..43769a69d --- /dev/null +++ b/scribble-test/src/test/resources/good/syntax/projection/grecursion/fair/Test03.scr @@ -0,0 +1,34 @@ +module good.syntax.projection.grecursion.fair.Test03; + + +// Needs -fair +global protocol Proto1(role A, role B, role C) +{ + rec Y + { + rec Z + { + 0() from A to C; + rec X + { + choice at A + { + 1() from A to B; + continue X; // Testing "pruning" of irrelevant (wrt. role) continue cases in nested recs (e.g. C) + } + or + { + 2() from A to B; + continue Y; + } + or + { + 3a() from A to B; + 3b() from A to C; + } + } + } + } + 4() from B to C; +} + diff --git a/scribble-test/src/test/resources/good/syntax/projroledeclfix/Test01.scr b/scribble-test/src/test/resources/good/syntax/projroledeclfix/Test01.scr new file mode 100644 index 000000000..10cff809e --- /dev/null +++ b/scribble-test/src/test/resources/good/syntax/projroledeclfix/Test01.scr @@ -0,0 +1,19 @@ +//$ bin/scribblec.sh scribble-test/src/test/resources/good/syntax/projroledeclfix/Test01.scr -project Bar F + + +module good.syntax.projroledeclfix.Test01; + + +// Test unused roledecl filtering in projections +global protocol Foo(role A, role B, role C) +{ + 1() from A to B; + do Bar(A, B, C); +} + +global protocol Bar(role D, role E, role F) +{ + 2() from D to F; + do Foo(D, E, F); +} + diff --git a/scribble-test/src/test/resources/good/syntax/projroledeclfix/Test02.scr b/scribble-test/src/test/resources/good/syntax/projroledeclfix/Test02.scr new file mode 100644 index 000000000..2ca5d4e6f --- /dev/null +++ b/scribble-test/src/test/resources/good/syntax/projroledeclfix/Test02.scr @@ -0,0 +1,11 @@ +module good.syntax.projroledeclfix.Test02; + + +global protocol Proto1(role A, role B, role C, role D) +{ + 1() from A to B; + 2() from C to D; + do Proto1(A, B, C, D); // Testing projections +} + + diff --git a/scribble-test/src/test/resources/good/todo/Choice07.scr b/scribble-test/src/test/resources/good/todo/Choice07.scr new file mode 100644 index 000000000..f7b13a763 --- /dev/null +++ b/scribble-test/src/test/resources/good/todo/Choice07.scr @@ -0,0 +1,25 @@ +module good.misc.globals.gchoice.Choice07; + + +global protocol Choice7(role A, role B) +{ + /*// TODO + choice at A + { + par + { + l1() from A to B; + } + and + { + //l2() from B to A; // Uncomment is bad + l2() from A to B; + } + } + or + { + //l2() from A to B; // Uncomment is bad + l3() from A to B; + }*/ +} + diff --git a/scribble-test/src/test/resources/good/todo/Do01c.scr b/scribble-test/src/test/resources/good/todo/Do01c.scr new file mode 100644 index 000000000..dea59b3e5 --- /dev/null +++ b/scribble-test/src/test/resources/good/todo/Do01c.scr @@ -0,0 +1,17 @@ +module good.misc.globals.gdo.Do01c; + + +global protocol Do1c(role A, role B) +{ + do Do1aux(A, B); + do good.misc.globals.gdo.Do01c.Do1aux(A, B); // Uncomment is OK + do X: Do1aux(A, B); // Uncomment is OK // TODO + //do Do1aux(A, B); // Uncomment is bad + //do Do1aux(A, A); // Uncomment is bad +} + +global protocol Do1aux(role C, role D) +{ + l1() from C to D; +} + diff --git a/scribble-test/src/test/resources/good/todo/Do04b.scr b/scribble-test/src/test/resources/good/todo/Do04b.scr new file mode 100644 index 000000000..34589b050 --- /dev/null +++ b/scribble-test/src/test/resources/good/todo/Do04b.scr @@ -0,0 +1,27 @@ +module good.misc.globals.gdo.Do04b; + + +global protocol Do4b(role A, role B) +{ + choice at A + { + l1() from A to B; + } + or + { + do Do4_1(A as C, B as D); + do X: Do4_1(A as C, B as D); // Uncomment is OK // TODO + } +} + +global protocol Do4_1(role C, role D) +{ + do Do4_2(C as E, D as F); +} + +global protocol Do4_2(role E, role F) +{ + //l1() from E to F; // Uncomment OK for the X-do only, not the unscoped one + l2() from E to F; +} + diff --git a/scribble-test/src/test/resources/good/todo/Do04c.scr b/scribble-test/src/test/resources/good/todo/Do04c.scr new file mode 100644 index 000000000..dab51c326 --- /dev/null +++ b/scribble-test/src/test/resources/good/todo/Do04c.scr @@ -0,0 +1,27 @@ +module good.misc.globals.gdo.Do04c; + + +global protocol Do4c(role A, role B) +{ + choice at A + { + l1() from A to B; + } + or + { + //do Do4_1(A as C, B as D); + do X: Do4_1(A as C, B as D); // Uncomment is OK // TODO + } +} + +global protocol Do4_1(role C, role D) +{ + do Do4_2(C as E, D as F); +} + +global protocol Do4_2(role E, role F) +{ + l1() from E to F; // Uncomment OK for the X-do only, not the unscoped one + l2() from E to F; +} + diff --git a/scribble-test/src/test/resources/good/todo/Do12b.scr b/scribble-test/src/test/resources/good/todo/Do12b.scr new file mode 100644 index 000000000..9a7fa4b6e --- /dev/null +++ b/scribble-test/src/test/resources/good/todo/Do12b.scr @@ -0,0 +1,23 @@ +module good.misc.globals.gdo.Do12b; + + +global protocol Do12b(role A, role B) +{ + choice at A + { + do Do12_1(A, B); + } + or + { + //do Do12_1(A, B); // Uncomment is bad + do X: Do12_1(A, B); // Uncomment is OK // TODO + do Do12_1(A, B); + } +} + +global protocol Do12_1(role C, role D) +{ + X from C to D; +} + + diff --git a/scribble-test/src/test/resources/good/todo/Do16.scr b/scribble-test/src/test/resources/good/todo/Do16.scr new file mode 100644 index 000000000..0aa8135b1 --- /dev/null +++ b/scribble-test/src/test/resources/good/todo/Do16.scr @@ -0,0 +1,33 @@ +module good.misc.globals.gdo.Do16; + + +global protocol Do16(role A, role B) +{ + /*// TODO + par + { + l1() from A to B; + do Do16a(A, B); + //do Do16(A, B); // Uncomment is bad, inlcuding if above line is commented + } + and + { + l2() from A to B; + }*/ +} + +global protocol Do16a(role A, role B) +{ + choice at A + { + l3() from A to B; + do Do16a(A, B); + //do Do16(A, B); // Uncomment is bad, including if above line is commented + } + or + { + l4() from A to B; + //l2() from A to B; // Uncomment is bad + } +} + diff --git a/scribble-test/src/test/resources/good/todo/Do18.scr b/scribble-test/src/test/resources/good/todo/Do18.scr new file mode 100644 index 000000000..bf6c9bf1a --- /dev/null +++ b/scribble-test/src/test/resources/good/todo/Do18.scr @@ -0,0 +1,22 @@ +module good.misc.globals.gdo.Do18; + + +global protocol Do18(role A, role B) +{ + do Do18a(A, B); + //do Do18a(A, B); // Uncomment is bad +} + +global protocol Do18a(role C, role D) +{ + /*// TODO + par + { + X from C to D; + } + and + { + Y from C to D; + }*/ +} + diff --git a/scribble-test/src/test/resources/good/todo/Do20.scr b/scribble-test/src/test/resources/good/todo/Do20.scr new file mode 100644 index 000000000..a62f0dd90 --- /dev/null +++ b/scribble-test/src/test/resources/good/todo/Do20.scr @@ -0,0 +1,22 @@ +module good.misc.globals.gdo.Do20; + + +global protocol Do20(role A, role B) +{ + do Do20Aux(A, B); +} + +global protocol Do20Aux(role C, role D) +{ + /*// TODO + interruptible + { + X from C to D; + } + with + { + //Y by C; // FIXME: interrupt parameter + l2() by C; + }*/ +} + diff --git a/scribble-test/src/test/resources/good/todo/Do22.scr b/scribble-test/src/test/resources/good/todo/Do22.scr new file mode 100644 index 000000000..b7bc76705 --- /dev/null +++ b/scribble-test/src/test/resources/good/todo/Do22.scr @@ -0,0 +1,22 @@ +module good.misc.globals.gdo.Do22; + + +// Maybe subsumed by Do12 +global protocol Do22(role A, role B) +{ + choice at A + { + do X: Do22a(A, B); // TODO + //do Do22a(A, B); // Uncomment not OK if above line is commented + } + or + { + l1() from A to B; + } +} + +global protocol Do22a(role C, role D) +{ + l1() from C to D; +} + diff --git a/scribble-test/src/test/resources/good/todo/Do24.scr b/scribble-test/src/test/resources/good/todo/Do24.scr new file mode 100644 index 000000000..5e9db3cb5 --- /dev/null +++ b/scribble-test/src/test/resources/good/todo/Do24.scr @@ -0,0 +1,24 @@ +module good.misc.globals.gdo.Do24; + + +global protocol Do24(role A, role B) +{ + /*// TODO + interruptible + { + l1() from A to B; + do Do24a(A, B); + //do Do24(A, B); // Uncomment bad + } + with + { + + }*/ +} + +global protocol Do24a(role C, role D) +{ + l1() from C to D; + do Do24a(C, D); + //do Do24(C, D); // Uncomment bad even if above line is commented +} diff --git a/scribble-test/src/test/resources/good/todo/Do28.scr b/scribble-test/src/test/resources/good/todo/Do28.scr new file mode 100644 index 000000000..7aae6865c --- /dev/null +++ b/scribble-test/src/test/resources/good/todo/Do28.scr @@ -0,0 +1,20 @@ +module good.misc.globals.gdo.Do28; + + +global protocol Do28(role A, role B) +{ + choice at A + { + m1() from A to B; + } + or + { + //do Do28a(A, B); // Uncomment bad + do X: Do28a(A, B); // TODO + } +} + +global protocol Do28a(role C, role D) +{ + m1() from C to D; +} diff --git a/scribble-test/src/test/resources/good/todo/IGNORE b/scribble-test/src/test/resources/good/todo/IGNORE new file mode 100644 index 000000000..e69de29bb diff --git a/scribble-test/src/test/resources/good/todo/Recursion08.scr b/scribble-test/src/test/resources/good/todo/Recursion08.scr new file mode 100644 index 000000000..1bcdf1f5a --- /dev/null +++ b/scribble-test/src/test/resources/good/todo/Recursion08.scr @@ -0,0 +1,20 @@ +module good.misc.globals.grecursion.Recursion08; + + +global protocol Recursion8(role A, role B) +{ + rec X + { + /*// TODO: + par + { + l1() from A to B; + } + and + { + l2() from A to B; + }*/ + continue X; + } +} + diff --git a/scribble-test/src/test/resources/good/todo/Recursion09.scr b/scribble-test/src/test/resources/good/todo/Recursion09.scr new file mode 100644 index 000000000..e88c022c9 --- /dev/null +++ b/scribble-test/src/test/resources/good/todo/Recursion09.scr @@ -0,0 +1,20 @@ +module good.misc.globals.grecursion.Recursion09; + + +global protocol Recursion9(role A, role B) +{ + rec X + { + /*// TODO: + par + { + l1() from A to B; + } + and + { + l2() from B to A; // "potential deadlock" warning (not related to recursion) + }*/ + continue X; + } +} + diff --git a/scribble-test/src/test/resources/good/todo/Recursion10.scr b/scribble-test/src/test/resources/good/todo/Recursion10.scr new file mode 100644 index 000000000..23f3be483 --- /dev/null +++ b/scribble-test/src/test/resources/good/todo/Recursion10.scr @@ -0,0 +1,20 @@ +module parsing.globals.grecursion.Recursion10; + + +global protocol Recursion10(role A, role B, role C) +{ + rec X + { + /* // TODO: + par + { + l1() from A to B; + } + and + { + l2() from C to A; + }*/ + continue X; + } +} + diff --git a/scribble-test/src/test/resources/good/todo/Recursion12.scr b/scribble-test/src/test/resources/good/todo/Recursion12.scr new file mode 100644 index 000000000..c9b686d65 --- /dev/null +++ b/scribble-test/src/test/resources/good/todo/Recursion12.scr @@ -0,0 +1,21 @@ +module parsing.globals.grecursion.Recursion12; + + +global protocol Recursion12(role A, role B) +{ + /*// TODO: + par + { + rec X + { + l1() from A to B; + continue X; + } + } + and + { + l2() from B to A; + }*/ + //l3() from B to A; // Uncommented bad +} + diff --git a/scribble-test/src/test/resources/good/todo/Recursion14.scr b/scribble-test/src/test/resources/good/todo/Recursion14.scr new file mode 100644 index 000000000..0d2a5db94 --- /dev/null +++ b/scribble-test/src/test/resources/good/todo/Recursion14.scr @@ -0,0 +1,23 @@ +module parsing.globals.grecursion.Recursion14; + + +global protocol Recursion14(role A, role B) +{ + rec X + { + l1() from A to B; + /*// TODO: + do Y: base.recursion.Recursion14.Recursion14a(A, B); + //do X: base.recursion.Recursion14.Recursion14a(A, B); // Uncomment OK if above line is commented + //do base.recursion.Recursion14.Recursion14a(A, B); // Uncomment bad, even if above two lines are commented*/ + } +} + +global protocol Recursion14a(role A, role B) +{ + rec X + { + l1() from A to B; + continue X; + } +} diff --git a/scribble-test/src/test/resources/good/wfchoice/enabling/threeparty/Test01.scr b/scribble-test/src/test/resources/good/wfchoice/enabling/threeparty/Test01.scr new file mode 100644 index 000000000..c4e6e5d75 --- /dev/null +++ b/scribble-test/src/test/resources/good/wfchoice/enabling/threeparty/Test01.scr @@ -0,0 +1,17 @@ +module good.wfchoice.enabling.threeparty.Test01; + + +global protocol Proto1(role A, role B, role C) +{ + 1() from A to B; + 1() from A to C; + choice at A + { + do Proto1(A, B, C); + } + or + { + 2() from A to B; + 2() from A to C; + } +} diff --git a/scribble-test/src/test/resources/good/wfchoice/enabling/threeparty/Test03b.scr b/scribble-test/src/test/resources/good/wfchoice/enabling/threeparty/Test03b.scr new file mode 100644 index 000000000..a685f6b0b --- /dev/null +++ b/scribble-test/src/test/resources/good/wfchoice/enabling/threeparty/Test03b.scr @@ -0,0 +1,30 @@ +module good.wfchoice.enabling.threeparty.Test03b; + + +global protocol Proto1(role A, role B, role C) +{ + rec X + { + choice at A + { + 1() from A to B; + choice at B + { + 1() from B to C; + //continue X; // Non-enabled A under this choice at B + } + or + { + 3() from B to C; + //continue X; + } + continue X; // Scribble needs "sequencing" + } + or + { + 2() from A to B; + 2() from B to C; + } + } +} + diff --git a/scribble-test/src/test/resources/good/wfchoice/enabling/twoparty/Test01.scr b/scribble-test/src/test/resources/good/wfchoice/enabling/twoparty/Test01.scr new file mode 100644 index 000000000..5dad7dda5 --- /dev/null +++ b/scribble-test/src/test/resources/good/wfchoice/enabling/twoparty/Test01.scr @@ -0,0 +1,30 @@ +module good.wfchoice.enabling.twoparty.Test01; + + +global protocol Proto1(role A, role B) +{ + choice at A + { + 1() from A to B; + 2() from B to A; + choice at A // Nested choice: check for distinct enabling messages in path collection is not broken for the two paths in this choice induced by nested choice + { + 3a() from A to B; + } + or + { + 3b() from A to B; + } + } + 4() from B to A; + choice at A + { + 5a() from A to B; + } + or + { + 5b() from A to B; + } + // Check path collection // Deprecated +} + diff --git a/scribble-test/src/test/resources/good/wfchoice/enabling/twoparty/Test02.scr b/scribble-test/src/test/resources/good/wfchoice/enabling/twoparty/Test02.scr new file mode 100644 index 000000000..37b19e865 --- /dev/null +++ b/scribble-test/src/test/resources/good/wfchoice/enabling/twoparty/Test02.scr @@ -0,0 +1,38 @@ +module good.wfchoice.enabling.twoparty.Test02; + + +//* +global protocol Proto1(role A, role B) +{ + choice at A + { + 1() from A to B; + choice at B + { + 2() from B to A; + } + or + { + 3() from B to A; + } + } +} +/*/ +//Standard problem of basic path/trace based WF choice checking: non-equiv (e.g. bisim) nested choice structures get conflated (as set of all traces), when looking downstream (not just enabling message) +//checking enabling only via global model is easy, difficulty is merge +//* +global protocol Proto1(role A, role B) +{ + choice at A + { + 1() from A to B; + 2() from B to A; + } + or + { + 1() from A to B; + 3() from B to A; + } +} +//*/ + diff --git a/scribble-test/src/test/resources/good/wfchoice/gchoice/Choice09b.scr b/scribble-test/src/test/resources/good/wfchoice/gchoice/Choice09b.scr new file mode 100644 index 000000000..8dd30fd7e --- /dev/null +++ b/scribble-test/src/test/resources/good/wfchoice/gchoice/Choice09b.scr @@ -0,0 +1,34 @@ +module good.wfchoice.gchoice.Choice09b; + + +global protocol Proto1(role A, role B, role C) +{ + 3() from A to C; + rec Y + { + () from A to B; // Uncomment is bad (non-enabled B / non-disjoint labels) + 2a() from B to A; + rec X + { + 1() from A to B; + choice at A + { + 2() from A to B; + continue X; // Testing project choice subject "inference", and testing continue-only choice block + } + or + { + continue X; + } + or + { + continue Y; // Different continue-only-blocks, tests FSM building + } + or + { + 4() from A to B; + } + } + } +} + diff --git a/scribble-test/src/test/resources/good/wfchoice/gchoice/Choice09c.scr b/scribble-test/src/test/resources/good/wfchoice/gchoice/Choice09c.scr new file mode 100644 index 000000000..3f4f495f6 --- /dev/null +++ b/scribble-test/src/test/resources/good/wfchoice/gchoice/Choice09c.scr @@ -0,0 +1,33 @@ +module good.wfchoice.gchoice.Choice09c; + + +global protocol Proto1(role A, role B, role C) +{ + 3() from A to C; + rec Y + { + () from A to B; + 2a() from B to A; + rec X + { + 1() from A to B; + choice at A + { + continue X; // Testing project choice subject "inference", and testing continue-only choice block + } + or + { + continue X; + } + or + { + continue Y; // Different continue-only-blocks, tests FSM building + } + or + { + 4() from A to B; + } + } + } +} + diff --git a/scribble-test/src/test/resources/good/wfchoice/gchoice/Choice09d.scr b/scribble-test/src/test/resources/good/wfchoice/gchoice/Choice09d.scr new file mode 100644 index 000000000..0c2cfb8aa --- /dev/null +++ b/scribble-test/src/test/resources/good/wfchoice/gchoice/Choice09d.scr @@ -0,0 +1,33 @@ +module good.wfchoice.gchoice.Choice09d; + + +global protocol Proto1(role A, role B, role C) +{ + 3() from A to C; + rec Y + { + () from A to B; + 2a() from B to A; + rec X + { + 1() from A to B; + choice at A + { + continue X; // Testing project choice subject "inference", and testing continue-only choice block + } + or + { + continue Y; // Different continue-only-blocks, tests FSM building + } + or + { + continue X; + } + or + { + 4() from A to B; + } + } + } +} + diff --git a/scribble-test/src/test/resources/good/wfchoice/gchoice/Choice09e.scr b/scribble-test/src/test/resources/good/wfchoice/gchoice/Choice09e.scr new file mode 100644 index 000000000..948cff727 --- /dev/null +++ b/scribble-test/src/test/resources/good/wfchoice/gchoice/Choice09e.scr @@ -0,0 +1,33 @@ +module good.wfchoice.gchoice.Choice09e; + + +global protocol Proto1(role A, role B, role C) +{ + 3() from A to C; + rec Y + { + () from A to B; + 2a() from B to A; + rec X + { + 1() from A to B; + choice at A + { + continue Y; // Different continue-only-blocks, tests FSM building + } + or + { + continue X; // Testing project choice subject "inference", and testing continue-only choice block + } + or + { + continue X; + } + or + { + 4() from A to B; + } + } + } +} + diff --git a/scribble-test/src/test/resources/good/wfchoice/gchoice/Choice10.scr b/scribble-test/src/test/resources/good/wfchoice/gchoice/Choice10.scr new file mode 100644 index 000000000..ea8e0ca6b --- /dev/null +++ b/scribble-test/src/test/resources/good/wfchoice/gchoice/Choice10.scr @@ -0,0 +1,35 @@ +module good.wfchoice.gchoice.Choice10; + + +global protocol Proto1(role A, role B) +{ + rec X + { + 1() from A to B; + choice at A + { + continue X; + } + or + { + rec Y + { + 2() from A to B; + choice at A + { + continue X; + } + or + { + 2() from A to B; // OK to be 2, because the above continue-X does 1() first + } + or + { + 3() from A to B; + continue Y; + } + } + } + } +} + diff --git a/scribble-test/src/test/resources/good/wfchoice/gchoice/Choice11.scr b/scribble-test/src/test/resources/good/wfchoice/gchoice/Choice11.scr new file mode 100644 index 000000000..9735a71a1 --- /dev/null +++ b/scribble-test/src/test/resources/good/wfchoice/gchoice/Choice11.scr @@ -0,0 +1,25 @@ +module good.wfchoice.gchoice.Choice11; + + +global protocol Proto1(role A, role B, role C) +{ + rec X + { + 1() from A to B; + //1() from B to C; // bad enabling + //2() from A to B; // bad safety + //1() from A to C; // bad liveness + choice at A + { + 1() from A to C; + continue X; + } + or + { + 2() from A to B; + 2() from A to C; + } + } +} + + diff --git a/scribble-test/src/test/resources/good/wfchoice/gdo/Test01.scr b/scribble-test/src/test/resources/good/wfchoice/gdo/Test01.scr new file mode 100644 index 000000000..1974a00bc --- /dev/null +++ b/scribble-test/src/test/resources/good/wfchoice/gdo/Test01.scr @@ -0,0 +1,17 @@ +module good.wfchoice.gdo.Test01; + + +global protocol Foo(role A, role B) +{ + do Bar(A, B); +} + + +aux global protocol Bar(role A, role B) +{ + choice at A + { + 1() from A to B; // Enabling message recursive subproto + do Bar(B, A); + } +} diff --git a/scribble-test/src/test/resources/good/wfchoice/gdo/Test02.scr b/scribble-test/src/test/resources/good/wfchoice/gdo/Test02.scr new file mode 100644 index 000000000..459132c13 --- /dev/null +++ b/scribble-test/src/test/resources/good/wfchoice/gdo/Test02.scr @@ -0,0 +1,22 @@ +module good.wfchoice.gdo.Test02; + + +global protocol Foo(role A, role B) +{ + 1() from A to B; + choice at A + { + 2() from A to B; + } + or + { + do Bar(A, B); + } +} + + +global protocol Bar(role A, role B) +{ + do Foo(A, B); +} + diff --git a/scribble-test/src/test/resources/good/wfchoice/gdo/params/Test01.scr b/scribble-test/src/test/resources/good/wfchoice/gdo/params/Test01.scr new file mode 100644 index 000000000..81ec8788e --- /dev/null +++ b/scribble-test/src/test/resources/good/wfchoice/gdo/params/Test01.scr @@ -0,0 +1,23 @@ +module good.wfchoice.gdo.params.Test01; + + +global protocol Foo(role A, role B) +{ + choice at A + { + M1 from A to B; + 3() from B to A; + } + or + { + do Bar<1()>(A, B); + 4() from B to A; + } +} + + +aux global protocol Bar(role C, role D) +{ + M2 from C to D; +} + diff --git a/scribble-test/src/test/resources/good/wfchoice/gdo/params/Test02.scr b/scribble-test/src/test/resources/good/wfchoice/gdo/params/Test02.scr new file mode 100644 index 000000000..8f63e0657 --- /dev/null +++ b/scribble-test/src/test/resources/good/wfchoice/gdo/params/Test02.scr @@ -0,0 +1,25 @@ +//$ bin/scribblec.sh scribble-test/src/test/resources/good/wfchoice/gdo/Test02.scr -project Foo A + + +module good.wfchoice.gdo.params.Test02; + + +global protocol Foo(role A, role B) +{ + choice at A + { + do Bar<1()>(A, B); + 1() from B to A; + } + or + { + do Bar<2()>(A, B); + 2() from B to A; + } +} + +aux global protocol Bar(role C, role D) +{ + M from C to D; +} + diff --git a/scribble-test/src/test/resources/good/wfchoice/merge/Test01.scr b/scribble-test/src/test/resources/good/wfchoice/merge/Test01.scr new file mode 100644 index 000000000..6b3429bf0 --- /dev/null +++ b/scribble-test/src/test/resources/good/wfchoice/merge/Test01.scr @@ -0,0 +1,17 @@ +module good.wfchoice.merge.Test01; + + +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + 1() from A to B; + 3() from B to C; + } + or + { + 2() from A to B; + 3() from B to C; // Testing same continuation for C (mergability, rather than just factoring out) + } +} + diff --git a/scribble-test/src/test/resources/good/wfchoice/merge/Test02.scr b/scribble-test/src/test/resources/good/wfchoice/merge/Test02.scr new file mode 100644 index 000000000..8fe9ea4f4 --- /dev/null +++ b/scribble-test/src/test/resources/good/wfchoice/merge/Test02.scr @@ -0,0 +1,20 @@ +module good.wfchoice.merge.Test02; + + +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + 1() from A to B; + 2() from B to C; // Needs "merge", cannot be factored out + 4() from A to B; + } + or + { + 3() from A to B; + 2() from B to C; + 5() from A to B; + } +} + + diff --git a/scribble-test/src/test/resources/good/wfchoice/merge/Test03.scr b/scribble-test/src/test/resources/good/wfchoice/merge/Test03.scr new file mode 100644 index 000000000..cdc7fb627 --- /dev/null +++ b/scribble-test/src/test/resources/good/wfchoice/merge/Test03.scr @@ -0,0 +1,19 @@ +module good.wfchoice.merge.Test03; + + +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + 1() from A to B; + 1() from B to C; + } + or + { + 2() from A to B; + 1() from B to C; // Comment is bad + } + 2() from C to B; +} + + diff --git a/scribble-test/src/test/resources/good/wfchoice/merge/Test04a.scr b/scribble-test/src/test/resources/good/wfchoice/merge/Test04a.scr new file mode 100644 index 000000000..be7e95fe4 --- /dev/null +++ b/scribble-test/src/test/resources/good/wfchoice/merge/Test04a.scr @@ -0,0 +1,27 @@ +module good.wfchoice.merge.Test04a; + + +// Similar to good.safety.stuckmsg.threeparty.Test03 +global protocol Proto1(role A, role B, role C) +{ + rec X + { + 1() from A to B; + 2() from B to C; + 3() from B to C; + choice at A // Not mergeable by, e.g., ICALP13 + { + 4() from A to B; + continue X; + } + or + { + 5() from A to B; + 2() from B to C; // An "extra iteration" between B-C (but not A-B), but fine // Generates non-det B?2's for C to different states, but OK (cf. -minfsm) + 3() from B to C; + continue X; + } + } +} + + diff --git a/scribble-test/src/test/resources/good/wfchoice/merge/Test04b.scr b/scribble-test/src/test/resources/good/wfchoice/merge/Test04b.scr new file mode 100644 index 000000000..a4e0ec404 --- /dev/null +++ b/scribble-test/src/test/resources/good/wfchoice/merge/Test04b.scr @@ -0,0 +1,28 @@ +module good.wfchoice.merge.Test04b; + + +global protocol Proto1(role A, role B, role C) +{ + rec X + { + rec Y + { + 1() from A to B; + 2() from A to C; + choice at C + { + 3() from C to A; + continue X; + } + or + { + 4() from C to A; + 1() from A to B; // B only receives 1's, so mergeable + 1() from A to B; + continue Y; + } + } + } +} + + diff --git a/scribble-test/src/test/resources/good/wfchoice/merge/Test05.scr b/scribble-test/src/test/resources/good/wfchoice/merge/Test05.scr new file mode 100644 index 000000000..1d4946150 --- /dev/null +++ b/scribble-test/src/test/resources/good/wfchoice/merge/Test05.scr @@ -0,0 +1,20 @@ +module good.wfchoice.merge.Test05; + + +global protocol Proto1(role A, role B) +{ + choice at A // Not syntactically allowed or mergeable by standard MPST, plain syntactic equality of cases + { + 1() from A to B; + 1() from B to A; + 2() from A to B; + } + or + { + 1() from A to B; + 1() from B to A; + 2() from A to B; + } +} + + diff --git a/scribble-test/src/test/resources/good/wfchoice/merge/Test06.scr b/scribble-test/src/test/resources/good/wfchoice/merge/Test06.scr new file mode 100644 index 000000000..8e33d5bed --- /dev/null +++ b/scribble-test/src/test/resources/good/wfchoice/merge/Test06.scr @@ -0,0 +1,25 @@ +module good.wfchoice.merge.Test06; + + +type "java.lang.String" from "rt.jar" as String; +type "java.lang.Integer" from "rt.jar" as Int; +type "java.lang.Boolean" from "rt.jar" as Bool; +type "java.lang.Float" from "rt.jar" as Float; + + +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + Msg1a(String) from A to B; + Msg2(Int) from B to C; + Msg3(Bool) from C to A; + } + or + { + Msg1b(Float) from A to B; + Msg2(Int) from B to C; + Msg3(Bool) from C to A; + } +} + diff --git a/scribble-test/src/test/resources/scribble/examples/GMessage.scr b/scribble-test/src/test/resources/scribble/examples/GMessage.scr new file mode 100644 index 000000000..c2644017f --- /dev/null +++ b/scribble-test/src/test/resources/scribble/examples/GMessage.scr @@ -0,0 +1,9 @@ +module scribble.examples.GMessage; + +type "{http://www.acme.com/financial}Order" from "http://www.acme.com/schemas/Order.xsd" as Order; +type "{http://www.acme.com/financial}Customer" from "http://www.acme.com/schemas/Customer.xsd" as Customer; + +global protocol GMessageProtocol(role Buyer, role Seller) { + buy(Order, Customer) from Buyer to Seller; + buy(Order) from Buyer to Seller; +} diff --git a/scribble-test/src/test/resources/scribble/examples/Imports.scr b/scribble-test/src/test/resources/scribble/examples/Imports.scr new file mode 100644 index 000000000..ec23f7934 --- /dev/null +++ b/scribble-test/src/test/resources/scribble/examples/Imports.scr @@ -0,0 +1,7 @@ +module scribble.examples.Imports; + +import scribble.examples.GMessage; + +global protocol ImportsProtocol(role Buyer, role Seller) { + do GMessage.GMessageProtocol(Buyer, Seller); +} diff --git a/scribble-test/src/test/scrib/demo/fase17/intro/FirstL.scr b/scribble-test/src/test/scrib/demo/fase17/intro/FirstL.scr new file mode 100644 index 000000000..36df81a49 --- /dev/null +++ b/scribble-test/src/test/scrib/demo/fase17/intro/FirstL.scr @@ -0,0 +1,18 @@ +module demo.fase17.intro.FirstL; + + +global protocol P1(role A, role B, role C) +{ + rec X + { + choice at A + { + 1() from A to B; + } + or + { + 2() from A to C; + } + continue X; + } +} diff --git a/scribble-test/src/test/scrib/demo/fase17/intro/FirstR.scr b/scribble-test/src/test/scrib/demo/fase17/intro/FirstR.scr new file mode 100644 index 000000000..d9d063f26 --- /dev/null +++ b/scribble-test/src/test/scrib/demo/fase17/intro/FirstR.scr @@ -0,0 +1,20 @@ +module demo.fase17.intro.FirstR; + + +explicit global protocol P2(role A, role B, role C) +{ + rec X + { + choice at A + { + 1() connect A to B; + disconnect A and B; + } + or + { + 2() connect A to C; + disconnect A and C; + } + continue X; + } +} diff --git a/scribble-test/src/test/scrib/demo/fase17/overview/P1.scr b/scribble-test/src/test/scrib/demo/fase17/overview/P1.scr new file mode 100644 index 000000000..26ecd3387 --- /dev/null +++ b/scribble-test/src/test/scrib/demo/fase17/overview/P1.scr @@ -0,0 +1,14 @@ +module demo.fase17.overview.P1; + + +global protocol P1(role A, role B, role C) +{ + choice at A + { + 1() from A to B; + } + or + { + 2() from A to C; + } +} diff --git a/scribble-test/src/test/scrib/demo/fase17/travel/TravelA.java b/scribble-test/src/test/scrib/demo/fase17/travel/TravelA.java new file mode 100644 index 000000000..ce758b1da --- /dev/null +++ b/scribble-test/src/test/scrib/demo/fase17/travel/TravelA.java @@ -0,0 +1,79 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package demo.fase17.travel; + +import static demo.fase17.travel.TravelAgent.TravelAgent.TravelAgent.A; +import static demo.fase17.travel.TravelAgent.TravelAgent.TravelAgent.C; +import static demo.fase17.travel.TravelAgent.TravelAgent.TravelAgent.query; +import static demo.fase17.travel.TravelAgent.TravelAgent.TravelAgent.quote; +import static demo.fase17.travel.TravelAgent.TravelAgent.TravelAgent.accpt; +import static demo.fase17.travel.TravelAgent.TravelAgent.TravelAgent.reject; + +import java.io.IOException; + +import org.scribble.main.ScribRuntimeException; +import org.scribble.runtime.message.ObjectStreamFormatter; +import org.scribble.runtime.util.Buf; +import org.scribble.runtime.message.ObjectStreamFormatter; +import org.scribble.runtime.net.ScribServerSocket; +import org.scribble.runtime.net.SocketChannelServer; +import org.scribble.runtime.session.ExplicitEndpoint; + +import demo.fase17.travel.TravelAgent.TravelAgent.TravelAgent; +import demo.fase17.travel.TravelAgent.TravelAgent.statechans.A.EndSocket; +import demo.fase17.travel.TravelAgent.TravelAgent.statechans.A.TravelAgent_A_1; +import demo.fase17.travel.TravelAgent.TravelAgent.statechans.A.TravelAgent_A_2_Cases; +import demo.fase17.travel.TravelAgent.TravelAgent.roles.A; + +public class TravelA +{ + public void run() throws Exception + { + try (ScribServerSocket ss = new SocketChannelServer(8888)) + { + while (true) + { + TravelAgent sess = new TravelAgent(); + try (ExplicitEndpoint se = new ExplicitEndpoint<>(sess, A, new ObjectStreamFormatter())) + { + run( + new TravelAgent_A_1(se) + .accept(C, ss) + .branch(C)); + } + catch (ScribRuntimeException | IOException | ClassNotFoundException e) + { + e.printStackTrace(); + } + } + } + } + + private EndSocket run(TravelAgent_A_2_Cases A2) throws Exception + { + Buf b = new Buf<>(); + switch (A2.op) + { + case query: A2 = A2.receive(query, b).send(C, quote, 1234).branch(C); System.out.println("(A) query: " + b.val); return run(A2); + case accpt: EndSocket end = A2.receive(accpt, b); System.out.println("(A) yes: " + b.val); return end; + case reject: return A2.receive(reject); + default: throw new RuntimeException("Shouldn't get in here: " + A2.op); + } + } + + public static void main(String[] args) throws Exception + { + new TravelA().run(); + } +} diff --git a/scribble-test/src/test/scrib/demo/fase17/travel/TravelAgent.scr b/scribble-test/src/test/scrib/demo/fase17/travel/TravelAgent.scr new file mode 100644 index 000000000..042e563e7 --- /dev/null +++ b/scribble-test/src/test/scrib/demo/fase17/travel/TravelAgent.scr @@ -0,0 +1,45 @@ +//$ bin/scribblec.sh scribble-test/src/test/scrib/demo/fase17/travel/TravelAgent.scr -ip scribble-test/src/test/scrib/ -d scribble-test/src/test/scrib -api TravelAgent C -v +//$ javadoc -cp scribble-core/target/classes:scribble-runtime/target/classes:scribble-test/src/test/scrib -subpackages demo.fase17.travel.TravelAgent.TravelAgent -d scribble-test/javadoc/fase17/travel + + +module demo.fase17.travel.TravelAgent; + +type "java.lang.Integer" from "rt.jar" as Int; +type "java.lang.String" from "rt.jar" as String; + + +explicit global protocol TravelAgent(role C, role A, role S) +{ + connect C to A; + do Nego(C, A, S); +} + +aux global protocol Nego(role C, role A, role S) +{ + choice at C + { + query(String) from C to A; + quote(Int) from A to C; + do Nego(C, A, S); + } + or + { + do Pay(C, A, S); + } +} + +// has to be aux (if default, then C/S duplicate connection; if explicit, C/A not connected) +aux global protocol Pay(role C, role A, role S) +{ + choice at C + { + connect C to S; + payment(String) from C to S; + confirm(Int) from S to C; + accpt(Int) from C to A; + } + or + { + reject() from C to A; + } +} diff --git a/scribble-test/src/test/scrib/demo/fase17/travel/TravelC.java b/scribble-test/src/test/scrib/demo/fase17/travel/TravelC.java new file mode 100644 index 000000000..bd6d62444 --- /dev/null +++ b/scribble-test/src/test/scrib/demo/fase17/travel/TravelC.java @@ -0,0 +1,71 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package demo.fase17.travel; + +import static demo.fase17.travel.TravelAgent.TravelAgent.TravelAgent.A; +import static demo.fase17.travel.TravelAgent.TravelAgent.TravelAgent.C; +import static demo.fase17.travel.TravelAgent.TravelAgent.TravelAgent.S; +import static demo.fase17.travel.TravelAgent.TravelAgent.TravelAgent.confirm; +import static demo.fase17.travel.TravelAgent.TravelAgent.TravelAgent.payment; +import static demo.fase17.travel.TravelAgent.TravelAgent.TravelAgent.query; +import static demo.fase17.travel.TravelAgent.TravelAgent.TravelAgent.quote; +import static demo.fase17.travel.TravelAgent.TravelAgent.TravelAgent.accpt; + +import org.scribble.main.ScribRuntimeException; +import org.scribble.runtime.message.ObjectStreamFormatter; +import org.scribble.runtime.net.SocketChannelEndpoint; +import org.scribble.runtime.util.Buf; +import org.scribble.runtime.message.ObjectStreamFormatter; +import org.scribble.runtime.net.ScribServerSocket; +import org.scribble.runtime.net.SocketChannelServer; +import org.scribble.runtime.session.ExplicitEndpoint; + +import demo.fase17.travel.TravelAgent.TravelAgent.TravelAgent; +import demo.fase17.travel.TravelAgent.TravelAgent.statechans.C.TravelAgent_C_1; +import demo.fase17.travel.TravelAgent.TravelAgent.statechans.C.TravelAgent_C_2; +import demo.fase17.travel.TravelAgent.TravelAgent.roles.C; + +public class TravelC +{ + public void run() throws Exception + { + String[] queries = { "aaa", "bbb", "ccc" }; + + TravelAgent sess = new TravelAgent(); + try (ExplicitEndpoint se = new ExplicitEndpoint<>(sess, C, new ObjectStreamFormatter())) + { + Buf b = new Buf<>(); + TravelAgent_C_2 C2 = new TravelAgent_C_1(se) + .request(A, SocketChannelEndpoint::new, "localhost", 8888); + + //Stream.of(queries).forEach((q) -> C2.send(A, query, q).receive(A, quote, b)); // C2 not reassigned; exceptions not handled + for (int i = 0; i < queries.length; i++) + { + C2 = C2.send(A, query, queries[i]).receive(A, quote, b); + } + + C2.request(S, SocketChannelEndpoint::new, "localhost", 9999) + .send(S, payment, "efgh") + .receive(S, confirm, b) + .send(A, accpt, b.val); // Forward payment ref number + + System.out.println("(C) confirm: " + b.val); + } + } + + public static void main(String[] args) throws Exception + { + new TravelC().run(); + } +} diff --git a/scribble-test/src/test/scrib/demo/fase17/travel/TravelS.java b/scribble-test/src/test/scrib/demo/fase17/travel/TravelS.java new file mode 100644 index 000000000..3bcf5d94a --- /dev/null +++ b/scribble-test/src/test/scrib/demo/fase17/travel/TravelS.java @@ -0,0 +1,68 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package demo.fase17.travel; + +import static demo.fase17.travel.TravelAgent.TravelAgent.TravelAgent.C; +import static demo.fase17.travel.TravelAgent.TravelAgent.TravelAgent.S; +import static demo.fase17.travel.TravelAgent.TravelAgent.TravelAgent.confirm; +import static demo.fase17.travel.TravelAgent.TravelAgent.TravelAgent.payment; + +import java.io.IOException; + +import org.scribble.main.ScribRuntimeException; +import org.scribble.runtime.message.ObjectStreamFormatter; +import org.scribble.runtime.util.Buf; +import org.scribble.runtime.message.ObjectStreamFormatter; +import org.scribble.runtime.net.ScribServerSocket; +import org.scribble.runtime.net.SocketChannelServer; +import org.scribble.runtime.session.ExplicitEndpoint; + +import demo.fase17.travel.TravelAgent.TravelAgent.TravelAgent; +import demo.fase17.travel.TravelAgent.TravelAgent.statechans.S.TravelAgent_S_1; +import demo.fase17.travel.TravelAgent.TravelAgent.roles.S; +import org.scribble.runtime.util.Buf; + +public class TravelS +{ + public void run() throws Exception + { + try (ScribServerSocket ss = new SocketChannelServer(9999)) + { + Buf b = new Buf<>(); + + while (true) + { + TravelAgent sess = new TravelAgent(); + try (ExplicitEndpoint se = new ExplicitEndpoint<>(sess, S, new ObjectStreamFormatter())) + { + new TravelAgent_S_1(se) + .accept(C, ss) + .receive(C, payment, b) + .send(C, confirm, 4567); + + System.out.println("(S) payment: " + b.val); + } + catch (ScribRuntimeException | IOException | ClassNotFoundException e) + { + e.printStackTrace(); + } + } + } + } + + public static void main(String[] args) throws Exception + { + new TravelS().run(); + } +} diff --git a/scribble-test/src/test/scrib/demo/fase17/travel2/Travel2A.java b/scribble-test/src/test/scrib/demo/fase17/travel2/Travel2A.java new file mode 100644 index 000000000..65a28fb63 --- /dev/null +++ b/scribble-test/src/test/scrib/demo/fase17/travel2/Travel2A.java @@ -0,0 +1,85 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package demo.fase17.travel2; + +import static demo.fase17.travel2.TravelAgent2.TravelAgent2.TravelAgent2.A; +import static demo.fase17.travel2.TravelAgent2.TravelAgent2.TravelAgent2.C; +import static demo.fase17.travel2.TravelAgent2.TravelAgent2.TravelAgent2.S; +import static demo.fase17.travel2.TravelAgent2.TravelAgent2.TravelAgent2.accpt; +import static demo.fase17.travel2.TravelAgent2.TravelAgent2.TravelAgent2.port; +import static demo.fase17.travel2.TravelAgent2.TravelAgent2.TravelAgent2.query; +import static demo.fase17.travel2.TravelAgent2.TravelAgent2.TravelAgent2.quote; +import static demo.fase17.travel2.TravelAgent2.TravelAgent2.TravelAgent2.reject; + +import java.io.IOException; + +import org.scribble.main.ScribRuntimeException; +import org.scribble.runtime.message.ObjectStreamFormatter; +import org.scribble.runtime.net.SocketChannelEndpoint; +import org.scribble.runtime.util.Buf; +import org.scribble.runtime.message.ObjectStreamFormatter; +import org.scribble.runtime.net.ScribServerSocket; +import org.scribble.runtime.net.SocketChannelServer; +import org.scribble.runtime.session.ExplicitEndpoint; + +import demo.fase17.travel2.TravelAgent2.TravelAgent2.TravelAgent2; +import demo.fase17.travel2.TravelAgent2.TravelAgent2.statechans.A.EndSocket; +import demo.fase17.travel2.TravelAgent2.TravelAgent2.statechans.A.TravelAgent2_A_1; +import demo.fase17.travel2.TravelAgent2.TravelAgent2.statechans.A.TravelAgent2_A_2_Cases; +import demo.fase17.travel2.TravelAgent2.TravelAgent2.roles.A; + +public class Travel2A +{ + public void run() throws Exception + { + try (ScribServerSocket ss = new SocketChannelServer(8888)) + { + while (true) + { + TravelAgent2 sess = new TravelAgent2(); + try (ExplicitEndpoint se = new ExplicitEndpoint<>(sess, A, new ObjectStreamFormatter())) + { + run( + new TravelAgent2_A_1(se) + .accept(C, ss) + .branch(C)); + } + catch (ScribRuntimeException | IOException | ClassNotFoundException e) + { + e.printStackTrace(); + } + } + } + } + + private EndSocket run(TravelAgent2_A_2_Cases A2) throws Exception + { + Buf b = new Buf<>(); + switch (A2.op) + { + case query: A2 = A2.receive(query, b).send(C, quote, 1234).branch(C); System.out.println("(A) query: " + b.val); return run(A2); + case accpt: + //EndSocket end = A2.receive(accpt, b); System.out.println("(A) yes: " + b.val); return end; + return A2.receive(accpt).request(S, SocketChannelEndpoint::new, "localhost", 9999) + .receive(S, port, b).send(C, port, (Integer) b.val); + case reject: return A2.receive(reject); + default: throw new RuntimeException("Shouldn't get in here: " + A2.op); + } + } + + public static void main(String[] args) throws Exception + { + new Travel2A().run(); + } +} diff --git a/scribble-test/src/test/scrib/demo/fase17/travel2/Travel2C.java b/scribble-test/src/test/scrib/demo/fase17/travel2/Travel2C.java new file mode 100644 index 000000000..90ad27439 --- /dev/null +++ b/scribble-test/src/test/scrib/demo/fase17/travel2/Travel2C.java @@ -0,0 +1,70 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package demo.fase17.travel2; + +import static demo.fase17.travel2.TravelAgent2.TravelAgent2.TravelAgent2.A; +import static demo.fase17.travel2.TravelAgent2.TravelAgent2.TravelAgent2.C; +import static demo.fase17.travel2.TravelAgent2.TravelAgent2.TravelAgent2.S; +import static demo.fase17.travel2.TravelAgent2.TravelAgent2.TravelAgent2.confirm; +import static demo.fase17.travel2.TravelAgent2.TravelAgent2.TravelAgent2.query; +import static demo.fase17.travel2.TravelAgent2.TravelAgent2.TravelAgent2.quote; +import static demo.fase17.travel2.TravelAgent2.TravelAgent2.TravelAgent2.accpt; +import static demo.fase17.travel2.TravelAgent2.TravelAgent2.TravelAgent2.port; + +import org.scribble.main.ScribRuntimeException; +import org.scribble.runtime.message.ObjectStreamFormatter; +import org.scribble.runtime.net.SocketChannelEndpoint; +import org.scribble.runtime.util.Buf; +import org.scribble.runtime.message.ObjectStreamFormatter; +import org.scribble.runtime.net.ScribServerSocket; +import org.scribble.runtime.net.SocketChannelServer; +import org.scribble.runtime.session.ExplicitEndpoint; + +import demo.fase17.travel2.TravelAgent2.TravelAgent2.TravelAgent2; +import demo.fase17.travel2.TravelAgent2.TravelAgent2.statechans.C.TravelAgent2_C_1; +import demo.fase17.travel2.TravelAgent2.TravelAgent2.statechans.C.TravelAgent2_C_2; +import demo.fase17.travel2.TravelAgent2.TravelAgent2.roles.C; + +public class Travel2C +{ + public void run() throws Exception + { + String[] queries = { "aaa", "bbb", "ccc" }; + + TravelAgent2 sess = new TravelAgent2(); + try (ExplicitEndpoint se = new ExplicitEndpoint<>(sess, C, new ObjectStreamFormatter())) + { + Buf b = new Buf<>(); + TravelAgent2_C_2 C2 = new TravelAgent2_C_1(se) + .request(A, SocketChannelEndpoint::new, "localhost", 8888); + + for (int i = 0; i < queries.length; i++) + { + C2 = C2.send(A, query, queries[i]).receive(A, quote, b); + } + + C2.send(A, accpt) + .receive(A, port, b) + .request(S, SocketChannelEndpoint::new, "localhost", (Integer) b.val) // FIXME: connect message + .receive(S, confirm, b); + + System.out.println("(C) confirm: " + b.val); + } + } + + public static void main(String[] args) throws Exception + { + new Travel2C().run(); + } +} diff --git a/scribble-test/src/test/scrib/demo/fase17/travel2/Travel2S.java b/scribble-test/src/test/scrib/demo/fase17/travel2/Travel2S.java new file mode 100644 index 000000000..6b684cd74 --- /dev/null +++ b/scribble-test/src/test/scrib/demo/fase17/travel2/Travel2S.java @@ -0,0 +1,70 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package demo.fase17.travel2; + +import static demo.fase17.travel2.TravelAgent2.TravelAgent2.TravelAgent2.C; +import static demo.fase17.travel2.TravelAgent2.TravelAgent2.TravelAgent2.S; +import static demo.fase17.travel2.TravelAgent2.TravelAgent2.TravelAgent2.A; +import static demo.fase17.travel2.TravelAgent2.TravelAgent2.TravelAgent2.confirm; +import static demo.fase17.travel2.TravelAgent2.TravelAgent2.TravelAgent2.port; + +import java.io.IOException; + +import org.scribble.main.ScribRuntimeException; +import org.scribble.runtime.message.ObjectStreamFormatter; +import org.scribble.runtime.util.Buf; +import org.scribble.runtime.message.ObjectStreamFormatter; +import org.scribble.runtime.net.ScribServerSocket; +import org.scribble.runtime.net.SocketChannelServer; +import org.scribble.runtime.session.ExplicitEndpoint; + +import demo.fase17.travel2.TravelAgent2.TravelAgent2.TravelAgent2; +import demo.fase17.travel2.TravelAgent2.TravelAgent2.statechans.S.TravelAgent2_S_1; +import demo.fase17.travel2.TravelAgent2.TravelAgent2.roles.S; + +public class Travel2S +{ + public void run() throws Exception + { + try (ScribServerSocket ss = new SocketChannelServer(9999); + ScribServerSocket ss2 = new SocketChannelServer(7777)) + { + Buf b = new Buf<>(); + + while (true) + { + TravelAgent2 sess = new TravelAgent2(); + try (ExplicitEndpoint se = new ExplicitEndpoint<>(sess, S, new ObjectStreamFormatter())) + { + new TravelAgent2_S_1(se) + .accept(A, ss) + .send(A, port, 7777) + .accept(C, ss2) // TODO: API gen accept message/payload ("payment") + .send(C, confirm, 4567); + + System.out.println("(S) payment: " + b.val); + } + catch (ScribRuntimeException | IOException e) + { + e.printStackTrace(); + } + } + } + } + + public static void main(String[] args) throws Exception + { + new Travel2S().run(); + } +} diff --git a/scribble-test/src/test/scrib/demo/fase17/travel2/TravelAgent2.scr b/scribble-test/src/test/scrib/demo/fase17/travel2/TravelAgent2.scr new file mode 100644 index 000000000..11803dcd5 --- /dev/null +++ b/scribble-test/src/test/scrib/demo/fase17/travel2/TravelAgent2.scr @@ -0,0 +1,52 @@ +//$ bin/scribblec.sh scribble-test/src/test/scrib/demo/fase17/travel2/TravelAgent2.scr -ip scribble-test/src/test/scrib/ -d scribble-test/src/test/scrib -nocorrelation +//$ javadoc -cp scribble-core/target/classes:scribble-runtime/target/classes:scribble-test/src/test/scrib -subpackages demo.fase17.travel2.TravelAgent2.TravelAgent2 -d scribble-test/javadoc/fase17/travel2 + + +module demo.fase17.travel2.TravelAgent2; + +type "java.lang.Integer" from "rt.jar" as Int; +type "java.lang.String" from "rt.jar" as String; + + +explicit global protocol TravelAgent2(role C, role A, role S) +{ + connect C to A; + do Nego(C, A, S); +} + +aux global protocol Nego(role C, role A, role S) +{ + choice at C + { + query(String) from C to A; + quote(Int) from A to C; + do Nego(C, A, S); + } + or + { + do Pay(C, A, S); + } +} + +aux global protocol Pay(role C, role A, role S) +{ + choice at C + { + accpt() from C to A; + connect A to S; + + port(Int) from S to A; + port(Int) from A to C; // A should forward prev Int to C + payment(String) connect C to S; // C should connect to S at prev Int port // FIXME: connect/accept message + +// port(p:Int) from S to A; +// port(p) from A to C; +// payment(String) connect C to S; @port=p + + confirm(Int) from S to C; + } + or + { + reject() from C to A; + } +} diff --git a/scribble-test/src/test/scrib/demo/highlow/HighLow.scr b/scribble-test/src/test/scrib/demo/highlow/HighLow.scr new file mode 100644 index 000000000..3cab42cda --- /dev/null +++ b/scribble-test/src/test/scrib/demo/highlow/HighLow.scr @@ -0,0 +1,35 @@ +//$ bin/scribblec.sh scribble-test/src/test/scrib/demo/highlow/HighLow.scr -d scribble-test/src/test/scrib/demo -api HighLow A +//$ bin/scribblec.sh scribble-test/src/test/scrib/demo/highlow/HighLow.scr -d scribble-test/src/test/scrib/demo -cbapi HighLow A +//$ javadoc -cp scribble-core/target/classes:scribble-runtime/target/classes:scribble-test/src/test/scrib/demo -subpackages highlow.HighLow.HighLow -d scribble-test/javadoc/highlow + +module highlow.HighLow; + +type "java.lang.Integer" from "runtime.jar" as int; + +global protocol HighLow(role A, role B, role C) { + secret(int) from A to B; //@'0<=n0 && n0<100' + tries(int) from A to B; //@'0x && t>1' + higher() from B to A; + do Aux(A, B, C); //@'B[n, t-1]' + } or { + lower() from B to C; //@'n1' + lower() from B to A; + do Aux(A, B, C); //@'B[n, t-1]' + } or { + lose() from B to C; //@'!(n1=x) && t1=1' + win() from B to A; + } +} + diff --git a/scribble-test/src/test/scrib/demo/highlow/HighLowA.java b/scribble-test/src/test/scrib/demo/highlow/HighLowA.java new file mode 100644 index 000000000..32c7f23e5 --- /dev/null +++ b/scribble-test/src/test/scrib/demo/highlow/HighLowA.java @@ -0,0 +1,68 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ + +package highlow; + +import highlow.HighLow.HighLow.HighLow; +import highlow.HighLow.HighLow.ops.secret; +import highlow.HighLow.HighLow.roles.A; +import highlow.HighLow.HighLow.statechans.A.EndSocket; +import highlow.HighLow.HighLow.statechans.A.HighLow_A_1; +import highlow.HighLow.HighLow.statechans.A.HighLow_A_3; +import highlow.HighLow.HighLow.statechans.A.HighLow_A_3_Cases; +import org.scribble.main.ScribRuntimeException; +import org.scribble.runtime.message.ObjectStreamFormatter; +import org.scribble.runtime.net.SocketChannelEndpoint; +import org.scribble.runtime.session.MPSTEndpoint; + +import java.io.IOException; + +import static highlow.HighLow.HighLow.HighLow.*; + +public class HighLowA { + public void run() throws Exception { + HighLow proto = new HighLow(); + try (MPSTEndpoint se + = new MPSTEndpoint<>(proto, A, new ObjectStreamFormatter())) { + se.request(B, SocketChannelEndpoint::new, "localhost", 8888); + highLow(new HighLow_A_1(se)); + } catch (ScribRuntimeException | IOException | ClassNotFoundException e) { + e.printStackTrace(); + } + } + + private EndSocket highLow(HighLow_A_1 a1) throws Exception { + return aux(a1.send(B, secret, 42).send(B, tries, 5)); + } + + private EndSocket aux(HighLow_A_3 a3) throws Exception { + HighLow_A_3_Cases a3Cases = a3.branch(B); + switch (a3Cases.op) { + case higher: + return aux(a3Cases.receive(higher)); + case lose: + return a3Cases.receive(lose); + case lower: + return aux(a3Cases.receive(lower)); + case win: + return a3Cases.receive(win); + default: + throw new RuntimeException("Won't get in here: " + a3Cases.op); + } + } + + public static void main(String[] args) throws Exception { + new HighLowA().run(); + } +} diff --git a/scribble-test/src/test/scrib/demo/highlow/HighLowB.java b/scribble-test/src/test/scrib/demo/highlow/HighLowB.java new file mode 100644 index 000000000..8580a6551 --- /dev/null +++ b/scribble-test/src/test/scrib/demo/highlow/HighLowB.java @@ -0,0 +1,76 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ + +package highlow; + +import highlow.HighLow.HighLow.HighLow; +import highlow.HighLow.HighLow.roles.B; +import highlow.HighLow.HighLow.statechans.B.EndSocket; +import highlow.HighLow.HighLow.statechans.B.HighLow_B_1; +import highlow.HighLow.HighLow.statechans.B.HighLow_B_3; +import highlow.HighLow.HighLow.statechans.B.HighLow_B_4; +import org.scribble.main.ScribRuntimeException; +import org.scribble.runtime.message.ObjectStreamFormatter; +import org.scribble.runtime.net.ScribServerSocket; +import org.scribble.runtime.net.SocketChannelServer; +import org.scribble.runtime.session.MPSTEndpoint; +import org.scribble.runtime.util.Buf; + +import java.io.IOException; + +import static highlow.HighLow.HighLow.HighLow.*; + +public class HighLowB { + public void run() throws Exception { + try (ScribServerSocket ssA = new SocketChannelServer(8888); + ScribServerSocket ssC = new SocketChannelServer(9999); + ) { + while (true) { + HighLow proto = new HighLow(); + try (MPSTEndpoint se + = new MPSTEndpoint<>(proto, B, new ObjectStreamFormatter())) { + se.accept(ssA, A); + se.accept(ssC, C); + highLow(new HighLow_B_1(se)); + } catch (ScribRuntimeException | IOException | ClassNotFoundException e) { + e.printStackTrace(); + } + } + } + } + + private EndSocket highLow(HighLow_B_1 b1) throws Exception { + Buf s = new Buf<>(); + Buf l = new Buf<>(); + return aux(b1.receive(A, secret, s).receive(A, tries, l), s.val, l.val); + } + + private EndSocket aux(HighLow_B_3 b3, int secret, int tries) throws Exception { + Buf g = new Buf<>(); + HighLow_B_4 b4 = b3.receive(C, guess, g); + if (g.val == secret) { + return b4.send(C, win).send(A, lose); + } else if (tries <= 1) { + return b4.send(C, lose).send(A, win); + } else if (g.val < secret) { + return aux(b4.send(C, higher).send(A, higher), secret, tries - 1); + } else { + return aux(b4.send(C, lower).send(A, lower), secret, tries - 1); + } + } + + public static void main(String[] args) throws Exception { + new HighLowB().run(); + } +} diff --git a/scribble-test/src/test/scrib/demo/highlow/HighLowC.java b/scribble-test/src/test/scrib/demo/highlow/HighLowC.java new file mode 100644 index 000000000..046e5b379 --- /dev/null +++ b/scribble-test/src/test/scrib/demo/highlow/HighLowC.java @@ -0,0 +1,72 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ + +package highlow; + +import highlow.HighLow.HighLow.HighLow; +import highlow.HighLow.HighLow.roles.C; +import highlow.HighLow.HighLow.statechans.C.EndSocket; +import highlow.HighLow.HighLow.statechans.C.HighLow_C_1; +import highlow.HighLow.HighLow.statechans.C.HighLow_C_2_Cases; +import org.scribble.main.ScribRuntimeException; +import org.scribble.runtime.message.ObjectStreamFormatter; +import org.scribble.runtime.net.SocketChannelEndpoint; +import org.scribble.runtime.session.MPSTEndpoint; + +import java.io.IOException; + +import static highlow.HighLow.HighLow.HighLow.*; + +public class HighLowC { + public void run() throws Exception { + HighLow proto = new HighLow(); + + try (MPSTEndpoint se + = new MPSTEndpoint<>(proto, C, new ObjectStreamFormatter())) { + se.request(B, SocketChannelEndpoint::new, "localhost", 9999); + + + highLow(new HighLow_C_1(se)); + } catch (ScribRuntimeException | IOException | ClassNotFoundException e) { + e.printStackTrace(); + } + } + + private EndSocket highLow(HighLow_C_1 c1) throws Exception { + return aux(c1, 50); + } + + private EndSocket aux(HighLow_C_1 c1, int g) throws Exception { + System.out.println("Guessing " + g); + HighLow_C_2_Cases c2Cases = c1.send(B, guess, g).branch(B); + switch (c2Cases.op) { + case higher: + return aux(c2Cases.receive(B, higher), g + 1); + case win: + System.out.println("We win!"); + return c2Cases.receive(B, win); + case lower: + return aux(c2Cases.receive(B, lower), g - 1); + case lose: + System.out.println("We lose..."); + return c2Cases.receive(B, lose); + default: + throw new RuntimeException("Won't get in here: " + c2Cases.op); + } + } + + public static void main(String[] args) throws Exception { + new HighLowC().run(); + } +} diff --git a/scribble-test/src/test/scrib/demo/highlow/cb/MyA.java b/scribble-test/src/test/scrib/demo/highlow/cb/MyA.java new file mode 100644 index 000000000..9dd323dfc --- /dev/null +++ b/scribble-test/src/test/scrib/demo/highlow/cb/MyA.java @@ -0,0 +1,78 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ + +package highlow.cb; + +import highlow.HighLow.HighLow.HighLow; +import highlow.HighLow.HighLow.callbacks.A.HighLow_A; +import highlow.HighLow.HighLow.callbacks.A.HighLow_A_3_Branch; +import highlow.HighLow.HighLow.callbacks.A.states.HighLow_A_1; +import highlow.HighLow.HighLow.callbacks.A.states.HighLow_A_2; +import highlow.HighLow.HighLow.callbacks.A.states.HighLow_A_3; +import highlow.HighLow.HighLow.ops.higher; +import highlow.HighLow.HighLow.ops.lose; +import highlow.HighLow.HighLow.ops.lower; +import highlow.HighLow.HighLow.ops.win; +import highlow.HighLow.HighLow.roles.B; +import org.scribble.main.ScribRuntimeException; +import org.scribble.runtime.message.ObjectStreamFormatter; +import org.scribble.runtime.net.SocketChannelEndpoint; + +import java.io.IOException; +import java.util.concurrent.Future; + +import static highlow.HighLow.HighLow.HighLow.A; +import static highlow.HighLow.HighLow.HighLow.B; + +public class MyA { + public void run() throws Exception { + HighLow proto = new HighLow(); + + try (HighLow_A c = new HighLow_A<>(proto, A, new ObjectStreamFormatter(), null)) { + c.icallback(HighLow_A_1.id, (data) -> new HighLow_A_1.B.secret(42)); + c.icallback(HighLow_A_2.id, (data) -> new HighLow_A_2.B.tries(5)); + c.icallback(HighLow_A_3.id, new MyHandlerA()); + + c.request(B, SocketChannelEndpoint::new, "localhost", 8888); + Future f = c.run(); + f.get(); + } catch (ScribRuntimeException | IOException e) { + e.printStackTrace(); + } + } + + public static void main(String[] args) throws Exception { + new MyA().run(); + } +} + +class MyHandlerA extends HighLow_A_3_Branch { + @Override + public void receive(Void data, highlow.HighLow.HighLow.roles.B peer, higher op) { + } + + @Override + public void receive(Void data, B peer, lose op) { + System.out.println("We lose..."); + } + + @Override + public void receive(Void data, B peer, lower op) { + } + + @Override + public void receive(Void data, B peer, win op) { + System.out.println("We win!"); + } +} diff --git a/scribble-test/src/test/scrib/demo/highlow/cb/MyB.java b/scribble-test/src/test/scrib/demo/highlow/cb/MyB.java new file mode 100644 index 000000000..61d469e24 --- /dev/null +++ b/scribble-test/src/test/scrib/demo/highlow/cb/MyB.java @@ -0,0 +1,110 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ + +package highlow.cb; + +import highlow.HighLow.HighLow.HighLow; +import highlow.HighLow.HighLow.callbacks.B.HighLow_B; +import highlow.HighLow.HighLow.callbacks.B.HighLow_B_1_Branch; +import highlow.HighLow.HighLow.callbacks.B.HighLow_B_2_Branch; +import highlow.HighLow.HighLow.callbacks.B.HighLow_B_3_Branch; +import highlow.HighLow.HighLow.callbacks.B.states.*; +import highlow.HighLow.HighLow.ops.guess; +import highlow.HighLow.HighLow.ops.secret; +import highlow.HighLow.HighLow.ops.tries; +import highlow.HighLow.HighLow.roles.A; +import highlow.HighLow.HighLow.roles.C; +import org.scribble.main.ScribRuntimeException; +import org.scribble.runtime.message.ObjectStreamFormatter; +import org.scribble.runtime.net.ScribServerSocket; +import org.scribble.runtime.net.SocketChannelServer; + +import java.io.IOException; +import java.util.concurrent.Future; + +import static highlow.HighLow.HighLow.HighLow.A; +import static highlow.HighLow.HighLow.HighLow.B; +import static highlow.HighLow.HighLow.HighLow.C; + +public class MyB { + public void run() throws Exception { + + try (ScribServerSocket ssA = new SocketChannelServer(8888); + ScribServerSocket ssC = new SocketChannelServer(9999) + ) { + while (true) { + HighLow proto = new HighLow(); + try (HighLow_B b = new HighLow_B<>(proto, B, new ObjectStreamFormatter(), new MyStateB())) { + b.icallback(HighLow_B_1.id, new MyHandlerB1()); + b.icallback(HighLow_B_2.id, new MyHandlerB2()); + b.icallback(HighLow_B_3.id, new MyHandlerB3()); + b.icallback(HighLow_B_4.id, (data) -> { + if (data.secret == data.guess) { + return new HighLow_B_4.C.win(); + } else if (data.tries == 0) { + return new HighLow_B_4.C.lose(); + } else { + data.tries--; + return (data.secret > data.guess) + ? new HighLow_B_4.C.higher() + : new HighLow_B_4.C.lower(); + } + }); + b.icallback(HighLow_B_5.id, (data) -> new HighLow_B_5.A.lose()); + b.icallback(HighLow_B_6.id, (data) -> new HighLow_B_6.A.higher()); + b.icallback(HighLow_B_7.id, (data) -> new HighLow_B_7.A.lower()); + b.icallback(HighLow_B_8.id, (data) -> new HighLow_B_8.A.win()); + + b.accept(ssA, A); + b.accept(ssC, C); + Future f = b.run(); + f.get(); + } catch (ScribRuntimeException | IOException e) { + e.printStackTrace(); + } + } + } + } + + public static void main(String[] args) throws Exception { + new MyB().run(); + } +} + +class MyStateB { + public int secret; + public int tries; + public int guess; +} + +class MyHandlerB1 extends HighLow_B_1_Branch { + @Override + public void receive(MyStateB data, A peer, secret op, Integer arg1) { + data.secret = arg1; + } +} + +class MyHandlerB2 extends HighLow_B_2_Branch { + @Override + public void receive(MyStateB data, A peer, tries op, Integer arg1) { + data.tries = arg1; + } +} + +class MyHandlerB3 extends HighLow_B_3_Branch { + @Override + public void receive(MyStateB data, C peer, guess op, Integer arg1) { + data.guess = arg1; + } +} diff --git a/scribble-test/src/test/scrib/demo/highlow/cb/MyC.java b/scribble-test/src/test/scrib/demo/highlow/cb/MyC.java new file mode 100644 index 000000000..ac412ff17 --- /dev/null +++ b/scribble-test/src/test/scrib/demo/highlow/cb/MyC.java @@ -0,0 +1,85 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ + +package highlow.cb; + +import highlow.HighLow.HighLow.HighLow; +import highlow.HighLow.HighLow.callbacks.C.HighLow_C; +import highlow.HighLow.HighLow.callbacks.C.HighLow_C_2_Branch; +import highlow.HighLow.HighLow.callbacks.C.states.HighLow_C_1; +import highlow.HighLow.HighLow.callbacks.C.states.HighLow_C_2; +import highlow.HighLow.HighLow.ops.higher; +import highlow.HighLow.HighLow.ops.lose; +import highlow.HighLow.HighLow.ops.lower; +import highlow.HighLow.HighLow.ops.win; +import highlow.HighLow.HighLow.roles.B; +import org.scribble.main.ScribRuntimeException; +import org.scribble.runtime.message.ObjectStreamFormatter; +import org.scribble.runtime.net.SocketChannelEndpoint; + +import java.io.IOException; +import java.util.concurrent.Future; + +import static highlow.HighLow.HighLow.HighLow.B; +import static highlow.HighLow.HighLow.HighLow.C; + +public class MyC { + public void run() throws Exception { + HighLow proto = new HighLow(); + + try (HighLow_C c = new HighLow_C<>(proto, C, new ObjectStreamFormatter(), new MyStateC())) { + c.icallback(HighLow_C_1.id, (data) -> { + System.out.println("Guessing " + data.guess); + return new HighLow_C_1.B.guess(data.guess); + }); + c.icallback(HighLow_C_2.id, new MyHandlerC()); + + c.request(B, SocketChannelEndpoint::new, "localhost", 9999); + Future f = c.run(); + f.get(); + } catch (ScribRuntimeException | IOException e) { + e.printStackTrace(); + } + } + + public static void main(String[] args) throws Exception { + new MyC().run(); + } +} + +class MyStateC { + public int guess = 50; +} + +class MyHandlerC extends HighLow_C_2_Branch { + @Override + public void receive(MyStateC data, B peer, higher op) { + data.guess++; + } + + @Override + public void receive(MyStateC data, B peer, lose op) { + System.out.println("We lose..."); + } + + @Override + public void receive(MyStateC data, B peer, lower op) { + data.guess--; + } + + @Override + public void receive(MyStateC data, B peer, win op) { + System.out.println("We win!"); + } +} diff --git a/scribble-test/src/test/scrib/demo/supplierinfo/SupplierInfoExplicit.scr b/scribble-test/src/test/scrib/demo/supplierinfo/SupplierInfoExplicit.scr new file mode 100644 index 000000000..f431eb65f --- /dev/null +++ b/scribble-test/src/test/scrib/demo/supplierinfo/SupplierInfoExplicit.scr @@ -0,0 +1,147 @@ +//$ bin/scribblec.sh scribble-core/src/test/scrib/demo/supplierinfo/SupplierInfoExplicit.scr -fsm InfoAuth Client + + +module src.SupplierInfoExplicit; + + +type "UserName" from "AUTH.xsd" as username; +type "Password" from "AUTH.xsd" as password; +type "UUID" from "AUTH.xsd" as uuid; +type "/retailhub/supplierdetails" from "Retailer.xsd" as supplierdetails; +type "/retailhub/contractdetails" from "Retailer.xsd" as contractdetails; + +type "..." from "...xsd" as usercontext; +type "..." from "...xsd" as filters; + + +// Needs -fair -- cf. SupplierInfoNoFair +explicit global protocol InfoAuth +( + role Client, + role LoginSvc, + role AuthSvc, + role FilterSvc, + role SupplierSvc, + role ContractSvc +) +{ + connect Client to LoginSvc; + login(username, password) from Client to LoginSvc; + choice at LoginSvc + { + //loginsuccess() from LoginSvc to Client; // Not an error if the following line commented (and fairness assumed) + loginfailure() from LoginSvc to Client; + /*connect Client to AuthSvc; + getsuppliers(uuid) from Client to AuthSvc; // Error: orphans*/ + disconnect Client and LoginSvc; + } + or + { + loginsuccess() from LoginSvc to Client; + //disconnect Client and LoginSvc; + connect Client to AuthSvc; + connect AuthSvc to FilterSvc; + connect AuthSvc to SupplierSvc; + connect AuthSvc to ContractSvc; + do Main(Client, AuthSvc, FilterSvc, SupplierSvc, ContractSvc); + } +} + + +aux global protocol Main +( + role Client, + role AuthSvc, + role FilterSvc, + role SupplierSvc, + role ContractSvc +) +{ + choice at Client + { + // GET SUPPLIER INFO + getsuppliers(uuid) from Client to AuthSvc; + //1() from AuthSvc to ContractSvc; + do SuppInfo(Client, AuthSvc, FilterSvc, SupplierSvc); + } + or + { + // GET CONTRACT INFO + getcontracts() from Client to AuthSvc; + //2() from AuthSvc to SupplierSvc; + do ContractInfo(Client, AuthSvc, FilterSvc, ContractSvc); + //do ContractInfo(Client, AuthSvc, FilterSvc, SupplierSvc); // Error + } + do Main(Client, AuthSvc, FilterSvc, SupplierSvc, ContractSvc); +} + + +aux global protocol SuppInfo +( + role Client, + role AuthSvc, + role FilterSvc, + role SupplierSvc +) +{ + choice at AuthSvc + { + // DENIED + deny() from AuthSvc to Client; + } + or + { + // PREPARE FILTERED SUPPLIER INFO FOR Client + getsuppliers() from AuthSvc to SupplierSvc; + suppliers() from SupplierSvc to AuthSvc; + do FilterInfo + + (AuthSvc, FilterSvc); + suppliers() from AuthSvc to Client; + } +} + + +aux global protocol ContractInfo +( + role Client, + role AuthSvc, + role FilterSvc, + role ContractSvc +) +{ + choice at AuthSvc + { + // DENIED + deny() from AuthSvc to Client; + } + or + { + // PREPARE FILTERED SUPPLIER INFO FOR Client + getcontracts() from AuthSvc to ContractSvc; + contracts() from ContractSvc to AuthSvc; + do FilterInfo + + // // OK (merge) + // // Error + (AuthSvc, FilterSvc); + contracts() from AuthSvc to Client; + } +} + + +//aux global protocol FilterInfo( // Bad non-det. payload +aux global protocol FilterInfo +< + sig Query +> +( + role AuthSvc, + role FilterSvc +) +{ + //filter(usercontext, filters, details) from AuthSvc to FilterSvc; + Query from AuthSvc to FilterSvc; + filtered() from FilterSvc to AuthSvc; +} + diff --git a/scribble-test/src/test/scrib/demo/supplierinfo/SupplierInfoNoFair.scr b/scribble-test/src/test/scrib/demo/supplierinfo/SupplierInfoNoFair.scr new file mode 100644 index 000000000..ea093745d --- /dev/null +++ b/scribble-test/src/test/scrib/demo/supplierinfo/SupplierInfoNoFair.scr @@ -0,0 +1,141 @@ +//$ bin/scribblec.sh scribble-core/src/test/scrib/demo/supplierinfo/SupplierInfoNoFair.scr -fsm InfoAuth Client + + +module src.SupplierInfoNoFair; + + +data "UserName" from "AUTH.xsd" as username; +data "Password" from "AUTH.xsd" as password; +data "UUID" from "AUTH.xsd" as uuid; +data "/retailhub/supplierdetails" from "Retailer.xsd" as supplierdetails; +data "/retailhub/contractdetails" from "Retailer.xsd" as contractdetails; + +data "..." from "...xsd" as usercontext; +data "..." from "...xsd" as filters; + + +explicit global protocol InfoAuth +( + role Client, + role LoginSvc, + role AuthSvc, + role FilterSvc, + role SupplierSvc, + role ContractSvc +) +{ + connect Client to LoginSvc; + login(username, password) from Client to LoginSvc; + choice at LoginSvc + { + loginfailure() from LoginSvc to Client; + //disconnect Client and LoginSvc; // Increases state space somewhat + } + or + { + loginsuccess() from LoginSvc to Client; + //disconnect Client and LoginSvc; + connect Client to AuthSvc; + do Main(Client, AuthSvc, FilterSvc, SupplierSvc, ContractSvc); + } +} + + +aux global protocol Main +( + role Client, + role AuthSvc, + role FilterSvc, + role SupplierSvc, + role ContractSvc +) +{ + choice at Client + { + // GET SUPPLIER INFO + getsuppliers(uuid) from Client to AuthSvc; + do SuppInfo(Client, AuthSvc, FilterSvc, SupplierSvc); + } + or + { + // GET CONTRACT INFO + getcontracts() from Client to AuthSvc; + do ContractInfo(Client, AuthSvc, FilterSvc, ContractSvc); + } + do Main(Client, AuthSvc, FilterSvc, SupplierSvc, ContractSvc); +} + + +aux global protocol SuppInfo +( + role Client, + role AuthSvc, + role FilterSvc, + role SupplierSvc +) +{ + choice at AuthSvc + { + // DENIED + deny() from AuthSvc to Client; + } + or + { + connect AuthSvc to SupplierSvc; + // PREPARE FILTERED SUPPLIER INFO FOR Client + getsuppliers() from AuthSvc to SupplierSvc; + suppliers() from SupplierSvc to AuthSvc; + //disconnect AuthSvc and SupplierSvc; + do FilterInfo + + // + (AuthSvc, FilterSvc); + disconnect AuthSvc and SupplierSvc; + suppliers() from AuthSvc to Client; + } +} + + +aux global protocol ContractInfo +( + role Client, + role AuthSvc, + role FilterSvc, + role ContractSvc +) +{ + choice at AuthSvc + { + // DENIED + deny() from AuthSvc to Client; + } + or + { + connect AuthSvc to ContractSvc; + // PREPARE FILTERED SUPPLIER INFO FOR Client + getcontracts() from AuthSvc to ContractSvc; + contracts() from ContractSvc to AuthSvc; + //disconnect AuthSvc and ContractSvc; + do FilterInfo + + (AuthSvc, FilterSvc); + disconnect AuthSvc and ContractSvc; + contracts() from AuthSvc to Client; + } +} + + +aux global protocol FilterInfo +< + sig Query +> +( + role AuthSvc, + role FilterSvc +) +{ + Query connect AuthSvc to FilterSvc; + filtered() from FilterSvc to AuthSvc; + disconnect AuthSvc and FilterSvc; +} + diff --git a/scribble-test/src/test/scrib/demo/supplierinfo/old/SupplierInfo.scr b/scribble-test/src/test/scrib/demo/supplierinfo/old/SupplierInfo.scr new file mode 100644 index 000000000..c75888fde --- /dev/null +++ b/scribble-test/src/test/scrib/demo/supplierinfo/old/SupplierInfo.scr @@ -0,0 +1,76 @@ +module src.SupplierInfo; + +type "UserName" from "AUTH.xsd" as username; +type "Password" from "AUTH.xsd" as password; +type "UUID" from "AUTH.xsd" as uuid; +type "/retailhub/supplierdetails" from "Retailer.xsd" as supplierdetails; +type "/retailhub/contractdetails" from "Retailer.xsd" as contractdetails; + +type "UserContext" from "AUTH.xsd" as usercontext; +type "FilterSet" from "AUTH.xsd" as filters; + + +explicit global protocol Partners( + role LOGINsvc, + role REQuestor, + role AUTHsvc, + //role usersvc, + role FILTERsvc, + role SUPPLIERsvc, + role CONTRACTsvc) +{ + connect REQuestor to LOGINsvc; + + login(username, password) from REQuestor to LOGINsvc; + choice at LOGINsvc + { + loginsuccess() from LOGINsvc to REQuestor; + //loginfailure() from LOGINsvc to REQuestor; + } or { + loginsuccess() from LOGINsvc to REQuestor; + + connect REQuestor to AUTHsvc; + connect AUTHsvc to SUPPLIERsvc; + connect AUTHsvc to CONTRACTsvc; + connect AUTHsvc to FILTERsvc; + + rec MAIN + { + choice at REQuestor + { + // GET SUPPLIER INFO + getsuppliers(uuid) from REQuestor to AUTHsvc; + choice at AUTHsvc + { + // DENIED + deny() from AUTHsvc to REQuestor; + } or { + // PREPARE FILTERED SUPPLIER INFO FOR REQuestor + getsuppliers() from AUTHsvc to SUPPLIERsvc; + suppliers() from SUPPLIERsvc to AUTHsvc; + filterSuppliers(usercontext, filters, supplierdetails) from AUTHsvc to FILTERsvc; + filtered() from FILTERsvc to AUTHsvc; + suppliers() from AUTHsvc to REQuestor; + } + continue MAIN; + } or { + // GET CONTRACT INFO + getcontracts() from REQuestor to AUTHsvc; + choice at AUTHsvc + { + // DENIED + deny() from AUTHsvc to REQuestor; + } or { + // PREPARE FILTERED SUPPLIER INFO FOR REQuestor + getcontracts() from AUTHsvc to CONTRACTsvc; + contracts() from CONTRACTsvc to AUTHsvc; + filterContracts(usercontext, filters, contractdetails) from AUTHsvc to FILTERsvc; + filtered() from FILTERsvc to AUTHsvc; + contracts() from AUTHsvc to REQuestor; + } + continue MAIN; + } + } + } +} + diff --git a/scribble-test/src/test/scrib/demo/supplierinfo/old/SupplierInfoBasic.scr b/scribble-test/src/test/scrib/demo/supplierinfo/old/SupplierInfoBasic.scr new file mode 100644 index 000000000..0cbb57bd4 --- /dev/null +++ b/scribble-test/src/test/scrib/demo/supplierinfo/old/SupplierInfoBasic.scr @@ -0,0 +1,100 @@ +module src.SupplierInfoBasic; + +type "UserName" from "AUTH.xsd" as username; +type "Password" from "AUTH.xsd" as password; +type "UUID" from "AUTH.xsd" as uuid; +type "/retailhub/supplierdetails" from "Retailer.xsd" as supplierdetails; +type "/retailhub/contractdetails" from "Retailer.xsd" as contractdetails; + +type "..." from "...xsd" as usercontext; +type "..." from "...xsd" as filters; + + +global protocol PartnershipSupplier( + role loginsvc, + role requestor, + role authorisersvc, + role filtersvc, + role suppliersvc, + role contractsvc) +{ + login(username, password) from requestor to loginsvc; + choice at loginsvc + { + //loginsuccess() from loginsvc to requestor // Error if below is commented + loginfailure() from loginsvc to requestor; + + //getsuppliers(uuid) from requestor to authorisersvc; // Error + + 0() from requestor to authorisersvc; + 0() from authorisersvc to filtersvc; + 0() from authorisersvc to suppliersvc; + 0() from authorisersvc to contractsvc; + } + or + { + loginsuccess() from loginsvc to requestor; + rec mainBlock + { + choice at requestor + { + // GET SUPPLIER INFO + getsuppliers(uuid) from requestor to authorisersvc; + + 1() from authorisersvc to contractsvc; // Cheaper here than below + + choice at authorisersvc + { + // DENIED + deny() from authorisersvc to requestor; + + 1() from authorisersvc to suppliersvc; + 1() from authorisersvc to filtersvc; + } + or + { + // PREPARE FILTERED SUPPLIER INFO FOR REQUESTOR + getsuppliers() from authorisersvc to suppliersvc; + suppliers() from suppliersvc to authorisersvc; + + filterSuppliers(usercontext, filters, supplierdetails) from authorisersvc to filtersvc; + filtered() from filtersvc to authorisersvc; + suppliers() from authorisersvc to requestor; + } + + //1() from authorisersvc to contractsvc; + continue mainBlock; + } + or + { + // GET CONTRACT INFO + getcontracts() from requestor to authorisersvc; + + 2() from authorisersvc to suppliersvc; + + choice at authorisersvc + { + // DENIED + deny() from authorisersvc to requestor; + + 2() from authorisersvc to contractsvc; + 2() from authorisersvc to filtersvc; + } + or + { + // PREPARE FILTERED SUPPLIER INFO FOR REQUESTOR + getcontracts() from authorisersvc to contractsvc; + contracts() from contractsvc to authorisersvc; + + filterContracts(usercontext, filters, contractdetails) from authorisersvc to filtersvc; + filtered() from filtersvc to authorisersvc; + contracts() from authorisersvc to requestor; + } + + //2() from authorisersvc to suppliersvc; + continue mainBlock; + } + } + } +} + diff --git a/scribble-test/src/test/scrib/demo/supplierinfo/old/SupplierInfoDemo.scr b/scribble-test/src/test/scrib/demo/supplierinfo/old/SupplierInfoDemo.scr new file mode 100644 index 000000000..aa6ee3675 --- /dev/null +++ b/scribble-test/src/test/scrib/demo/supplierinfo/old/SupplierInfoDemo.scr @@ -0,0 +1,68 @@ +module src.SupplierInfoDemo; + +type "UserName" from "AUTH.xsd" as username; +type "Password" from "AUTH.xsd" as password; +type "UUID" from "AUTH.xsd" as uuid; +type "/retailhub/supplierdetails" from "Retailer.xsd" as supplierdetails; +type "/retailhub/contractdetails" from "Retailer.xsd" as contractdetails; + +//type "UserContext" from "AUTH.xsd" as usercontext; +//type "FilterSet" from "AUTH.xsd" as filters; + + +global protocol Partners( + role LOGINsvc, + role REQUESTOR, + role AUTHsvc, + role usersvc, + role FILTERsvc, + role SUPPLIERsvc, + role CONTRACTsvc) +{ + login(username, password) from REQUESTOR to LOGINsvc; + choice at LOGINsvc + { + loginfailure() from LOGINsvc to REQUESTOR; + } or { + loginsuccess() from LOGINsvc to REQUESTOR; + + rec MAIN + { + choice at REQUESTOR + { + // GET SUPPLIER INFO + getsuppliers(uuid) from REQUESTOR to AUTHsvc; + choice at AUTHsvc + { + // DENIED + deny() from AUTHsvc to REQUESTOR; + } or { + // PREPARE FILTERED SUPPLIER INFO FOR REQUESTOR + getsuppliers() from AUTHsvc to SUPPLIERsvc; + suppliers() from SUPPLIERsvc to AUTHsvc; + filterSuppliers(usercontext, filters, supplierdetails) from AUTHsvc to FILTERsvc; + filtered() from FILTERsvc to AUTHsvc; + suppliers() from AUTHsvc to REQUESTOR; + } + continue MAIN; + } or { + // GET CONTRACT INFO + getcontracts() from REQUESTOR to AUTHsvc; + choice at authoriser + { + // DENIED + deny() from AUTHsvc to REQUESTOR; + } or { + // PREPARE FILTERED SUPPLIER INFO FOR REQUESTOR + getcontracts() from AUTHsvc to CONTRACTsvc; + contracts() from CONTRACTsvc to AUTHsvc; + filterContracts(usercontext, filters, contractdetails) from AUTHsvc to FILTERsvc; + filtered() from FILTERsvc to AUTHsvc; + contracts() from AUTHsvc to REQUESTOR; + } + continue MAIN; + } + } + } +} + diff --git a/scribble-test/src/test/scrib/demo/supplierinfo/old/SupplierInfoExper.scr b/scribble-test/src/test/scrib/demo/supplierinfo/old/SupplierInfoExper.scr new file mode 100644 index 000000000..a7a9863ea --- /dev/null +++ b/scribble-test/src/test/scrib/demo/supplierinfo/old/SupplierInfoExper.scr @@ -0,0 +1,86 @@ +module src.SupplierInfoExper; + +type "UserName" from "AUTH.xsd" as username; +type "Password" from "AUTH.xsd" as password; +type "UUID" from "AUTH.xsd" as uuid; +type "/retailhub/supplierdetails" from "Retailer.xsd" as supplierdetails; +type "/retailhub/contractdetails" from "Retailer.xsd" as contractdetails; + +type "..." from "...xsd" as usercontext; +type "..." from "...xsd" as filters; + +type "java.lang.Integer" from "rt.jar" as int; + + +global protocol PartnershipSupplier( + role loginsvc, + role requestor) +{ + login(username, password) from requestor to loginsvc; + choice at loginsvc + { + loginfailure() from loginsvc to requestor; + } + or + { + loginsuccess() from loginsvc to requestor; + do Main(loginsvc, requestor); + } +} + +global protocol Main( + role loginsvc, + role requestor) +{ + loginsvc connects( // connect/disconnect now done as explicit statements + role authorisersvc, + role filtersvc, + role suppliersvc, + role contractsvc) + { + rec mainBlock + { + choice at requestor + { + // GET SUPPLIER INFO + getsuppliers(uuid) from requestor to authorisersvc; + choice at authorisersvc + { + // DENIED + deny() from authorisersvc to requestor, suppliersvc; + } + or + { + // PREPARE FILTERED SUPPLIER INFO FOR REQUESTOR + getsuppliers() from authorisersvc to suppliersvc; + suppliers() from suppliersvc to authorisersvc; + filter1(usercontext, filters, supplierdetails) from authorisersvc to filtersvc; + filtered1() from filtersvc to authorisersvc; + suppliers() from authorisersvc to requestor; + } + } + or + { + // GET CONTRACT INFO + getcontracts() from requestor to authorisersvc; + //choice at authoriser + choice at authorisersvc + { + // DENIED + deny() from authorisersvc to requestor, contractsvc; + } + or + { + // PREPARE FILTERED SUPPLIER INFO FOR REQUESTOR + getcontracts() from authorisersvc to contractsvc; + suppliers() from contractsvc to authorisersvc; + filter2(usercontext, filters, supplierdetails) from authorisersvc to filtersvc; + filtered2() from filtersvc to authorisersvc; + contracts() from authorisersvc to requestor; + } + } + continue mainBlock; + } + } +} + diff --git a/scribble-test/src/test/scrib/demo/supplierinfo/old/SupplierInfoNoFairBeta.scr b/scribble-test/src/test/scrib/demo/supplierinfo/old/SupplierInfoNoFairBeta.scr new file mode 100644 index 000000000..b2adfda38 --- /dev/null +++ b/scribble-test/src/test/scrib/demo/supplierinfo/old/SupplierInfoNoFairBeta.scr @@ -0,0 +1,140 @@ +module src.SupplierInfoNoFairBeta; + + +type "UserName" from "AUTH.xsd" as username; +type "Password" from "AUTH.xsd" as password; +type "UUID" from "AUTH.xsd" as uuid; +type "/retailhub/supplierdetails" from "Retailer.xsd" as supplierdetails; +type "/retailhub/contractdetails" from "Retailer.xsd" as contractdetails; + +type "..." from "...xsd" as usercontext; +type "..." from "...xsd" as filters; + + +explicit global protocol PartnershipSupplier +( + role loginsvc, + role requestor, + role authorisersvc, + role filtersvc, + role suppliersvc, + role contractsvc +) +{ + connect requestor to loginsvc; + login(username, password) from requestor to loginsvc; + choice at loginsvc + { + loginfailure() from loginsvc to requestor; + disconnect requestor and loginsvc; + } + or + { + loginsuccess() from loginsvc to requestor; + connect requestor to authorisersvc; + connect authorisersvc to filtersvc; + do Main(requestor, authorisersvc, filtersvc, suppliersvc, contractsvc); + } +} + + +aux global protocol Main +( + role requestor, + role authorisersvc, + role filtersvc, + role suppliersvc, + role contractsvc +) +{ + choice at requestor + { + // GET SUPPLIER INFO + getsuppliers(uuid) from requestor to authorisersvc; + do SuppInfo(requestor, authorisersvc, filtersvc, suppliersvc); + } + or + { + // GET CONTRACT INFO + getcontracts() from requestor to authorisersvc; + do ContractInfo(requestor, authorisersvc, filtersvc, contractsvc); + } + do Main(requestor, authorisersvc, filtersvc, suppliersvc, contractsvc); +} + + +aux global protocol SuppInfo +( + role requestor, + role authorisersvc, + role filtersvc, + role suppliersvc +) +{ + choice at authorisersvc + { + // DENIED + deny() from authorisersvc to requestor; + + 0() from authorisersvc to filtersvc; // FIXME: need accept+message branching, to factor out non-fair filter subproto + } + or + { + connect authorisersvc to suppliersvc; + // PREPARE FILTERED SUPPLIER INFO FOR REQUESTOR + getsuppliers() from authorisersvc to suppliersvc; + suppliers() from suppliersvc to authorisersvc; + do FilterInfo + + (authorisersvc, filtersvc); + disconnect authorisersvc and suppliersvc; + suppliers() from authorisersvc to requestor; + } +} + + +aux global protocol ContractInfo +( + role requestor, + role authorisersvc, + role filtersvc, + role contractsvc +) +{ + choice at authorisersvc + { + // DENIED + deny() from authorisersvc to requestor; + + 0() from authorisersvc to filtersvc; + } + or + { + connect authorisersvc to contractsvc; + // PREPARE FILTERED SUPPLIER INFO FOR REQUESTOR + getcontracts() from authorisersvc to contractsvc; + contracts() from contractsvc to authorisersvc; + do FilterInfo + + (authorisersvc, filtersvc); + disconnect authorisersvc and contractsvc; + contracts() from authorisersvc to requestor; + } +} + + +//aux global protocol FilterInfo( // Bad non-det. payload +aux global protocol FilterInfo +< + sig Query +> +( + role authorisersvc, + role filtersvc +) +{ + //filter(usercontext, filters, details) from authorisersvc to filtersvc; + Query from authorisersvc to filtersvc; + filtered() from filtersvc to authorisersvc; +} + diff --git a/scribble-test/src/test/scrib/demo/supplierinfo/old/SupplierInfoOrig.scr b/scribble-test/src/test/scrib/demo/supplierinfo/old/SupplierInfoOrig.scr new file mode 100644 index 000000000..91d44e26e --- /dev/null +++ b/scribble-test/src/test/scrib/demo/supplierinfo/old/SupplierInfoOrig.scr @@ -0,0 +1,59 @@ +module src.SupplierInfoOrig; + +type "UserName" from "AUTH.xsd" as username; +type "Password" from "AUTH.xsd" as password; +type "UUID" from "AUTH.xsd" as uuid; +type "/retailhub/supplierdetails" from "Retailer.xsd" as supplierdetails; +type "/retailhub/contractdetails" from "Retailer.xsd" as contractdetails; + +type "java.lang.Integer" from "rt.jar" as int; + + +global protocol PartnershipSupplier( role loginsvc, + role requestor, + role authorisersvc, + role usersvc, + role filtersvc, + role suppliersvc, + role contractsvc) +{ + login(username, password) from requestor to loginsvc; + choice at loginsvc + { + loginfailure() from loginsvc to requestor; + } or { + loginsuccess() from loginsvc to requestor; + rec mainBlock + { + choice at requestor + { // GET SUPPLIER INFO + getsuppliers(uuid) from requestor to authorisersvc; + choice at authorisersvc + { // DENIED + deny() from authorisersvc to requestor; + } or { // PREPARE FILTERED SUPPLIER INFO FOR REQUESTOR + getsuppliers() from authorisersvc to suppliersvc; + suppliers() from suppliersvc to authorisersvc; + filter(usercontext, filters, supplierdetails) from authorisersvc to filtersvc; + filtered() from filtersvc to authorisersvc; + suppliers() from authorisersvc to requestor; + } + continue mainBlock; + } or { // GET CONTRACT INFO + getcontracts() from requestor to authorisersvc; + choice at authoriser + { // DENIED + deny() from authorisersvc to requestor; + } or {// PREPARE FILTERED SUPPLIER INFO FOR REQUESTOR + getcontracts() from authorisersvc to contractsvc; + suppliers() from contractsvc to authorisersvc; + filter(usercontext, filters, contractdetails) from authorisersvc to filtersvc; + filtered() from filtersvc to authorisersvc; + contracts() from authorisersvc to requestor; + } + continue mainBlock; + } + } + } +} + diff --git a/scribble-test/src/test/scrib/demo/supplierinfo/old/SupplierInfoSubprot.scr b/scribble-test/src/test/scrib/demo/supplierinfo/old/SupplierInfoSubprot.scr new file mode 100644 index 000000000..46a567f32 --- /dev/null +++ b/scribble-test/src/test/scrib/demo/supplierinfo/old/SupplierInfoSubprot.scr @@ -0,0 +1,137 @@ +module src.SupplierInfoSubprot; + +type "UserName" from "AUTH.xsd" as username; +type "Password" from "AUTH.xsd" as password; +type "UUID" from "AUTH.xsd" as uuid; +type "/retailhub/supplierdetails" from "Retailer.xsd" as supplierdetails; +type "/retailhub/contractdetails" from "Retailer.xsd" as contractdetails; + +type "..." from "...xsd" as usercontext; +type "..." from "...xsd" as filters; + + +global protocol PartnershipSupplier( + role loginsvc, + role requestor, + role authorisersvc, + role filtersvc, + role suppliersvc, + role contractsvc) +{ + login(username, password) from requestor to loginsvc; + choice at loginsvc + { + //loginsuccess() from loginsvc to requestor; // Only an error if the following line remains uncommented + loginfailure() from loginsvc to requestor; + //getsuppliers(uuid) from requestor to authorisersvc; + 0() from requestor to authorisersvc; + 0() from authorisersvc to filtersvc; + 0() from authorisersvc to suppliersvc; + 0() from authorisersvc to contractsvc; + } + or + { + loginsuccess() from loginsvc to requestor; + do Main(requestor, authorisersvc, filtersvc, suppliersvc, contractsvc); + } +} + +aux global protocol Main( + role requestor, + role authorisersvc, + role filtersvc, + role suppliersvc, + role contractsvc) +{ + choice at requestor + { + // GET SUPPLIER INFO + getsuppliers(uuid) from requestor to authorisersvc; + //1() from authorisersvc to contractsvc; // FIXME: big state explosion? + //do SuppInfo(requestor, authorisersvc, filtersvc, suppliersvc); // FIXME: non-WF subprotocol + choice at authorisersvc + { + // DENIED + deny() from authorisersvc to requestor; + } + or + { + // PREPARE FILTERED SUPPLIER INFO FOR REQUESTOR + getsuppliers() from authorisersvc to suppliersvc; + do FilterInfo + + (authorisersvc, filtersvc); + suppliers() from suppliersvc to authorisersvc; + suppliers() from authorisersvc to requestor; + } + } + or + { + // GET CONTRACT INFO + getcontracts() from requestor to authorisersvc; + //2() from authorisersvc to suppliersvc; + choice at authorisersvc + { + // DENIED + deny() from authorisersvc to requestor; + } + or + { + // PREPARE FILTERED SUPPLIER INFO FOR REQUESTOR + getcontracts() from authorisersvc to contractsvc; + suppliers() from contractsvc to authorisersvc; + do FilterInfo + + // // OK (merge) + // // Error + (authorisersvc, filtersvc); + contracts() from authorisersvc to requestor; + } + } + + do Main(requestor, authorisersvc, filtersvc, suppliersvc, contractsvc); +} + + +//aux global protocol FilterInfo( // Bad non-det. payload +aux global protocol FilterInfo +< + sig Query +> +( + role authorisersvc, + role filtersvc +) +{ + //filter(usercontext, filters, details) from authorisersvc to filtersvc; + Query from authorisersvc to filtersvc; + filtered() from filtersvc to authorisersvc; +} + + +// FIXME: don't want WF validation on this (sub)protocol by itself +/* +global protocol SuppInfo( + role requestor, + role authorisersvc, + role filtersvc, + role suppliersvc) +{ + choice at authorisersvc + { + // DENIED + deny() from authorisersvc to requestor; + } + or + { + // PREPARE FILTERED SUPPLIER INFO FOR REQUESTOR + getsuppliers() from authorisersvc to suppliersvc; + suppliers() from suppliersvc to authorisersvc; + + filter(usercontext, filters, supplierdetails) from authorisersvc to filtersvc; + filtered() from filtersvc to authorisersvc; + suppliers() from authorisersvc to requestor; + } +} +//*/ + diff --git a/scribble-test/src/test/scrib/exercise/calculator/Client.java b/scribble-test/src/test/scrib/exercise/calculator/Client.java new file mode 100644 index 000000000..c9e376751 --- /dev/null +++ b/scribble-test/src/test/scrib/exercise/calculator/Client.java @@ -0,0 +1,48 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package exercise.calculator; + +import java.io.IOException; +import java.util.concurrent.ExecutionException; + +import org.scribble.main.ScribbleRuntimeException; +import org.scribble.net.ObjectStreamFormatter; +import org.scribble.net.session.MPSTEndpoint; +import org.scribble.net.session.SocketChannelEndpoint; + +import exercise.calculator.EProtocol.Calc.Calc; +import exercise.calculator.EProtocol.Calc.channels.C.Calc_C_1; +import exercise.calculator.EProtocol.Calc.roles.C; + +public class Client +{ + public static void main(String[] args) throws IOException, ScribbleRuntimeException, ExecutionException, InterruptedException, ClassNotFoundException + { + Calc calculator = new Calc(); + try (MPSTEndpoint se = new MPSTEndpoint<>(calculator, Calc.C, new ObjectStreamFormatter())) + { + se.connect(Calc.C, SocketChannelEndpoint::new, "localhost", 8888); + + Calc_C_1 s1 = new Calc_C_1(se); + + // toto: Implement the rest ... + + System.out.println("Done:"); + + } catch (Exception e) + { + e.printStackTrace(); + } + } +} diff --git a/scribble-test/src/test/scrib/exercise/calculator/EProtocol.scr b/scribble-test/src/test/scrib/exercise/calculator/EProtocol.scr new file mode 100644 index 000000000..c2bf7489f --- /dev/null +++ b/scribble-test/src/test/scrib/exercise/calculator/EProtocol.scr @@ -0,0 +1,25 @@ +//$ bin/scribblec.sh -d modules/core/src/test/scrib/ modules/core/src/test/scrib/exercise/calculator/EProtocol.scr -api Calc C + +module exercise.calculator.EProtocol; + +type "java.lang.Integer" from "rt.jar" as int; +type "java.lang.String" from "rt.jar" as string; + + +global protocol Calc(role S , role C ) { + rec Loop { + choice at C { + sum (int, int) from C to S ; + result (int) from S to C ; + continue Loop ; + } or { + multiply (int, int) from C to S ; + result (int) from S to C ; + continue Loop ; + } or { + quit () from C to S ; + terminate () from S to C ; + } + } +} + diff --git a/scribble-test/src/test/scrib/exercise/calculator/Server.java b/scribble-test/src/test/scrib/exercise/calculator/Server.java new file mode 100644 index 000000000..dfbdd7451 --- /dev/null +++ b/scribble-test/src/test/scrib/exercise/calculator/Server.java @@ -0,0 +1,46 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package exercise.calculator; + +import java.io.IOException; +import java.util.concurrent.ExecutionException; + +import org.scribble.main.ScribbleRuntimeException; +import org.scribble.net.ObjectStreamFormatter; +import org.scribble.net.session.MPSTEndpoint; +import org.scribble.net.session.SocketChannelEndpoint; + +import exercise.calculator.EProtocol.Calc.Calc; +import exercise.calculator.EProtocol.Calc.channels.S.Calc_S_1; +import exercise.calculator.EProtocol.Calc.roles.S; + + +public class Server +{ + public static void main(String[] args) throws IOException, ScribbleRuntimeException, ExecutionException, InterruptedException, ClassNotFoundException + { + Calc calculator = new Calc(); + try (MPSTEndpoint se = new MPSTEndpoint<>(calculator, Calc.S, new ObjectStreamFormatter())) + { + se.connect(Calc.S, SocketChannelEndpoint::new, "localhost", 8888); + Calc_S_1 s1 = new Calc_S_1(se); + + // toto: Implement the rest ... + + } catch (Exception e) + { + e.printStackTrace(); + } + } +} diff --git a/scribble-test/src/test/scrib/exercise/voting/EProtocol.scr b/scribble-test/src/test/scrib/exercise/voting/EProtocol.scr new file mode 100644 index 000000000..b0ab16f03 --- /dev/null +++ b/scribble-test/src/test/scrib/exercise/voting/EProtocol.scr @@ -0,0 +1,24 @@ +//$ bin/scribblec.sh -d modules/core/src/test/scrib/ modules/core/src/test/scrib/exercise/voting/EProtocol.scr -api EVoting C + +module exercise.voting.EProtocol; + +type "java.lang.Integer" from "rt.jar" as Int; +type "java.lang.String" from "rt.jar" as String; + + +global protocol EVoting(role V, role S){ + Authenticate(String ) from V to S; + choice at S { + Ok(String) from S to V; + + choice at V { + Yes(String) from V to S; + } or { + No(String) from V to S; + } + Result(Int) from S to V; + } or { + Reject(String ) from S to V; + } +} + diff --git a/scribble-test/src/test/scrib/exercise/voting/Server.java b/scribble-test/src/test/scrib/exercise/voting/Server.java new file mode 100644 index 000000000..f9400addc --- /dev/null +++ b/scribble-test/src/test/scrib/exercise/voting/Server.java @@ -0,0 +1,62 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package exercise.voting; + +import java.io.IOException; +import java.util.concurrent.ExecutionException; + +import org.scribble.main.ScribbleRuntimeException; +import org.scribble.net.Buf; +import org.scribble.net.ObjectStreamFormatter; +import org.scribble.net.session.MPSTEndpoint; +import org.scribble.net.session.SocketChannelEndpoint; + +import exercise.voting.EProtocol.EVoting.EVoting; +import exercise.voting.EProtocol.EVoting.channels.S.EVoting_S_1; +import exercise.voting.EProtocol.EVoting.channels.S.EVoting_S_3_Cases; +import exercise.voting.EProtocol.EVoting.channels.S.EVoting_S_4; +import exercise.voting.EProtocol.EVoting.roles.S; + +public class Server +{ + public static void main(String[] args) throws IOException, ScribbleRuntimeException, ExecutionException, InterruptedException, ClassNotFoundException + { + EVoting vp = new EVoting(); + try (MPSTEndpoint se = new MPSTEndpoint<>(vp, EVoting.S, new ObjectStreamFormatter())) + { + se.connect(EVoting.S, SocketChannelEndpoint::new, "localhost", 8888); + EVoting_S_1 s1 = new EVoting_S_1(se); + Buf name = new Buf<>(); + + EVoting_S_3_Cases cases = s1.receive(EVoting.V, EVoting.Authenticate, name) + .send(EVoting.V, EVoting.Ok, name.val).branch(EVoting.V); + + Buf vote = new Buf<>(); + + EVoting_S_4 s2 = null; + switch(cases.op){ + case No: s2 = cases.receive(EVoting.V, EVoting.No, vote); break; + case Yes: s2 = cases.receive(EVoting.V, EVoting.No, vote); break; + } + + s2.send(EVoting.V, EVoting.Result, new Integer(1)); + + System.out.printf("Done: ~s", vote.val); + + } catch (Exception e) + { + e.printStackTrace(); + } + } +} diff --git a/scribble-test/src/test/scrib/exercise/voting/Voter.java b/scribble-test/src/test/scrib/exercise/voting/Voter.java new file mode 100644 index 000000000..39777f82a --- /dev/null +++ b/scribble-test/src/test/scrib/exercise/voting/Voter.java @@ -0,0 +1,72 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package exercise.voting; + +import java.io.IOException; +import java.util.concurrent.ExecutionException; + +import org.scribble.main.ScribbleRuntimeException; +import org.scribble.net.Buf; +import org.scribble.net.ObjectStreamFormatter; +import org.scribble.net.session.MPSTEndpoint; +import org.scribble.net.session.SocketChannelEndpoint; + +import exercise.voting.EProtocol.EVoting.EVoting; +import exercise.voting.EProtocol.EVoting.channels.V.EVoting_V_1; +import exercise.voting.EProtocol.EVoting.channels.V.EVoting_V_2_Cases; +import exercise.voting.EProtocol.EVoting.channels.V.EVoting_V_4; +import exercise.voting.EProtocol.EVoting.roles.V; + + +public class Voter +{ + public static void main(String[] args) throws IOException, ScribbleRuntimeException, ExecutionException, InterruptedException, ClassNotFoundException + { + EVoting vp = new EVoting(); + try (MPSTEndpoint se = new MPSTEndpoint<>(vp, EVoting.V, new ObjectStreamFormatter())) + { + se.connect(EVoting.V, SocketChannelEndpoint::new, "localhost", 8888); + String name = "my name"; + EVoting_V_1 s1 = new EVoting_V_1(se); + + /* + EVoting_V_2_Cases cases = s1.receive(EVoting.S, EVoting.Authenticate, name) + .branch(EVoting.S);; + + EVoting_V_4 s3 = null; + + switch(cases.op){ + case Ok: Buf token = new Buf<>(); + s3 = cases.receive(EVoting.Ok, token) + .send(EVoting.S, EVoting.Maybe, token); + break; + case Reject: + Buf reason = new Buf<>(); + s3 = cases.receive(EVoting.S, EVoting.Reject,reason) + .send(EVoting.S, EVoting.Yes, name); + break; + + } + Buf results = new Buf<>(); + s3.receive(EVoting.S, EVoting.Result, results); + */ + + System.out.println("Done:"); + + } catch (Exception e) + { + e.printStackTrace(); + } + } +} diff --git a/scribble-test/src/test/scrib/scratch/scratch1/MyC.java b/scribble-test/src/test/scrib/scratch/scratch1/MyC.java new file mode 100644 index 000000000..5720d3b1b --- /dev/null +++ b/scribble-test/src/test/scrib/scratch/scratch1/MyC.java @@ -0,0 +1,82 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +//$ java -cp modules/cli/target/classes/';'modules/core/target/classes';'modules/trace/target/classes';'modules/parser/target/classes';c:\Users\Raymond\.m2\repository\org\antlr\antlr-runtime\3.2\antlr-runtime-3.2.jar;'modules/validation/target/classes/';'modules/projection/target/classes/';C:\Users\Raymond\.m2\repository\org\codehaus\jackson\jackson-mapper-asl\1.9.9\jackson-mapper-asl-1.9.9.jar;C:\Users\Raymond\.m2\repository\org\codehaus\jackson\jackson-core-asl\1.9.9\jackson-core-asl-1.9.9.jar' org.scribble2.cli.CommandLine -path modules/validation/src/test/scrib/src modules/validation/src/test/scrib/src/Test.scr -session Foo -d modules/validation/src/main/java +//$ java -cp modules/cli/target/classes/';'modules/core/target/classes';'modules/trace/target/classes';'modules/parser/target/classes';c:\Users\Raymond\.m2\repository\org\antlr\antlr-runtime\3.2\antlr-runtime-3.2.jar;'modules/validation/target/classes/';'modules/projection/target/classes/';C:\Users\Raymond\.m2\repository\org\codehaus\jackson\jackson-mapper-asl\1.9.9\jackson-mapper-asl-1.9.9.jar;C:\Users\Raymond\.m2\repository\org\codehaus\jackson\jackson-core-asl\1.9.9\jackson-core-asl-1.9.9.jar' org.scribble2.cli.CommandLine -path modules/validation/src/test/scrib/src modules/validation/src/test/scrib/src/Test.scr -api Foo A -d modules/validation/src/main/java + +package scratch.scratch1; + +import java.io.IOException; + +import org.scribble.main.ScribbleRuntimeException; +import org.scribble.net.ObjectStreamFormatter; +import org.scribble.net.session.MPSTEndpoint; +import org.scribble.net.session.SocketChannelEndpoint; + +import scratch.scratch1.Scratch1.Proto1.Proto1; +import scratch.scratch1.Scratch1.Proto1.channels.C.Proto1_C_1; +import scratch.scratch1.Scratch1.Proto1.channels.C.Proto1_C_2; +import scratch.scratch1.Scratch1.Proto1.channels.C.ioifaces.Receive_C_S_3_Int; +import scratch.scratch1.Scratch1.Proto1.channels.C.ioifaces.Select_C_S_1; +import scratch.scratch1.Scratch1.Proto1.channels.C.ioifaces.Select_C_S_2_Int__S_4a; +import scratch.scratch1.Scratch1.Proto1.channels.C.ioifaces.Select_C_S_4b; +import scratch.scratch1.Scratch1.Proto1.channels.C.ioifaces.Succ_Out_S_4a; +import scratch.scratch1.Scratch1.Proto1.roles.C; + + +public class MyC +{ + // refactor separate io iface generators + // fix action string canonical ordering + // subtype hierarchy / io iface for handler iface + + public static void main(String[] args) throws Exception + { + Proto1 adder = new Proto1(); + try (MPSTEndpoint se = new MPSTEndpoint<>(adder, Proto1.C, new ObjectStreamFormatter())) + { + se.connect(Proto1.S, SocketChannelEndpoint::new, "localhost", 8888); + + Proto1_C_2 s2 = new Proto1_C_1(se).send(Proto1.S, Proto1._1); + /*for (int i = 0; i < 3; i++) + { + s2 = + s2.send(Proto1.S, Proto1._2, 123) + .async(Proto1.S, Proto1._3) + .send(Proto1.S, Proto1._1); + } + s2.send(Proto1.S, Proto1._4).end();*/ + + /*for (int i = 0; i < 3; i++) + { + s1 = + s1.send(Proto1.S, Proto1._1) + .send(Proto1.S, Proto1._2, 123) + .receive(Proto1.S, Proto1._3, new Buff<>()); + } + s1.send(Proto1.S, Proto1._1).send(Proto1.S, Proto1._4).end();*/ + + foo(s2, 0).to(Select_C_S_4b.cast).send(Proto1.S, Proto1._4b); + } + } + + static Succ_Out_S_4a foo(Select_C_S_2_Int__S_4a s, int i) throws ScribbleRuntimeException, IOException + { + return (i < 3) + ? foo( + s.send(Proto1.S, Proto1._2, 123) + .to(Receive_C_S_3_Int.cast).async(Proto1.S, Proto1._3) + .to(Select_C_S_1.cast).send(Proto1.S, Proto1._1).to(Select_C_S_2_Int__S_4a.cast), i + 1) //Select_C_S_2_Int__S_4.cast + : s.send(Proto1.S, Proto1._4a); + } +} diff --git a/scribble-test/src/test/scrib/scratch/scratch1/MyS.java b/scribble-test/src/test/scrib/scratch/scratch1/MyS.java new file mode 100644 index 000000000..bd90e35cf --- /dev/null +++ b/scribble-test/src/test/scrib/scratch/scratch1/MyS.java @@ -0,0 +1,155 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package scratch.scratch1; + +import java.io.IOException; + +import org.scribble.main.ScribbleRuntimeException; +import org.scribble.net.Buf; +import org.scribble.net.ObjectStreamFormatter; +import org.scribble.net.scribsock.ScribServerSocket; +import org.scribble.net.scribsock.SocketChannelServer; +import org.scribble.net.session.MPSTEndpoint; + +import scratch.scratch1.Scratch1.Proto1.Proto1; +import scratch.scratch1.Scratch1.Proto1.channels.S.EndSocket; +import scratch.scratch1.Scratch1.Proto1.channels.S.Proto1_S_1; +import scratch.scratch1.Scratch1.Proto1.channels.S.ioifaces.Branch_S_C_2_Int__C_4a; +import scratch.scratch1.Scratch1.Proto1.channels.S.ioifaces.Handle_S_C_2_Int__C_4a; +import scratch.scratch1.Scratch1.Proto1.channels.S.ioifaces.Receive_S_C_1; +import scratch.scratch1.Scratch1.Proto1.channels.S.ioifaces.Receive_S_C_4b; +import scratch.scratch1.Scratch1.Proto1.channels.S.ioifaces.Select_S_C_3_Int; +import scratch.scratch1.Scratch1.Proto1.channels.S.ioifaces.Succ_In_C_2_Int; +import scratch.scratch1.Scratch1.Proto1.channels.S.ioifaces.Succ_In_C_4a; +import scratch.scratch1.Scratch1.Proto1.ops._2; +import scratch.scratch1.Scratch1.Proto1.ops._4a; +import scratch.scratch1.Scratch1.Proto1.roles.S; + +public class MyS +{ + public static void main(String[] args) throws IOException, ScribbleRuntimeException + { + try (ScribServerSocket ss = new SocketChannelServer(8888)) + { + //Buf i1 = new Buf<>(); + //Buf i2 = new Buf<>(); + + while (true) + { + Proto1 foo = new Proto1(); + //SessionEndpoint se = foo.project(Proto1.S, new ObjectStreamFormatter(), ss); + try (MPSTEndpoint se = new MPSTEndpoint<>(foo, Proto1.S, new ObjectStreamFormatter())) + { + se.accept(ss, Proto1.C); + + new Proto1_S_1(se).async(Proto1.C, Proto1._1) + //.branch(Proto1.C, new Handler()); + .handle(Proto1.C, new Handler2()); + //.branch(Proto1.C, new Handler3<>()); + } + catch (Exception e)//ScribbleRuntimeException | IOException | ExecutionException | InterruptedException | ClassNotFoundException e) + { + e.printStackTrace(); + } + } + } + } +} + +/*class Handler implements Proto1_S_2_Handler +{ + @Override + public void receive(EndSocket schan, _4 op) throws ScribbleRuntimeException, IOException + { + System.out.println("Done1-4"); + schan.end(); + } + + @Override + public void receive(Proto1_S_3 schan, _2 op, Buf b) throws ScribbleRuntimeException, IOException + { + System.out.println("Redo: " + b.val); + try + { + schan.send(Proto1.C, Proto1._3, 456).async(Proto1.C, Proto1._1) + .branch(Proto1.C, this); + //.handle(Proto1.C, this); // "this" handler is not generic enough + } + catch (ClassNotFoundException e) + { + throw new IOException(e); + } + } + + //@Override // Re-generated State I/O handler won't have the deprecated callback + public void receive(EndSocket schan, _5 op) throws ScribbleRuntimeException, IOException, ClassNotFoundException + { + System.out.println("Done1-5"); + } +} +//*/ + +//class Handler2 implements Handle_S_C_2_Int__C_4 +class Handler2 implements Handle_S_C_2_Int__C_4a +{ + @Override + //public void receive(Proto1_S_3 schan, _2 op, Buf b) throws ScribbleRuntimeException, IOException, ClassNotFoundException + //public void receive(Select_S_C_3_Int schan, _2 op, Buf b) throws ScribbleRuntimeException, IOException, ClassNotFoundException + //public void receive(Succ_In_C_2_Int schan, _2 op, Buf b) throws ScribbleRuntimeException, IOException, ClassNotFoundException + public void receive(Succ_In_C_2_Int schan, _2 op, Buf b) throws ScribbleRuntimeException, IOException, ClassNotFoundException + { + System.out.println("Redo: " + b.val); + schan.to(Select_S_C_3_Int.cast).send(Proto1.C, Proto1._3, 356).to(Receive_S_C_1.cast).async(Proto1.C, Proto1._1).to(Branch_S_C_2_Int__C_4a.cast).handle(Proto1.C, this); + } + + @Override + public void receive(Succ_In_C_4a schan, _4a op) throws ScribbleRuntimeException, IOException, ClassNotFoundException + { + schan.to(Receive_S_C_4b.cast).receive(Proto1.C, Proto1._4b).to(EndSocket.cast).end(); + System.out.println("Done2-4"); + } + + /*@Override + public void receive(Succ_In_C_5 schan, _5 op) throws ScribbleRuntimeException, IOException, ClassNotFoundException + { + System.out.println("Done2-5"); + }*/ +} + +/*class Handler3 implements Handle_S_C_2_Int__C_4__C_5 +{ + @Override + public void receive(Succ1 schan, _2 op, Buf b) throws ScribbleRuntimeException, IOException, ClassNotFoundException + { + System.out.println("Redo: " + b.val); + ((Branch_S_C_2_Int__C_4__C_5) schan.to(Select_S_C_3_Int.cast).send(Proto1.C, Proto1._3, 356).to(Receive_S_C_1.cast).async(Proto1.C, Proto1._1)).branch(Proto1.C, this); + //schan.to(Select_S_C_3_Int.cast).send(Proto1.C, Proto1._3, 356).to(Receive_S_C_1.cast).async(Proto1.C, Proto1._1).to(Branch_S_C_2_Int__C_4.cast).branch(Proto1.C, this); + //((Branch_S_C_2_Int__C_4) schan.to(Select_S_C_3_Int.cast).send(Proto1.C, Proto1._3, 356).to(Receive_S_C_1.cast).async(Proto1.C, Proto1._1)).branch(Proto1.C, this); + //schan.to(Select_S_C_3_Int.cast).send(Proto1.C, Proto1._3, 356).to(Receive_S_C_1.cast).async(Proto1.C, Proto1._1).to(Branch_S_C_2_Int__C_4.cast).branch(Proto1.C, this); + } + + @Override + public void receive(Succ2 schan, _4 op) throws ScribbleRuntimeException, IOException + { + schan.to(EndSocket.cast).end(); + System.out.println("Done3-4"); + } + + @Override + public void receive(Succ3 schan, _5 op) throws ScribbleRuntimeException, IOException, ClassNotFoundException + { + System.out.println("Done3-5"); + } +} +//*/ diff --git a/scribble-test/src/test/scrib/scratch/scratch1/Scratch1.scr b/scribble-test/src/test/scrib/scratch/scratch1/Scratch1.scr new file mode 100644 index 000000000..77141c5e2 --- /dev/null +++ b/scribble-test/src/test/scrib/scratch/scratch1/Scratch1.scr @@ -0,0 +1,65 @@ +//http://sandbox.kidstrythisathome.com/erdos/ + +//$ bin/scribblec.sh modules/core/src/test/scrib/scratch/scratch1/Scratch1.scr -ip modules/core/src/test/scrib/ -d modules/core/src/test/scrib/ -api Proto1 C -subtypes +//$ javadoc -cp modules/cli/target/classes/';'modules/core/target/classes';'modules/trace/target/classes';'modules/parser/target/classes';c:\Users\Raymond\.m2\repository\org\antlr\antlr-runtime\3.2\antlr-runtime-3.2.jar;'modules/validation/target/classes/';'modules/projection/target/classes/';C:\Users\Raymond\.m2\repository\org\codehaus\jackson\jackson-mapper-asl\1.9.9\jackson-mapper-asl-1.9.9.jar;C:\Users\Raymond\.m2\repository\org\codehaus\jackson\jackson-core-asl\1.9.9\jackson-core-asl-1.9.9.jar;'modules/core/src/test/scrib modules/core/src/test/scrib/scratch/scratch1/Proto1*.java -d test/doc/scratch/scratch1 + +module scratch.scratch1.Scratch1; + +type "java.lang.Integer" from "rt.jar" as Int; + +global protocol Proto1(role C, role S) +{ + rec X + { + 1() from C to S; + choice at C + { + 2(Int) from C to S; + 3(Int) from S to C; + continue X; + } + or + { + 4a() from C to S; + 4b() from C to S; + } + or + { + 4a() from C to S; // Currently needs -minfsm + 4b() from C to S; + } + } +} + +global protocol Proto2(role C, role S) +{ + 1() from C to S; + //2() from C to S; + choice at C + { + 3() from C to S; + do Proto2(C, S); + } + or + { + 2() from C to S; + } +} + +global protocol Proto3(role C, role S) +{ + rec X + { + 1() from C to S; + choice at C + { + 2(Int) from C to S; + 3(Int) from S to C; + continue X; + } + or + { + 4() from C to S; + } + } +} \ No newline at end of file diff --git a/scribble-test/src/test/scrib/test/foo/Foo.scr b/scribble-test/src/test/scrib/test/foo/Foo.scr new file mode 100644 index 000000000..63f6966ac --- /dev/null +++ b/scribble-test/src/test/scrib/test/foo/Foo.scr @@ -0,0 +1,27 @@ +//Raymond@HZHL3 ~/code/scribble-java/scribble-java +//$ java -cp modules/cli/target/classes/';'modules/core/target/classes';'modules/trace/target/classes';'modules/parser/target/classes';c:\Users\Raymond\.m2\repository\org\antlr\antlr-runtime\3.2\antlr-runtime-3.2.jar;'modules/validation/target/classes/';'modules/projection/target/classes/';C:\Users\Raymond\.m2\repository\org\codehaus\jackson\jackson-mapper-asl\1.9.9\jackson-mapper-asl-1.9.9.jar;C:\Users\Raymond\.m2\repository\org\codehaus\jackson\jackson-core-asl\1.9.9\jackson-core-asl-1.9.9.jar' org.scribble.cli.CommandLine -path modules/core/src/test/scrib modules/core/src/test/scrib/test/foo/Foo.scr -session Foo -d modules/core/src/test/scrib +//$ java -cp modules/cli/target/classes/';'modules/core/target/classes';'modules/trace/target/classes';'modules/parser/target/classes';c:\Users\Raymond\.m2\repository\org\antlr\antlr-runtime\3.2\antlr-runtime-3.2.jar;'modules/validation/target/classes/';'modules/projection/target/classes/';C:\Users\Raymond\.m2\repository\org\codehaus\jackson\jackson-mapper-asl\1.9.9\jackson-mapper-asl-1.9.9.jar;C:\Users\Raymond\.m2\repository\org\codehaus\jackson\jackson-core-asl\1.9.9\jackson-core-asl-1.9.9.jar' org.scribble.cli.CommandLine -path modules/core/src/test/scrib modules/core/src/test/scrib/test/foo/Foo.scr -api Foo A -d modules/core/src/test/scrib + +//$ javadoc -cp modules/cli/target/classes/';'modules/core/target/classes';'modules/trace/target/classes';'modules/parser/target/classes';c:\Users\Raymond\.m2\repository\org\antlr\antlr-runtime\3.2\antlr-runtime-3.2.jar;'modules/validation/target/classes/';'modules/projection/target/classes/';C:\Users\Raymond\.m2\repository\org\codehaus\jackson\jackson-mapper-asl\1.9.9\jackson-mapper-asl-1.9.9.jar;C:\Users\Raymond\.m2\repository\org\codehaus\jackson\jackson-core-asl\1.9.9\jackson-core-asl-1.9.9.jar;'modules/core/src/test/scrib modules/core/src/test/scrib/test/foo/Foo*.java -d test/javadoc/test + +//$ bin/scribblec.sh modules/core/src/test/scrib/test/foo/Foo.scr -ip modules/core/src/test/scrib/ -d modules/core/src/test/scrib/ -session Foo -api Foo A -V + +module test.foo.Foo; + + +//type "java.lang.Integer" from "rt.jar" as Integer; + + +global protocol Foo(role A, role B, role C) +{ + choice at A + { + 1() from A to B; + 2() from A to C; + } + or + { + 1() from A to C; + 2() from A to B; + } +} diff --git a/scribble-test/src/test/scrib/test/foo/MyA.java b/scribble-test/src/test/scrib/test/foo/MyA.java new file mode 100644 index 000000000..9910a2b03 --- /dev/null +++ b/scribble-test/src/test/scrib/test/foo/MyA.java @@ -0,0 +1,46 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +//$ java -cp modules/cli/target/classes/';'modules/core/target/classes';'modules/trace/target/classes';'modules/parser/target/classes';c:\Users\Raymond\.m2\repository\org\antlr\antlr-runtime\3.2\antlr-runtime-3.2.jar;'modules/validation/target/classes/';'modules/projection/target/classes/';C:\Users\Raymond\.m2\repository\org\codehaus\jackson\jackson-mapper-asl\1.9.9\jackson-mapper-asl-1.9.9.jar;C:\Users\Raymond\.m2\repository\org\codehaus\jackson\jackson-core-asl\1.9.9\jackson-core-asl-1.9.9.jar' org.scribble2.cli.CommandLine -path modules/validation/src/test/scrib/src modules/validation/src/test/scrib/src/Test.scr -session Foo -d modules/validation/src/main/java +//$ java -cp modules/cli/target/classes/';'modules/core/target/classes';'modules/trace/target/classes';'modules/parser/target/classes';c:\Users\Raymond\.m2\repository\org\antlr\antlr-runtime\3.2\antlr-runtime-3.2.jar;'modules/validation/target/classes/';'modules/projection/target/classes/';C:\Users\Raymond\.m2\repository\org\codehaus\jackson\jackson-mapper-asl\1.9.9\jackson-mapper-asl-1.9.9.jar;C:\Users\Raymond\.m2\repository\org\codehaus\jackson\jackson-core-asl\1.9.9\jackson-core-asl-1.9.9.jar' org.scribble2.cli.CommandLine -path modules/validation/src/test/scrib/src modules/validation/src/test/scrib/src/Test.scr -api Foo A -d modules/validation/src/main/java + +package test.foo; + +import org.scribble.runtime.net.ObjectStreamFormatter; +import org.scribble.runtime.net.session.MPSTEndpoint; +import org.scribble.runtime.net.session.SocketChannelEndpoint; + +import test.foo.Foo.Foo.Foo; +import test.foo.Foo.Foo.channels.A.Foo_A_1; +import test.foo.Foo.Foo.roles.A; + + +public class MyA +{ + public static void main(String[] args) throws Exception + { + //Buff i1 = new Buff<>(0); + + Foo foo = new Foo(); + try (MPSTEndpoint se = new MPSTEndpoint<>(foo, Foo.A, new ObjectStreamFormatter())) + { + se.connect(Foo.B, SocketChannelEndpoint::new, "localhost", 8888); + se.connect(Foo.C, SocketChannelEndpoint::new, "localhost", 9999); + + Foo_A_1 s1 = new Foo_A_1(se); + s1 + //.send(Foo.C, Foo._1).send(Foo.B, Foo._2); + .send(Foo.B, Foo._1).send(Foo.C, Foo._2); + } + } +} diff --git a/scribble-test/src/test/scrib/test/foo/MyBC.java b/scribble-test/src/test/scrib/test/foo/MyBC.java new file mode 100644 index 000000000..e8ad5a23c --- /dev/null +++ b/scribble-test/src/test/scrib/test/foo/MyBC.java @@ -0,0 +1,116 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package test.foo; + +import java.io.IOException; + +import org.scribble.main.ScribbleRuntimeException; +import org.scribble.runtime.net.ObjectStreamFormatter; +import org.scribble.runtime.net.scribsock.ScribServerSocket; +import org.scribble.runtime.net.scribsock.SocketChannelServer; +import org.scribble.runtime.net.session.MPSTEndpoint; + +import test.foo.Foo.Foo.Foo; +import test.foo.Foo.Foo.channels.B.Foo_B_1; +import test.foo.Foo.Foo.channels.B.Foo_B_1_Cases; +import test.foo.Foo.Foo.channels.C.Foo_C_1; +import test.foo.Foo.Foo.channels.C.Foo_C_1_Cases; +import test.foo.Foo.Foo.roles.B; +import test.foo.Foo.Foo.roles.C; + +public class MyBC +{ + public static void main(String[] args) throws IOException, ScribbleRuntimeException, InterruptedException + { + try (ScribServerSocket ss_B = new SocketChannelServer(8888); + ScribServerSocket ss_C = new SocketChannelServer(9999)) + { + //Buff s = new Buff<>(); + + while (true) + { + Foo foo = new Foo(); + + Thread B = new Thread() + { + public void run() + { + try (MPSTEndpoint se_B = new MPSTEndpoint<>(foo, Foo.B, new ObjectStreamFormatter())) + { + se_B.accept(ss_B, Foo.A); + Foo_B_1 s1_B = new Foo_B_1(se_B); + + Foo_B_1_Cases s1cases_B = s1_B.branch(Foo.A); + switch (s1cases_B.op) + { + case _1: + { + s1cases_B.receive(Foo._1); + System.out.println("B first!"); + break; + } + case _2: + { + s1cases_B.receive(Foo._2); + break; + } + } + } + catch (ScribbleRuntimeException | IOException | ClassNotFoundException e) + { + e.printStackTrace(); + } + } + }; + + Thread C = new Thread() + { + public void run() + { + try (MPSTEndpoint se_C = new MPSTEndpoint<>(foo, Foo.C, new ObjectStreamFormatter())) + { + se_C.accept(ss_C, Foo.A); + + Foo_C_1 s1_C = new Foo_C_1(se_C); + Foo_C_1_Cases s1cases_C = s1_C.branch(Foo.A); + switch (s1cases_C.op) + { + case _1: + { + s1cases_C.receive(Foo._1); + System.out.println("C first!"); + break; + } + case _2: + { + s1cases_C.receive(Foo._2); + break; + } + } + } + catch (ScribbleRuntimeException | IOException | ClassNotFoundException e) + { + e.printStackTrace(); + } + } + }; + + B.start(); + C.start(); + B.join(); + C.join(); + } + } + } +} diff --git a/scribble-test/src/test/scrib/test/test1/MyC.java b/scribble-test/src/test/scrib/test/test1/MyC.java new file mode 100644 index 000000000..094129aa5 --- /dev/null +++ b/scribble-test/src/test/scrib/test/test1/MyC.java @@ -0,0 +1,59 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +//$ java -cp modules/cli/target/classes/';'modules/core/target/classes';'modules/trace/target/classes';'modules/parser/target/classes';c:\Users\Raymond\.m2\repository\org\antlr\antlr-runtime\3.2\antlr-runtime-3.2.jar;'modules/validation/target/classes/';'modules/projection/target/classes/';C:\Users\Raymond\.m2\repository\org\codehaus\jackson\jackson-mapper-asl\1.9.9\jackson-mapper-asl-1.9.9.jar;C:\Users\Raymond\.m2\repository\org\codehaus\jackson\jackson-core-asl\1.9.9\jackson-core-asl-1.9.9.jar' org.scribble2.cli.CommandLine -path modules/validation/src/test/scrib/src modules/validation/src/test/scrib/src/Test.scr -session Foo -d modules/validation/src/main/java +//$ java -cp modules/cli/target/classes/';'modules/core/target/classes';'modules/trace/target/classes';'modules/parser/target/classes';c:\Users\Raymond\.m2\repository\org\antlr\antlr-runtime\3.2\antlr-runtime-3.2.jar;'modules/validation/target/classes/';'modules/projection/target/classes/';C:\Users\Raymond\.m2\repository\org\codehaus\jackson\jackson-mapper-asl\1.9.9\jackson-mapper-asl-1.9.9.jar;C:\Users\Raymond\.m2\repository\org\codehaus\jackson\jackson-core-asl\1.9.9\jackson-core-asl-1.9.9.jar' org.scribble2.cli.CommandLine -path modules/validation/src/test/scrib/src modules/validation/src/test/scrib/src/Test.scr -api Foo A -d modules/validation/src/main/java + +package test.test1; + +import org.scribble.runtime.message.ObjectStreamFormatter; +import org.scribble.runtime.net.SocketChannelEndpoint; +import org.scribble.runtime.session.MPSTEndpoint; +import org.scribble.runtime.util.Buf; + +import test.test1.Test1.Proto1.Proto1; +import test.test1.Test1.Proto1.roles.C; +import test.test1.Test1.Proto1.statechans.C.Proto1_C_1; +import test.test1.Test1.Proto1.statechans.C.Proto1_C_2; + +public class MyC +{ + public static void main(String[] args) throws Exception + { + Proto1 adder = new Proto1(); + try (MPSTEndpoint se = new MPSTEndpoint<>(adder, Proto1.C, + new ObjectStreamFormatter())) + { + se.request(Proto1.S, SocketChannelEndpoint::new, "localhost", 8888); + + Proto1_C_2 s2 = new Proto1_C_1(se).send(Proto1.S, Proto1._1); + for (int i = 0; i < 3; i++) + { + s2 = + s2.send(Proto1.S, Proto1._2, 123) + .receive(Proto1.S, Proto1._3, new Buf<>()) + .send(Proto1.S, Proto1._1); + } + s2.send(Proto1.S, Proto1._4).end(); + + /*for (int i = 0; i < 3; i++) + { + s1 = + s1.send(Proto1.S, Proto1._1) + .send(Proto1.S, Proto1._2, 123) + .receive(Proto1.S, Proto1._3, new Buff<>()); + } + s1.send(Proto1.S, Proto1._1).send(Proto1.S, Proto1._4).end();*/ + } + } +} diff --git a/scribble-test/src/test/scrib/test/test1/MyS.java b/scribble-test/src/test/scrib/test/test1/MyS.java new file mode 100644 index 000000000..a88b7daf6 --- /dev/null +++ b/scribble-test/src/test/scrib/test/test1/MyS.java @@ -0,0 +1,121 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package test.test1; + +import java.io.IOException; + +import org.scribble.main.ScribRuntimeException; +import org.scribble.runtime.message.ObjectStreamFormatter; +import org.scribble.runtime.net.ScribServerSocket; +import org.scribble.runtime.net.SocketChannelServer; +import org.scribble.runtime.session.MPSTEndpoint; +import org.scribble.runtime.util.Buf; + +import test.test1.Test1.Proto1.Proto1; +import test.test1.Test1.Proto1.ops._2; +import test.test1.Test1.Proto1.ops._4; +import test.test1.Test1.Proto1.roles.S; +import test.test1.Test1.Proto1.statechans.S.EndSocket; +import test.test1.Test1.Proto1.statechans.S.Proto1_S_1; +import test.test1.Test1.Proto1.statechans.S.Proto1_S_2_Handler; +import test.test1.Test1.Proto1.statechans.S.Proto1_S_3; +import test.test1.Test1.Proto1.statechans.S.ioifaces.Branch_S_C_2_Integer__C_4; +import test.test1.Test1.Proto1.statechans.S.ioifaces.Handle_S_C_2_Integer__C_4; +import test.test1.Test1.Proto1.statechans.S.ioifaces.Receive_S_C_1; +import test.test1.Test1.Proto1.statechans.S.ioifaces.Select_S_C_3_Integer; +import test.test1.Test1.Proto1.statechans.S.ioifaces.Succ_In_C_2_Integer; +import test.test1.Test1.Proto1.statechans.S.ioifaces.Succ_In_C_4; + +public class MyS +{ + public static void main(String[] args) + throws IOException, ScribRuntimeException + { + try (ScribServerSocket ss = new SocketChannelServer(8888)) + { + //Buf i1 = new Buf<>(); + //Buf i2 = new Buf<>(); + + while (true) + { + Proto1 foo = new Proto1(); + //SessionEndpoint se = foo.project(Proto1.S, new ObjectStreamFormatter(), ss); + try (MPSTEndpoint se = new MPSTEndpoint<>(foo, Proto1.S, + new ObjectStreamFormatter())) + { + se.accept(ss, Proto1.C); + + new Proto1_S_1(se).async(Proto1.C, Proto1._1) + //.branch(Proto1.C, new Handler()); + .handle(Proto1.C, new Handler2()); + } + catch (Exception e)//ScribbleRuntimeException | IOException | ExecutionException | InterruptedException | ClassNotFoundException e) + { + e.printStackTrace(); + } + } + } + } +} + +class Handler implements Proto1_S_2_Handler +{ + @Override + public void receive(EndSocket schan, _4 op) + throws ScribRuntimeException, IOException + { + System.out.println("Done"); + schan.end(); + } + + @Override + public void receive(Proto1_S_3 schan, _2 op, Buf b) + throws ScribRuntimeException, IOException + { + System.out.println("Redo: " + b.val); + try + { + schan.send(Proto1.C, Proto1._3, 456).async(Proto1.C, Proto1._1) + .branch(Proto1.C, this); + } + catch (ClassNotFoundException e) + { + throw new IOException(e); + } + } +} + +class Handler2 + implements Handle_S_C_2_Integer__C_4 +{ + @Override + public void receive(Succ_In_C_2_Integer schan, _2 op, + Buf b) + throws ScribRuntimeException, IOException, ClassNotFoundException + { + System.out.println("Redo: " + b.val); + schan + .to(Select_S_C_3_Integer.cast).send(Proto1.C, Proto1._3, 123) + .to(Receive_S_C_1.cast).async(Proto1.C, Proto1._1) + .to(Branch_S_C_2_Integer__C_4.cast).handle(Proto1.C, this); + } + + @Override + public void receive(Succ_In_C_4 schan, _4 op) + throws ScribRuntimeException, IOException, ClassNotFoundException + { + schan.to(EndSocket.cast).end(); + System.out.println("Done"); + } +} diff --git a/scribble-test/src/test/scrib/test/test1/Test1.scr b/scribble-test/src/test/scrib/test/test1/Test1.scr new file mode 100644 index 000000000..3c11f8f03 --- /dev/null +++ b/scribble-test/src/test/scrib/test/test1/Test1.scr @@ -0,0 +1,32 @@ +//http://sandbox.kidstrythisathome.com/erdos/ + +//$ bin/scribblec.sh scribble-test/src/test/scrib/test/test1/Test1.scr -ip scribble-test/src/test/scrib/ -d scribble-test/src/test/scrib/ -api Proto1 C -V +//$ javadoc -cp modules/cli/target/classes/';'modules/core/target/classes';'modules/trace/target/classes';'modules/parser/target/classes';c:\Users\Raymond\.m2\repository\org\antlr\antlr-runtime\3.2\antlr-runtime-3.2.jar;'modules/validation/target/classes/';'modules/projection/target/classes/';C:\Users\Raymond\.m2\repository\org\codehaus\jackson\jackson-mapper-asl\1.9.9\jackson-mapper-asl-1.9.9.jar;C:\Users\Raymond\.m2\repository\org\codehaus\jackson\jackson-core-asl\1.9.9\jackson-core-asl-1.9.9.jar;'modules/core/src/test/scrib modules/core/src/test/scrib/test/test1/Proto1*.java -d test/doc/test1 + +module test.test1.Test1; + +type "java.lang.Integer" from "rt.jar" as Integer; + +global protocol Proto1(role C, role S) +{ + rec X + { + 1() from C to S; + choice at C + { + 2(Integer) from C to S; + 3(Integer) from S to C; + continue X; + } + or + { + 4() from C to S; + } + } +} + +global protocol Proto2(role C, role S) +{ + 1() from C to S; + 2() from C to S; +} diff --git a/scribble-test/src/test/scrib/test/test2/MyA.java b/scribble-test/src/test/scrib/test/test2/MyA.java new file mode 100644 index 000000000..72a1e4072 --- /dev/null +++ b/scribble-test/src/test/scrib/test/test2/MyA.java @@ -0,0 +1,106 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package test.test2; + +import static test.test2.Test2.Proto1.Proto1.A; +import static test.test2.Test2.Proto1.Proto1.B; +import static test.test2.Test2.Proto1.Proto1._1; + +import java.io.IOException; +import java.util.concurrent.Future; + +import org.scribble.runtime.message.ObjectStreamFormatter; +import org.scribble.runtime.net.SocketChannelEndpoint; +import org.scribble.runtime.session.MPSTEndpoint; + +import test.test2.Test2.Proto1.Proto1; +import test.test2.Test2.Proto1.callbacks.A.Proto1_A; +import test.test2.Test2.Proto1.callbacks.A.states.Proto1_A_1; +import test.test2.Test2.Proto1.roles.A; + +// TODO: test interop between ED API and SC API (also for sig messages) +public class MyA +{ + public static void main(String[] args) throws IOException + { + //foo1(); + foo3(); + } + + public static void foo3() throws IOException + { + Proto1 P1 = new Proto1(); + try (Proto1_A a = new Proto1_A<>(P1, A, new ObjectStreamFormatter(), null)) + { + a.request(B, SocketChannelEndpoint::new, "localhost", 8888); + + //TODO: test choice at A { 1() from A to B; 2() from A to C; } or { 1() from A to C; 3() from A to B; } + + a.icallback(Proto1_A_1.id, x -> + new Proto1_A_1.B._1(123) + //new Proto1_A_5.B._2("abc") + ); + // new IntPay<>(B, _1, 123)); // IntPay -- or StrPay + + Future f = a.run(); // Even if registration checks still dynamic, much better to check at "session init" than partway through session after potential side effects + f.get(); + + System.out.println("(A) end"); + } + catch (Exception e) + { + e.printStackTrace(); + } + } + + /*public static void foo2() throws IOException, ScribbleRuntimeException + { + Proto1 P1 = new Proto1(); + try (Proto1_A a = new Proto1_A(P1, A, new ObjectStreamFormatter())) + { + a.request(B, SocketChannelEndpoint::new, "localhost", 8888); + //a.register(Proto1_A_5.id, x -> new ScribEvent(B, _1)); + a.register(Proto1_A_5.id, x -> new ScribEvent(B, _2)); + // FIXME: type by Op (state-specific op enum for state-specific scribevent?); sort out session object + + Future f = a.run(); + f.get(); + + System.out.println("A done"); + } + catch (Exception e) + { + e.printStackTrace(); + } + }*/ + + public static void foo1() + { + Proto1 P1 = new Proto1(); + try (MPSTEndpoint a = new MPSTEndpoint<>(P1, A, new ObjectStreamFormatter())) + { + a.request(B, SocketChannelEndpoint::new, "localhost", 8888); + + test.test2.Test2.Proto1.statechans.A.Proto1_A_1 s + = new test.test2.Test2.Proto1.statechans.A.Proto1_A_1(a); + s.send(B, _1, 123); + + //new Proto1_A_1(a).send(B, _2, "abc"); + } + catch (Exception e) + { + e.printStackTrace(); + } + } +} diff --git a/scribble-test/src/test/scrib/test/test2/MyB.java b/scribble-test/src/test/scrib/test/test2/MyB.java new file mode 100644 index 000000000..8f5ea4cf0 --- /dev/null +++ b/scribble-test/src/test/scrib/test/test2/MyB.java @@ -0,0 +1,152 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package test.test2; + +import static test.test2.Test2.Proto1.Proto1.A; +import static test.test2.Test2.Proto1.Proto1.B; + +import java.io.IOException; +import java.util.concurrent.Future; + +import org.scribble.main.ScribbleRuntimeException; +import org.scribble.runtime.message.ObjectStreamFormatter; +import org.scribble.runtime.net.ScribServerSocket; +import org.scribble.runtime.net.SocketChannelServer; +import org.scribble.runtime.session.MPSTEndpoint; +import org.scribble.runtime.util.Buf; + +import test.test2.Test2.Proto1.Proto1; +import test.test2.Test2.Proto1.callbacks.B.Proto1_B; +import test.test2.Test2.Proto1.callbacks.B.Proto1_B_1_Branch; +import test.test2.Test2.Proto1.callbacks.B.states.Proto1_B_1; +import test.test2.Test2.Proto1.ops._1; +import test.test2.Test2.Proto1.ops._2; +import test.test2.Test2.Proto1.roles.A; +import test.test2.Test2.Proto1.roles.B; +import test.test2.Test2.Proto1.statechans.B.EndSocket; +import test.test2.Test2.Proto1.statechans.B.Proto1_B_1_Handler; + +public class MyB +{ + public static void main(String[] args) throws IOException, ScribbleRuntimeException + { + foo3(); + //foo1(); + } + + public static void foo3() throws IOException + { + class MyHandler extends Proto1_B_1_Branch + { + @Override + public void receive(Void data, A peer, _1 op, Integer arg1) + { + System.out.println("(B) received 1: " + arg1); + } + + @Override + public void receive(Void data, A peer, _2 op, String arg1) + { + System.out.println("(B) received 2: " + arg1); + } + } + + try (ScribServerSocket ss = new SocketChannelServer(8888)) + { + while (true) + { + Proto1 P1 = new Proto1(); + try (Proto1_B b = new Proto1_B<>(P1, B, new ObjectStreamFormatter(), null)) + { + b.accept(ss, A); + + b.icallback(Proto1_B_1.id, new MyHandler()); + + Future f = b.run(); + f.get(); + + System.out.println("(B) end"); + } + catch (Exception e) + { + e.printStackTrace(); + } + } + } + } + + /*public static void foo2() throws IOException, ScribbleRuntimeException + { + try (ScribServerSocket ss = new SocketChannelServer(8888)) + { + while (true) + { + Proto1 P1 = new Proto1(); + try (Proto1_B b = new Proto1_B(P1, B, new ObjectStreamFormatter())) + { + b.accept(ss, A); + b.register(Proto1_B_10.id, + (op, sess) -> { System.out.println("Done 1"); return null; }, + (op, sess) -> { System.out.println("Done 2"); return null; }); + // FIXME: branch handler objects and payloads + + Future f = b.run(); + f.get(); + + System.out.println("B done"); + } + catch (Exception e) + { + e.printStackTrace(); + } + } + } + }*/ + + public static void foo1() throws IOException, ScribbleRuntimeException + { + class MyHandler implements Proto1_B_1_Handler + { + @Override + public void receive(EndSocket schan, _1 op, Buf arg1) throws ScribbleRuntimeException, IOException, ClassNotFoundException + { + System.out.println("Done 1"); + } + + @Override + public void receive(EndSocket schan, _2 op, Buf arg1) throws ScribbleRuntimeException, IOException, ClassNotFoundException + { + System.out.println("Done 2"); + } + } + + try (ScribServerSocket ss = new SocketChannelServer(8888)) + { + while (true) + { + Proto1 P1 = new Proto1(); + try (MPSTEndpoint b = new MPSTEndpoint<>(P1, B, new ObjectStreamFormatter())) + { + b.accept(ss, A); + + new test.test2.Test2.Proto1.statechans.B.Proto1_B_1(b).branch(A, new MyHandler()); + } + catch (Exception e)//ScribbleRuntimeException | IOException | ExecutionException | InterruptedException | ClassNotFoundException e) + { + e.printStackTrace(); + } + } + } + } +} diff --git a/scribble-test/src/test/scrib/test/test2/Test2.scr b/scribble-test/src/test/scrib/test/test2/Test2.scr new file mode 100644 index 000000000..33fda4133 --- /dev/null +++ b/scribble-test/src/test/scrib/test/test2/Test2.scr @@ -0,0 +1,19 @@ +//$ bin/scribblec.sh scribble-test/src/test/scrib/test/test2/Test2.scr -d scribble-test/src/test/scrib/ -cbapi Proto1 A -cbapi Proto1 B +//$ javadoc -cp scribble-cli/target/classes/';'scribble-test/target/classes';'scribble-parser/target/classes';'scribble-parser/lib/antlr-3.5.2-complete.jar';'scrib-core/src/test/scrib scrib-core/src/test/scrib/test/test2/Proto1*.java -d test/doc/test2 + +module test.test2.Test2; + +type "java.lang.Integer" from "rt.jar" as Int; +type "java.lang.String" from "rt.jar" as Str; + +global protocol Proto1(role A, role B) +{ + choice at A + { + 1(Int) from A to B; + } + or + { + 2(Str) from A to B; + } +} diff --git a/scribble-test/src/test/scrib/test/test3/MyA.java b/scribble-test/src/test/scrib/test/test3/MyA.java new file mode 100644 index 000000000..e13d1b4f1 --- /dev/null +++ b/scribble-test/src/test/scrib/test/test3/MyA.java @@ -0,0 +1,55 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package test.test3; + +import static test.test3.Test3.Proto1.Proto1.A; +import static test.test3.Test3.Proto1.Proto1.B; + +import java.io.IOException; +import java.util.concurrent.Future; + +import org.scribble.runtime.message.ObjectStreamFormatter; +import org.scribble.runtime.net.SocketChannelEndpoint; + +import test.test3.Test3.Proto1.Proto1; +import test.test3.Test3.Proto1.callbacks.A.Proto1_A; +import test.test3.Test3.Proto1.callbacks.A.states.Proto1_A_1; + +public class MyA +{ + public static void main(String[] args) throws IOException + { + Proto1 P1 = new Proto1(); + try (Proto1_A aep + = new Proto1_A<>(P1, A, new ObjectStreamFormatter(), new int[1])) + { + aep.request(B, SocketChannelEndpoint::new, "localhost", 8888); + + aep.icallback(Proto1_A_1.id, + x -> (x[0]++ < 3) + ? new Proto1_A_1.B._1(123) + : new Proto1_A_1.B._3("abc") + ); + + Future f = aep.run(); + f.get(); + + System.out.println("(A) end"); + } + catch (Exception e) + { + e.printStackTrace(); + } + } +} diff --git a/scribble-test/src/test/scrib/test/test3/MyB.java b/scribble-test/src/test/scrib/test/test3/MyB.java new file mode 100644 index 000000000..9b893d3e6 --- /dev/null +++ b/scribble-test/src/test/scrib/test/test3/MyB.java @@ -0,0 +1,87 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package test.test3; + +import static test.test3.Test3.Proto1.Proto1.A; +import static test.test3.Test3.Proto1.Proto1.B; +import static test.test3.Test3.Proto1.Proto1.C; + +import java.io.IOException; +import java.util.concurrent.Future; + +import org.scribble.runtime.message.ObjectStreamFormatter; +import org.scribble.runtime.net.ScribServerSocket; +import org.scribble.runtime.net.SocketChannelEndpoint; +import org.scribble.runtime.net.SocketChannelServer; + +import test.test3.Test3.Proto1.Proto1; +import test.test3.Test3.Proto1.callbacks.B.Proto1_B; +import test.test3.Test3.Proto1.callbacks.B.Proto1_B_1_Branch; +import test.test3.Test3.Proto1.callbacks.B.states.Proto1_B_1; +import test.test3.Test3.Proto1.callbacks.B.states.Proto1_B_2; +import test.test3.Test3.Proto1.callbacks.B.states.Proto1_B_3; +import test.test3.Test3.Proto1.ops._1; +import test.test3.Test3.Proto1.ops._3; +import test.test3.Test3.Proto1.roles.A; + +public class MyB +{ + public static void main(String[] args) throws IOException + { + class MyHandler extends Proto1_B_1_Branch + { + @Override + public void receive(int[] data, A peer, _1 op, Integer x) + { + data[0]++; + System.out.println("(B) received 1: " + data[0] + ", " + x); + } + + @Override + public void receive(int[] data, A peer, _3 op, String x) + { + data[0]++; + System.out.println("(B) received 3: " + data[0] + ", " + x); + } + } + + try (ScribServerSocket ss = new SocketChannelServer(8888)) + { + while (true) + { + Proto1 P1 = new Proto1(); + try (Proto1_B b = new Proto1_B<>(P1, B, new ObjectStreamFormatter(), new int[1])) + { + b.accept(ss, A); + b.request(C, SocketChannelEndpoint::new, "localhost", 9999); + + b.icallback(Proto1_B_1.id, new MyHandler()) + .icallback(Proto1_B_2.id, x -> new Proto1_B_2.C._2(456)) + .icallback(Proto1_B_3.id, x -> new Proto1_B_3.C._4("def")); + + //b.icallback(Proto1_B_2.id, x -> new Proto1_B_3.C._4("def")); + + Future f = b.run(); + f.get(); + + System.out.println("(B) end"); + } + catch (Exception e) + { + e.printStackTrace(); + } + } + } + } +} diff --git a/scribble-test/src/test/scrib/test/test3/MyC.java b/scribble-test/src/test/scrib/test/test3/MyC.java new file mode 100644 index 000000000..2ccd7339d --- /dev/null +++ b/scribble-test/src/test/scrib/test/test3/MyC.java @@ -0,0 +1,76 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package test.test3; + +import static test.test3.Test3.Proto1.Proto1.B; +import static test.test3.Test3.Proto1.Proto1.C; + +import java.io.IOException; +import java.util.concurrent.Future; + +import org.scribble.runtime.message.ObjectStreamFormatter; +import org.scribble.runtime.net.ScribServerSocket; +import org.scribble.runtime.net.SocketChannelServer; + +import test.test3.Test3.Proto1.Proto1; +import test.test3.Test3.Proto1.callbacks.C.Proto1_C; +import test.test3.Test3.Proto1.callbacks.C.Proto1_C_1_Branch; +import test.test3.Test3.Proto1.callbacks.C.states.Proto1_C_1; +import test.test3.Test3.Proto1.ops._2; +import test.test3.Test3.Proto1.ops._4; +import test.test3.Test3.Proto1.roles.B; + +public class MyC +{ + public static void main(String[] args) throws IOException + { + class MyHandler extends Proto1_C_1_Branch + { + @Override + public void receive(Void data, B peer, _2 op, Integer x) + { + System.out.println("(C) received 2: " + x); + } + + @Override + public void receive(Void data, B peer, _4 op, String x) + { + System.out.println("(C) received 4: " + x); + } + } + + try (ScribServerSocket ss = new SocketChannelServer(9999)) + { + while (true) + { + Proto1 P1 = new Proto1(); + try (Proto1_C cep = new Proto1_C<>(P1, C, new ObjectStreamFormatter(), null)) + { + cep.accept(ss, B); + + cep.icallback(Proto1_C_1.id, new MyHandler()); + + Future f = cep.run(); + f.get(); + + System.out.println("(C) end"); + } + catch (Exception e) + { + e.printStackTrace(); + } + } + } + } +} diff --git a/scribble-test/src/test/scrib/test/test3/Test3.scr b/scribble-test/src/test/scrib/test/test3/Test3.scr new file mode 100644 index 000000000..ad9e614cb --- /dev/null +++ b/scribble-test/src/test/scrib/test/test3/Test3.scr @@ -0,0 +1,22 @@ +//$ bin/scribblec.sh scribble-test/src/test/scrib/test/test3/Test3.scr -d scribble-test/src/test/scrib/ -cbapi Proto1 A -cbapi Proto1 B -cbapi Proto1 C +//$ javadoc -cp scribble-cli/target/classes/';'scribble-test/target/classes';'scribble-parser/target/classes';'scribble-parser/lib/antlr-3.5.2-complete.jar';'scrib-core/src/test/scrib scrib-core/src/test/scrib/test/test3/Proto1*.java -d test/doc/test3 + +module test.test3.Test3; + +type "java.lang.Integer" from "rt.jar" as Int; +type "java.lang.String" from "rt.jar" as Str; + +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + 1(Int) from A to B; + 2(Int) from B to C; + do Proto1(A, B, C); + } + or + { + 3(Str) from A to B; + 4(Str) from B to C; + } +} diff --git a/scribble-test/src/test/scrib/test/test4/MyA.java b/scribble-test/src/test/scrib/test/test4/MyA.java new file mode 100644 index 000000000..9c5d0e835 --- /dev/null +++ b/scribble-test/src/test/scrib/test/test4/MyA.java @@ -0,0 +1,55 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package test.test4; + +import static test.test4.Test4.Proto1.Proto1.A; +import static test.test4.Test4.Proto1.Proto1.B; + +import java.io.IOException; +import java.util.concurrent.Future; + +import org.scribble.runtime.net.SocketChannelEndpoint; + +import test.test4.Test4.Proto1.Proto1; +import test.test4.Test4.Proto1.callbacks.A.Proto1_A; +import test.test4.Test4.Proto1.callbacks.A.states.Proto1_A_1; +import test.test4.sig.Bar; +import test.test4.sig.Foo; +import test.test4.sig.Test4Formatter;; + +public class MyA +{ + public static void main(String[] args) throws IOException + { + Proto1 P1 = new Proto1(); + try (Proto1_A a = new Proto1_A<>(P1, A, new Test4Formatter(), new int[1])) + { + a.request(B, SocketChannelEndpoint::new, "localhost", 8888); + + a.icallback(Proto1_A_1.id, + x -> (x[0]++ < 5) ? new Proto1_A_1.B.Foo(new Foo("abc" + x[0])) : new Proto1_A_1.B.Bar(new Bar(123)) + ); + // FIXME: "inline" Sig class constructor args directly as Op class constructor args -- maybe by reflection + + Future f = a.run(); + f.get(); + + System.out.println("(A) end"); + } + catch (Exception e) + { + e.printStackTrace(); + } + } +} diff --git a/scribble-test/src/test/scrib/test/test4/MyB.java b/scribble-test/src/test/scrib/test/test4/MyB.java new file mode 100644 index 000000000..98b4490a3 --- /dev/null +++ b/scribble-test/src/test/scrib/test/test4/MyB.java @@ -0,0 +1,78 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package test.test4; + +import static test.test4.Test4.Proto1.Proto1.A; +import static test.test4.Test4.Proto1.Proto1.B; + +import java.io.IOException; +import java.util.concurrent.Future; + +import org.scribble.runtime.net.ScribServerSocket; +import org.scribble.runtime.net.SocketChannelServer; + +import test.test4.Test4.Proto1.Proto1; +import test.test4.Test4.Proto1.callbacks.B.Proto1_B; +import test.test4.Test4.Proto1.callbacks.B.Proto1_B_1_Branch; +import test.test4.Test4.Proto1.callbacks.B.states.Proto1_B_1; +import test.test4.Test4.Proto1.roles.A; +import test.test4.sig.Bar; +import test.test4.sig.Foo; +import test.test4.sig.Test4Formatter; + +public class MyB +{ + public static void main(String[] args) throws IOException + { + class MyHandler extends Proto1_B_1_Branch + { + @Override + public void receive(int[] data, A peer, Foo m) + { + data[0]++; + System.out.println("(B) received Foo: " + m.getBody() + ", " + data[0]); + } + + @Override + public void receive(int[] data, A peer, Bar m) + { + data[0]++; + System.out.println("(B) received Bar: " + m.getBody() + ", " + data[0]); + } + } + + try (ScribServerSocket ss = new SocketChannelServer(8888)) + { + while (true) + { + Proto1 P1 = new Proto1(); + try (Proto1_B b = new Proto1_B<>(P1, B, new Test4Formatter(), new int[1])) + { + b.accept(ss, A); + + b.icallback(Proto1_B_1.id, new MyHandler()); + + Future f = b.run(); + f.get(); + + System.out.println("(B) end"); + } + catch (Exception e) + { + e.printStackTrace(); + } + } + } + } +} diff --git a/scribble-test/src/test/scrib/test/test4/Test4.scr b/scribble-test/src/test/scrib/test/test4/Test4.scr new file mode 100644 index 000000000..2c729455a --- /dev/null +++ b/scribble-test/src/test/scrib/test/test4/Test4.scr @@ -0,0 +1,20 @@ +//$ bin/scribblec.sh scribble-test/src/test/scrib/test/test4/Test4.scr -d scribble-test/src/test/scrib/ -cbapi Proto1 A -cbapi Proto1 B +//$ javadoc -cp scribble-cli/target/classes/';'scribble-test/target/classes';'scribble-parser/target/classes';'scribble-parser/lib/antlr-3.5.2-complete.jar';'scrib-core/src/test/scrib scrib-core/src/test/scrib/test/test4/Proto1*.java -d test/doc/test4 + +module test.test4.Test4; + +sig "test.test4.sig.Foo" from "test/test4/sig/Foo.java" as Foo; +sig "test.test4.sig.Bar" from "test/test4/sig/Bar.java" as Bar; + +global protocol Proto1(role A, role B) +{ + choice at A + { + Foo from A to B; + do Proto1(A, B); + } + or + { + Bar from A to B; + } +} diff --git a/scribble-test/src/test/scrib/test/test4/sig/Bar.java b/scribble-test/src/test/scrib/test/test4/sig/Bar.java new file mode 100644 index 000000000..717a2e36c --- /dev/null +++ b/scribble-test/src/test/scrib/test/test4/sig/Bar.java @@ -0,0 +1,32 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package test.test4.sig; + +import test.test4.Test4.Proto1.Proto1; + +public class Bar extends Test4Message +{ + private static final long serialVersionUID = 1L; + + public Bar(int body) + { + super(Proto1.Bar, body); + } + + @Override + public Integer getBody() + { + return (Integer) this.payload[0]; + } +} diff --git a/scribble-test/src/test/scrib/test/test4/sig/Foo.java b/scribble-test/src/test/scrib/test/test4/sig/Foo.java new file mode 100644 index 000000000..bd52d0700 --- /dev/null +++ b/scribble-test/src/test/scrib/test/test4/sig/Foo.java @@ -0,0 +1,32 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package test.test4.sig; + +import test.test4.Test4.Proto1.Proto1; + +public class Foo extends Test4Message +{ + private static final long serialVersionUID = 1L; + + public Foo(String body) + { + super(Proto1.Foo, body); + } + + @Override + public String getBody() + { + return (String) this.payload[0]; + } +} diff --git a/scribble-test/src/test/scrib/test/test4/sig/Test4Formatter.java b/scribble-test/src/test/scrib/test/test4/sig/Test4Formatter.java new file mode 100644 index 000000000..603c62acd --- /dev/null +++ b/scribble-test/src/test/scrib/test/test4/sig/Test4Formatter.java @@ -0,0 +1,109 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package test.test4.sig; + +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.Charset; + +import org.scribble.runtime.message.ScribMessage; +import org.scribble.runtime.message.ScribMessageFormatter; + +public class Test4Formatter implements ScribMessageFormatter +{ + public static Charset cs = Charset.forName("UTF8"); + + public Test4Formatter() + { + + } + + @Override + public byte[] toBytes(ScribMessage m) throws IOException + { + return ((Test4Message) m).toBytes(); + } + + @Override + public ScribMessage fromBytes(ByteBuffer bb) throws IOException, ClassNotFoundException + { + bb.flip(); + int rem = bb.remaining(); + if (rem < 3) + { + bb.compact(); + return null; + } + + int pos = bb.position(); + String m = new String(new byte[] { bb.get(pos), bb.get(pos + 1), bb.get(pos + 2) }, Test4Formatter.cs); + switch (m) + { + case "Foo": + { + String body = readLine(bb, pos + 3).trim(); // Whitespace already built into the message classes + bb.compact(); + if (body == null) + { + return null; + } + return new Foo(body); + } + case "Bar": + { + String body = readLine(bb, pos + 3).trim(); // Whitespace already built into the message classes + bb.compact(); + if (body == null) + { + return null; + } + return new Bar(Integer.parseInt(body)); + } + default: throw new RuntimeException("Deserialization error: " + m); + } + } + + private static String readLine(ByteBuffer bb, int i) throws IOException + { + StringBuilder sb = new StringBuilder(); + for (int limit = bb.limit(); i <= limit; ) + { + char c = (char) bb.get(i++); + sb.append(c); + if (c == '\n') + { + bb.position(i); + return sb.substring(0, sb.length() - 1).toString(); + } + } + return null; + } + + + @Deprecated + @Override + public void writeMessage(DataOutputStream dos, ScribMessage m) throws IOException + { + throw new RuntimeException("Deprecated: " + m); + } + + @Deprecated + @Override + public Test4Message readMessage(DataInputStream dis) throws IOException + { + throw new RuntimeException("Deprecated: "); + } +} diff --git a/scribble-test/src/test/scrib/test/test4/sig/Test4Message.java b/scribble-test/src/test/scrib/test/test4/sig/Test4Message.java new file mode 100644 index 000000000..d430b679c --- /dev/null +++ b/scribble-test/src/test/scrib/test/test4/sig/Test4Message.java @@ -0,0 +1,47 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package test.test4.sig; + +import org.scribble.runtime.message.ScribMessage; +import org.scribble.type.name.Op; + +public abstract class Test4Message extends ScribMessage +{ + private static final long serialVersionUID = 1L; + + /*public Test4Message(Op op) + { + super(op); + }*/ + + public Test4Message(Op op, Object body) + { + super(op, body); + } + + public abstract Object getBody(); + + public byte[] toBytes() + { + // op is 3-char header (Foo/Bar) + byte[] bs = (this.op.toString() + getBody() + "\n").getBytes(Test4Formatter.cs); + return bs; + } + + @Override + public String toString() + { + return new String(toBytes()); + } +} diff --git a/scribble-test/src/test/scrib/test/test5/MyA.java b/scribble-test/src/test/scrib/test/test5/MyA.java new file mode 100644 index 000000000..7492cdfb4 --- /dev/null +++ b/scribble-test/src/test/scrib/test/test5/MyA.java @@ -0,0 +1,56 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package test.test5; + +import static test.test5.Test5.Proto1.Proto1.A; +import static test.test5.Test5.Proto1.Proto1.B; +import static test.test5.Test5.Proto1.Proto1.C; + +import java.io.IOException; +import java.util.concurrent.Future; + +import org.scribble.runtime.message.ObjectStreamFormatter; +import org.scribble.runtime.net.SocketChannelEndpoint; + +import test.test5.Test5.Proto1.Proto1; +import test.test5.Test5.Proto1.callbacks.A.Proto1_A; +import test.test5.Test5.Proto1.callbacks.A.states.Proto1_A_1; +import test.test5.Test5.Proto1.callbacks.A.states.Proto1_A_2; +import test.test5.Test5.Proto1.callbacks.A.states.Proto1_A_3; + +public class MyA +{ + public static void main(String[] args) throws IOException + { + Proto1 P1 = new Proto1(); + try (Proto1_A a = new Proto1_A<>(P1, A, new ObjectStreamFormatter(), new int[1])) + { + a.request(B, SocketChannelEndpoint::new, "localhost", 8888); + a.request(C, SocketChannelEndpoint::new, "localhost", 9999); + + a.icallback(Proto1_A_1.id, x -> (x[0]++ < 3) ? new Proto1_A_1.B._1(123) : new Proto1_A_1.C._3("abc")) + .icallback(Proto1_A_2.id, x -> new Proto1_A_2.C._2(456)) + .icallback(Proto1_A_3.id, x -> new Proto1_A_3.B._4("def")); + + Future f = a.run(); + f.get(); + + System.out.println("(A) end"); + } + catch (Exception e) + { + e.printStackTrace(); + } + } +} diff --git a/scribble-test/src/test/scrib/test/test5/MyB.java b/scribble-test/src/test/scrib/test/test5/MyB.java new file mode 100644 index 000000000..fa72ab187 --- /dev/null +++ b/scribble-test/src/test/scrib/test/test5/MyB.java @@ -0,0 +1,78 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package test.test5; + +import static test.test5.Test5.Proto1.Proto1.A; +import static test.test5.Test5.Proto1.Proto1.B; + +import java.io.IOException; +import java.util.concurrent.Future; + +import org.scribble.runtime.message.ObjectStreamFormatter; +import org.scribble.runtime.net.ScribServerSocket; +import org.scribble.runtime.net.SocketChannelServer; + +import test.test5.Test5.Proto1.Proto1; +import test.test5.Test5.Proto1.callbacks.B.Proto1_B; +import test.test5.Test5.Proto1.callbacks.B.Proto1_B_1_Branch; +import test.test5.Test5.Proto1.callbacks.B.states.Proto1_B_1; +import test.test5.Test5.Proto1.ops._1; +import test.test5.Test5.Proto1.ops._4; +import test.test5.Test5.Proto1.roles.A; + +public class MyB +{ + public static void main(String[] args) throws IOException + { + class MyHandler extends Proto1_B_1_Branch + { + @Override + public void receive(int[] data, A peer, _1 op, Integer x) + { + data[0]++; + System.out.println("(B) received 1: " + data[0] + ", " + x); + } + + @Override + public void receive(int[] data, A peer, _4 op, String x) + { + data[0]++; + System.out.println("(B) received 4: " + data[0] + ", " + x); + } + } + + try (ScribServerSocket ss = new SocketChannelServer(8888)) + { + while (true) + { + Proto1 P1 = new Proto1(); + try (Proto1_B b = new Proto1_B<>(P1, B, new ObjectStreamFormatter(), new int[1])) + { + b.accept(ss, A); + + b.icallback(Proto1_B_1.id, new MyHandler()); + + Future f = b.run(); + f.get(); + + System.out.println("(B) end"); + } + catch (Exception e) + { + e.printStackTrace(); + } + } + } + } +} diff --git a/scribble-test/src/test/scrib/test/test5/MyC.java b/scribble-test/src/test/scrib/test/test5/MyC.java new file mode 100644 index 000000000..e3bb9d01b --- /dev/null +++ b/scribble-test/src/test/scrib/test/test5/MyC.java @@ -0,0 +1,76 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package test.test5; + +import static test.test5.Test5.Proto1.Proto1.A; +import static test.test5.Test5.Proto1.Proto1.C; + +import java.io.IOException; +import java.util.concurrent.Future; + +import org.scribble.runtime.message.ObjectStreamFormatter; +import org.scribble.runtime.net.ScribServerSocket; +import org.scribble.runtime.net.SocketChannelServer; + +import test.test5.Test5.Proto1.Proto1; +import test.test5.Test5.Proto1.callbacks.C.Proto1_C; +import test.test5.Test5.Proto1.callbacks.C.Proto1_C_1_Branch; +import test.test5.Test5.Proto1.callbacks.C.states.Proto1_C_1; +import test.test5.Test5.Proto1.ops._2; +import test.test5.Test5.Proto1.ops._3; +import test.test5.Test5.Proto1.roles.A; + +public class MyC +{ + public static void main(String[] args) throws IOException + { + class MyHandler extends Proto1_C_1_Branch + { + @Override + public void receive(Void data, A peer, _2 op, Integer x) + { + System.out.println("(C) received 2: " + x); + } + + @Override + public void receive(Void data, A peer, _3 op, String x) + { + System.out.println("(C) received 4: " + x); + } + } + + try (ScribServerSocket ss = new SocketChannelServer(9999)) + { + while (true) + { + Proto1 P1 = new Proto1(); + try (Proto1_C b = new Proto1_C<>(P1, C, new ObjectStreamFormatter(), null)) + { + b.accept(ss, A); + + b.icallback(Proto1_C_1.id, new MyHandler()); + + Future f = b.run(); + f.get(); + + System.out.println("(C) end"); + } + catch (Exception e) + { + e.printStackTrace(); + } + } + } + } +} diff --git a/scribble-test/src/test/scrib/test/test5/Test5.scr b/scribble-test/src/test/scrib/test/test5/Test5.scr new file mode 100644 index 000000000..79b33211d --- /dev/null +++ b/scribble-test/src/test/scrib/test/test5/Test5.scr @@ -0,0 +1,22 @@ +//$ bin/scribblec.sh scribble-test/src/test/scrib/test/test5/Test5.scr -d scribble-test/src/test/scrib/ -cbapi Proto1 A -cbapi Proto1 B -cbapi Proto1 C +//$ javadoc -cp scribble-cli/target/classes/';'scribble-test/target/classes';'scribble-parser/target/classes';'scribble-parser/lib/antlr-3.5.2-complete.jar';'scrib-core/src/test/scrib scrib-core/src/test/scrib/test/test5/Proto1*.java -d test/doc/test5 + +module test.test5.Test5; + +type "java.lang.Integer" from "rt.jar" as Int; +type "java.lang.String" from "rt.jar" as Str; + +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + 1(Int) from A to B; + 2(Int) from A to C; + do Proto1(A, B, C); + } + or + { + 3(Str) from A to C; + 4(Str) from A to B; + } +} diff --git a/scribble-test/src/test/scrib/test/test6/MyA.java b/scribble-test/src/test/scrib/test/test6/MyA.java new file mode 100644 index 000000000..ba94cedd7 --- /dev/null +++ b/scribble-test/src/test/scrib/test/test6/MyA.java @@ -0,0 +1,72 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package test.test6; + +import static test.test6.Test6.Proto1.Proto1.A; +import static test.test6.Test6.Proto1.Proto1.B; + +import java.io.IOException; +import java.util.concurrent.Future; +import java.util.function.Function; + +import org.scribble.runtime.message.ObjectStreamFormatter; +import org.scribble.runtime.net.SocketChannelEndpoint; + +import test.test6.Test6.Proto1.Proto1; +import test.test6.Test6.Proto1.callbacks.A.Proto1_A; +import test.test6.Test6.Proto1.callbacks.A.Proto1_A_2_Branch; +import test.test6.Test6.Proto1.callbacks.A.states.Proto1_A_1; +import test.test6.Test6.Proto1.callbacks.A.states.Proto1_A_2; +import test.test6.Test6.Proto1.callbacks.A.states.Proto1_A_3; +import test.test6.Test6.Proto1.callbacks.A.states.Proto1_A_4; +import test.test6.Test6.Proto1.ops._2; +import test.test6.Test6.Proto1.roles.B;; + +public class MyA +{ + public static void main(String[] args) throws IOException + { + class MyHandler extends Proto1_A_2_Branch + { + @Override + public void receive(int[] data, B peer, _2 op, String arg1) + { + System.out.println("(A) received 2: " + arg1 + ", " + data[0]++); + } + } + + Proto1 P1 = new Proto1(); + try (Proto1_A a = new Proto1_A<>(P1, A, new ObjectStreamFormatter(), new int[1])) + { + a.request(B, SocketChannelEndpoint::new, "localhost", 8888); + + Function h1 = x -> new Proto1_A_1.B._1(x[0]++); + MyHandler h2 = new MyHandler(); + + a.icallback(Proto1_A_1.id, h1) + .icallback(Proto1_A_2.id, h2) + .icallback(Proto1_A_3.id, h1) + .icallback(Proto1_A_4.id, h2); + + Future f = a.run(); + f.get(); + + System.out.println("(A) end"); + } + catch (Exception e) + { + e.printStackTrace(); + } + } +} diff --git a/scribble-test/src/test/scrib/test/test6/MyB.java b/scribble-test/src/test/scrib/test/test6/MyB.java new file mode 100644 index 000000000..029b3ab2a --- /dev/null +++ b/scribble-test/src/test/scrib/test/test6/MyB.java @@ -0,0 +1,79 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package test.test6; + +import static test.test6.Test6.Proto1.Proto1.A; +import static test.test6.Test6.Proto1.Proto1.B; + +import java.io.IOException; +import java.util.concurrent.Future; +import java.util.function.Function; + +import org.scribble.runtime.message.ObjectStreamFormatter; +import org.scribble.runtime.net.ScribServerSocket; +import org.scribble.runtime.net.SocketChannelServer; + +import test.test6.Test6.Proto1.Proto1; +import test.test6.Test6.Proto1.callbacks.B.Proto1_B; +import test.test6.Test6.Proto1.callbacks.B.Proto1_B_3_Branch; +import test.test6.Test6.Proto1.callbacks.B.states.Proto1_B_1; +import test.test6.Test6.Proto1.callbacks.B.states.Proto1_B_2; +import test.test6.Test6.Proto1.callbacks.B.states.Proto1_B_3; +import test.test6.Test6.Proto1.callbacks.B.states.Proto1_B_4; + +public class MyB +{ + public static void main(String[] args) throws IOException + { + class MyHandler extends Proto1_B_3_Branch + { + @Override + public void receive(String[] data, test.test6.Test6.Proto1.roles.A peer, test.test6.Test6.Proto1.ops._1 op, Integer arg1) + { + System.out.println("(B) received 1: " + arg1 + ", " + (data[0] += "a")); + + } + } + + try (ScribServerSocket ss = new SocketChannelServer(8888)) + { + while (true) + { + Proto1 P1 = new Proto1(); + String[] data = new String[] { "" }; + try (Proto1_B b = new Proto1_B<>(P1, B, new ObjectStreamFormatter(), data)) + { + b.accept(ss, A); + + MyHandler h1 = new MyHandler(); + Function h2 = x -> new Proto1_B_4.A._2(x[0] += "a"); + + b.icallback(Proto1_B_1.id, h1) + .icallback(Proto1_B_2.id, h2) + .icallback(Proto1_B_3.id, h1) + .icallback(Proto1_B_4.id, h2); + + Future f = b.run(); + f.get(); + + System.out.println("(B) end"); + } + catch (Exception e) + { + e.printStackTrace(); + } + } + } + } +} diff --git a/scribble-test/src/test/scrib/test/test6/Test6.scr b/scribble-test/src/test/scrib/test/test6/Test6.scr new file mode 100644 index 000000000..e375d4651 --- /dev/null +++ b/scribble-test/src/test/scrib/test/test6/Test6.scr @@ -0,0 +1,15 @@ +//$ bin/scribblec.sh scribble-test/src/test/scrib/test/test6/Test6.scr -d scribble-test/src/test/scrib/ -cbapi Proto1 A -cbapi Proto1 B +//$ javadoc -cp scribble-cli/target/classes/';'scribble-test/target/classes';'scribble-parser/target/classes';'scribble-parser/lib/antlr-3.5.2-complete.jar';'scrib-core/src/test/scrib scrib-core/src/test/scrib/test/test6/Proto1*.java -d test/doc/test6 + +module test.test6.Test6; + +type "java.lang.Integer" from "rt.jar" as Int; +type "java.lang.String" from "rt.jar" as Str; + +global protocol Proto1(role A, role B) +{ + 1(Int) from A to B; + 2(Str) from B to A; + 1(Int) from A to B; + 2(Str) from B to A; +} diff --git a/scribble-test/src/test/scrib/test/test7/MyA.java b/scribble-test/src/test/scrib/test/test7/MyA.java new file mode 100644 index 000000000..8358ae5da --- /dev/null +++ b/scribble-test/src/test/scrib/test/test7/MyA.java @@ -0,0 +1,56 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package test.test7; + +import static test.test7.Test7.Proto1.Proto1.A; +import static test.test7.Test7.Proto1.Proto1.B; + +import java.io.IOException; +import java.util.concurrent.Future; +import java.util.function.Function; + +import org.scribble.runtime.message.ObjectStreamFormatter; +import org.scribble.runtime.net.SocketChannelEndpoint; + +import test.test7.Test7.Proto1.Proto1; +import test.test7.Test7.Proto1.callbacks.A.Proto1_A; +import test.test7.Test7.Proto1.callbacks.A.states.Proto1_A_1; +import test.test7.Test7.Proto1.callbacks.A.states.Proto1_A_2; + +public class MyA +{ + public static void main(String[] args) throws IOException + { + Proto1 P1 = new Proto1(); + String[] data = new String[] { "" }; + try (Proto1_A a = new Proto1_A<>(P1, A, new ObjectStreamFormatter(), data)) + { + a.request(B, SocketChannelEndpoint::new, "localhost", 8888); + + Function h = x -> new Proto1_A_1.B._2((x[0] += "a")); + + a.icallback(Proto1_A_1.id, h) + .icallback(Proto1_A_2.id, h); + + Future f = a.run(); + f.get(); + + System.out.println("(A) end"); + } + catch (Exception e) + { + e.printStackTrace(); + } + } +} diff --git a/scribble-test/src/test/scrib/test/test7/MyB.java b/scribble-test/src/test/scrib/test/test7/MyB.java new file mode 100644 index 000000000..65afb87d4 --- /dev/null +++ b/scribble-test/src/test/scrib/test/test7/MyB.java @@ -0,0 +1,79 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package test.test7; + +import static test.test7.Test7.Proto1.Proto1.A; +import static test.test7.Test7.Proto1.Proto1.B; + +import java.io.IOException; +import java.util.concurrent.Future; + +import org.scribble.runtime.message.ObjectStreamFormatter; +import org.scribble.runtime.net.ScribServerSocket; +import org.scribble.runtime.net.SocketChannelServer; + +import test.test7.Test7.Proto1.Proto1; +import test.test7.Test7.Proto1.callbacks.B.Proto1_B; +import test.test7.Test7.Proto1.callbacks.B.Proto1_B_1_Branch; +import test.test7.Test7.Proto1.callbacks.B.states.Proto1_B_1; +import test.test7.Test7.Proto1.callbacks.B.states.Proto1_B_2; +import test.test7.Test7.Proto1.ops._1; +import test.test7.Test7.Proto1.ops._2; +import test.test7.Test7.Proto1.roles.A; + +public class MyB +{ + public static void main(String[] args) throws IOException + { + class MyHandler extends Proto1_B_1_Branch + { + @Override + public void receive(int[] data, A peer, _1 op, Integer arg1) + { + System.out.println("(B) received 1: " + arg1 + ", " + data[0]++); + } + + @Override + public void receive(int[] data, A peer, _2 op, String arg1) + { + System.out.println("(B) received 1: " + arg1 + ", " + data[0]++); + } + } + + try (ScribServerSocket ss = new SocketChannelServer(8888)) + { + while (true) + { + Proto1 P1 = new Proto1(); + try (Proto1_B b = new Proto1_B<>(P1, B, new ObjectStreamFormatter(), new int[1])) + { + b.accept(ss, A); + + MyHandler h = new MyHandler(); + b.icallback(Proto1_B_1.id, h) + .icallback(Proto1_B_2.id, h); + + Future f = b.run(); + f.get(); + + System.out.println("(B) end"); + } + catch (Exception e) + { + e.printStackTrace(); + } + } + } + } +} diff --git a/scribble-test/src/test/scrib/test/test7/Test7.scr b/scribble-test/src/test/scrib/test/test7/Test7.scr new file mode 100644 index 000000000..197730008 --- /dev/null +++ b/scribble-test/src/test/scrib/test/test7/Test7.scr @@ -0,0 +1,27 @@ +//$ bin/scribblec.sh scribble-test/src/test/scrib/test/test7/Test7.scr -d scribble-test/src/test/scrib/ -cbapi Proto1 A -cbapi Proto1 B +//$ javadoc -cp scribble-cli/target/classes/';'scribble-test/target/classes';'scribble-parser/target/classes';'scribble-parser/lib/antlr-3.5.2-complete.jar';'scrib-core/src/test/scrib scrib-core/src/test/scrib/test/test7/Proto1*.java -d test/doc/test7 + +module test.test7.Test7; + +type "java.lang.Integer" from "rt.jar" as Int; +type "java.lang.String" from "rt.jar" as Str; + +global protocol Proto1(role A, role B) +{ + choice at A + { + 1(Int) from A to B; + } + or + { + 2(Str) from A to B; + } + choice at A + { + 1(Int) from A to B; + } + or + { + 2(Str) from A to B; + } +} diff --git a/scribble-test/src/test/scrib/test/test8/MyA.java b/scribble-test/src/test/scrib/test/test8/MyA.java new file mode 100644 index 000000000..ff54d0a73 --- /dev/null +++ b/scribble-test/src/test/scrib/test/test8/MyA.java @@ -0,0 +1,80 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package test.test8; + +import static test.test8.Test8.Proto1.Proto1.A; +import static test.test8.Test8.Proto1.Proto1.B; +import static test.test8.Test8.Proto1.Proto1.C; + +import java.io.IOException; +import java.util.concurrent.Future; + +import org.scribble.runtime.message.ObjectStreamFormatter; +import org.scribble.runtime.net.SocketChannelEndpoint; + +import test.test8.Test8.Proto1.Proto1; +import test.test8.Test8.Proto1.callbacks.A.Proto1_A; +import test.test8.Test8.Proto1.callbacks.A.states.Proto1_A_1; +import test.test8.Test8.Proto1.callbacks.A.states.Proto1_A_2; +import test.test8.Test8.Proto1.callbacks.A.states.Proto1_A_3; +import test.test8.Test8.Proto1.callbacks.A.states.Proto1_A_4; +import test.test8.Test8.Proto1.callbacks.A.states.Proto1_A_5; + +public class MyA +{ + public static void main(String[] args) throws IOException + { + foo(); + } + + public static void foo() throws IOException + { + Proto1 P1 = new Proto1(); + try (Proto1_A a = new Proto1_A<>(P1, A, new ObjectStreamFormatter(), new int[] { 0 })) + { + a.request(B, SocketChannelEndpoint::new, "localhost", 8888); + a.request(C, SocketChannelEndpoint::new, "localhost", 9999); + + a.icallback(Proto1_A_1.id, + x -> (x[0]++ < 3) ? new Proto1_A_1.B._1(x[0]) : new Proto1_A_1.C._4("abc") + ); + a.icallback(Proto1_A_2.id, x -> new Proto1_A_2.B._1(123)); + a.icallback(Proto1_A_3.id, x -> new Proto1_A_3.C._3()); + a.icallback(Proto1_A_4.id, x -> new Proto1_A_4.B._3(456)); + a.icallback(Proto1_A_5.id, x -> new Proto1_A_5.B._4("def")); + + /*a.callback(Proto1_A_1.id, x -> new Proto1_A_1.B._1("abc")); + a.callback(Proto1_A_1.id, x -> new Proto1_A_1.B._2(123)); + a.callback(Proto1_A_1.id, x -> new Proto1_A_1.C._1(123)); + a.callback(Proto1_A_1.id, x -> new Proto1_A_5.B._4("def")); + + a.icallback(Proto1_A_1.id, x -> new Proto1_A_1.B._1("abc")); + a.icallback(Proto1_A_1.id, x -> new Proto1_A_1.B._2(123)); + a.icallback(Proto1_A_1.id, x -> new Proto1_A_1.C._1(123)); + a.icallback(Proto1_A_1.id, x -> new Proto1_A_5.B._4("def"));*/ + + //a.callback(Proto1_A_2.id, x -> new Proto1_A_1.B._1(123)); + a.icallback(Proto1_A_2.id, x -> new Proto1_A_1.B._1(123)); + + Future f = a.run(); + f.get(); + + System.out.println("(A) end"); + } + catch (Exception e) + { + e.printStackTrace(); + } + } +} diff --git a/scribble-test/src/test/scrib/test/test8/MyB.java b/scribble-test/src/test/scrib/test/test8/MyB.java new file mode 100644 index 000000000..1cc3c9561 --- /dev/null +++ b/scribble-test/src/test/scrib/test/test8/MyB.java @@ -0,0 +1,92 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package test.test8; + +import static test.test8.Test8.Proto1.Proto1.A; +import static test.test8.Test8.Proto1.Proto1.B; + +import java.io.IOException; +import java.util.concurrent.Future; + +import org.scribble.runtime.message.ObjectStreamFormatter; +import org.scribble.runtime.net.ScribServerSocket; +import org.scribble.runtime.net.SocketChannelServer; + +import test.test8.Test8.Proto1.Proto1; +import test.test8.Test8.Proto1.callbacks.B.Proto1_B; +import test.test8.Test8.Proto1.callbacks.B.Proto1_B_1_Branch; +import test.test8.Test8.Proto1.callbacks.B.states.Proto1_B_1; +import test.test8.Test8.Proto1.callbacks.B.states.Proto1_B_2; +import test.test8.Test8.Proto1.ops._1; +import test.test8.Test8.Proto1.ops._3; +import test.test8.Test8.Proto1.ops._4; +import test.test8.Test8.Proto1.roles.A; + +public class MyB +{ + public static void main(String[] args) throws IOException + { + foo(); + } + + public static void foo() throws IOException + { + class MyHandler extends Proto1_B_1_Branch + { + @Override + public void receive(Void data, A peer, _1 op, Integer arg1) + { + System.out.println("(B) received 1: " + arg1); + } + + @Override + public void receive(Void data, A peer, _3 op, Integer arg1) + { + System.out.println("(B) received 3: " + arg1); + } + + @Override + public void receive(Void data, A peer, _4 op, String arg1) + { + System.out.println("(B) received 4: " + arg1); + } + } + + try (ScribServerSocket ss = new SocketChannelServer(8888)) + { + while (true) + { + Proto1 P1 = new Proto1(); + try (Proto1_B b = new Proto1_B<>(P1, B, new ObjectStreamFormatter(), null)) + { + b.accept(ss, A); + + MyHandler h = new MyHandler(); + b.icallback(Proto1_B_1.id, h); + //b.callback(Proto1_B_2.id, h); + b.icallback(Proto1_B_2.id, h); + + Future f = b.run(); + f.get(); + + System.out.println("(B) end"); + } + catch (Exception e) + { + e.printStackTrace(); + } + } + } + } +} diff --git a/scribble-test/src/test/scrib/test/test8/MyC.java b/scribble-test/src/test/scrib/test/test8/MyC.java new file mode 100644 index 000000000..2984de63d --- /dev/null +++ b/scribble-test/src/test/scrib/test/test8/MyC.java @@ -0,0 +1,89 @@ +/** + * Copyright 2008 The Scribble 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 + * + * http://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. + */ +package test.test8; + +import static test.test8.Test8.Proto1.Proto1.A; +import static test.test8.Test8.Proto1.Proto1.C; + +import java.io.IOException; +import java.util.concurrent.Future; + +import org.scribble.runtime.message.ObjectStreamFormatter; +import org.scribble.runtime.net.ScribServerSocket; +import org.scribble.runtime.net.SocketChannelServer; + +import test.test8.Test8.Proto1.Proto1; +import test.test8.Test8.Proto1.callbacks.C.Proto1_C; +import test.test8.Test8.Proto1.callbacks.C.Proto1_C_1_Branch; +import test.test8.Test8.Proto1.callbacks.C.states.Proto1_C_1; +import test.test8.Test8.Proto1.ops._2; +import test.test8.Test8.Proto1.ops._3; +import test.test8.Test8.Proto1.ops._4; +import test.test8.Test8.Proto1.roles.A; + +public class MyC +{ + public static void main(String[] args) throws IOException + { + foo(); + } + + public static void foo() throws IOException + { + class MyHandler extends Proto1_C_1_Branch + { + @Override + public void receive(Void data, A peer, _3 op) + { + System.out.println("(C) received 3: "); + } + + @Override + public void receive(Void data, A peer, _2 op, Integer arg1) + { + System.out.println("(C) received 2: " + arg1); + } + + @Override + public void receive(Void data, A peer, _4 op, String arg1) + { + System.out.println("(C) received 4: " + arg1); + } + } + + try (ScribServerSocket ss = new SocketChannelServer(9999)) + { + while (true) + { + Proto1 P1 = new Proto1(); + try (Proto1_C b = new Proto1_C<>(P1, C, new ObjectStreamFormatter(), null)) + { + b.accept(ss, A); + + MyHandler h = new MyHandler(); + b.icallback(Proto1_C_1.id, h); + + Future f = b.run(); + f.get(); + + System.out.println("(C) end"); + } + catch (Exception e) + { + e.printStackTrace(); + } + } + } + } +} diff --git a/scribble-test/src/test/scrib/test/test8/Test8.scr b/scribble-test/src/test/scrib/test/test8/Test8.scr new file mode 100644 index 000000000..0f77b4e3d --- /dev/null +++ b/scribble-test/src/test/scrib/test/test8/Test8.scr @@ -0,0 +1,28 @@ +//$ bin/scribblec.sh scribble-test/src/test/scrib/test/test8/Test8.scr -d scribble-test/src/test/scrib/ -cbapi Proto1 A -cbapi Proto1 B -cbapi Proto1 C +//$ javadoc -cp scribble-cli/target/classes/';'scribble-test/target/classes';'scribble-parser/target/classes';'scribble-parser/lib/antlr-3.5.2-complete.jar';'scrib-core/src/test/scrib scrib-core/src/test/scrib/test/test8/Proto1*.java -d test/doc/test8 + +module test.test8.Test8; + +type "java.lang.Integer" from "rt.jar" as Int; +type "java.lang.String" from "rt.jar" as Str; + +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + 1(Int) from A to B; + 1(Int) from A to B; + 3() from A to C; + //1(Int) from A to C; + } + or + { + 2(Int) from A to C; + 3(Int) from A to B; + } + or + { + 4(Str) from A to C; + 4(Str) from A to B; + } +} diff --git a/scribble-test/src/test/scrib/tmp/Betty.scr b/scribble-test/src/test/scrib/tmp/Betty.scr new file mode 100644 index 000000000..9ae24dbc8 --- /dev/null +++ b/scribble-test/src/test/scrib/tmp/Betty.scr @@ -0,0 +1,362 @@ +module Betty; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +/* +type "test.nego.SAP" from "test/nego/SAP.java" as SAP; + +global protocol Negotiate(role C, role P) { + propose(SAP) from C to P; + rec X { + choice at P { + accpt() from P to C; + confirm() from C to P; + } or { + reject() from P to C; + } or { + propose(SAP) from P to C; + choice at C { + accpt() from C to P; + confirm() from P to C; + } or { + reject() from C to P; + } or { + propose(SAP) from C to P; + continue X; + } + } + } +} +//*/ + + +/* +type "java.lang.Integer" from "rt.jar" as Int; +type "java.lang.String" from "rt.jar" as String; + +global protocol Proto1(role A, role B) { + 123(Int, String) from A to B; +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) { + choice at A { + 1() from A to B; + 2() from A to C; + } or { + 3() from A to B; + 4() from A to C; + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) { + choice at A { + 1() from A to B; + 2() from A to C; + } or { + 4() from A to C; + 3() from A to B; + } +} +//*/ + + +/* +type "java.lang.Integer" from "rt.jar" as Int; + +global protocol Proto1(role A, role B, role C) { + choice at A { + buyer1(Int) from A to B; // Total + (Int) from B to A; // B will pay this much + buyer2(Int) from A to C; // C will pay remainder + } or { + buyer1(Int) from A to C; // Total + (Int) from C to A; // C will pay this much + buyer2(Int) from A to B; // B will pay remainder + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) { + choice at A { + 1() from A to B; + 1() from B to C; + } or { + //2() from A to B; + 2() from B to A; + choice at B { + 3() from B to C; + } or { + 4() from B to C; + } + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) { + choice at A { + 1() from A to B; + 3() from B to C; + 4() from C to A; + } or { + 2() from A to B; + 3() from B to C; + 5() from C to A; + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) { + choice at A { + 1() from A to B; + 3() from B to C; + 4() from C to A; + } or { + 2() from A to B; + 3() from B to C; + 4() from C to A; + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) { + choice at A { + 1() from A to B; + 3() from B to C; + do Merge(A, C); + } or { + 2() from A to B; + 3() from B to C; + do Merge(A, C); + } +} + +aux global protocol Merge(role A, role C) { + 4() from A to C; +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) { + choice at A { + 1() from A to B; + 3() from B to C; + do Merge(A, C); + } or { + 2() from A to B; + 3() from B to C; + do Merge(A, C); + } +} + +aux global protocol Merge(role A, role C) { + 4() from C to A; +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) { + choice at A { + 1() from A to B; + 3() from B to C; + do Merge(A, C); + } or { + 2() from A to B; + 3() from B to C; + do Merge(A, C); + } +} + +aux global protocol Merge(role A, role C) { + choice at A { + 4() from A to C; + } or { + 5() from A to C; + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) { + choice at A { + 1() from A to B; + 2() from A to C; + 3() from B to C; + 4() from C to A; + } or { + 1b() from A to B; + 3() from B to C; // -nolocalchoicecheck to show orphans + 4() from C to A; + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) { + choice at A { + 1() from A to B; + 2() from A to C; + } or { + 3() from A to B; + } +} +//*/ + + +/* +global protocol Proto1(role A, role B) { + rec X { + choice at A { + 1() from A to B; + continue X; + 2() from A to B; + } or { + 3() from A to B; + } + 4() from A to B; + } + 5() from A to B; +} +//*/ + + +/* +global protocol Proto1(role A, role B) { + rec X { + 1() from A to B; + continue X; + } + 2() from A to B; +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C, role D) { + rec X { + 1() from A to B; + continue X; + } + 2() from C to D; +} +//*/ + + +/* +global protocol Proto1(role A, role B) { + rec X { + choice at A { + 1() from A to B; + continue X; + } or { + 1() from A to B; + } + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) { + choice at A { + rec X { + 1() from A to B; + 1() from B to C; + continue X; + } + } or { + 2() from A to B; + 2() from B to C; + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) { + choice at A { + rec X { + 1() from A to B; + continue X; + } + } or { + 2() from A to B; + 2() from B to C; + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) { + choice at A { + rec X { + 1() from A to B; + continue X; + } + } or { + 2() from A to B; + } + 2() from C to B; +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) { + rec X { + choice at A { + 1() from A to B; + continue X; + } or { + 2() from A to B; + 2() from B to C; + } + } +} +//*/ + diff --git a/scribble-test/src/test/scrib/tmp/Demo.scr b/scribble-test/src/test/scrib/tmp/Demo.scr new file mode 100644 index 000000000..f7b23b9cc --- /dev/null +++ b/scribble-test/src/test/scrib/tmp/Demo.scr @@ -0,0 +1,220 @@ +//$ bin/scribblec.sh modules/core/src/test/scrib/Test.scr -ip modules/core/src/test/scrib/ -d modules/core/src/test/scrib/ + + +module Demo; + + +/** + * Stuck message + */ + +/* +global protocol Proto(role A, role B) +{ + choice at A + { + 1() from A to B; + 2() from B to A; + } + or + { + 1() from A to B; + 3() from B to A; + //2() from B to A; + } +} +//*/ + + +/** + * Wait-for + */ + +/* +global protocol Proto(role A, role B, role C) +{ + //rec X { + choice at A + { + 1() from A to B; + //continue X; + } + or + { + 2() from A to B; + 2() from B to C; + } + } +} +//*/ + +/* +explicit global protocol Proto(role A, role B, role C) +{ + connect A to B; + //connect B to C; + choice at A + { + 1() from A to B; + //connect A to C; // Sync-blocked (cf. input-blocked, terminated) + 1() from A to C; + } + or + { + 2() from A to B; + } +} +//*/ + +/* +explicit global protocol Proto(role A, role B, role C) +{ + connect A to B; + rec X + { + choice at A + { + 1() from A to B; + connect A to C; + 1() from A to C; + //continue X; + } + or + { + 2() from A to B; + } + } +} +//*/ + +/* +global protocol Proto(role A, role B) +{ + choice at A + { + 1() from A to B; + 2() from A to B; + 3() from B to A; + } + or + { + 1() from A to B; + 3() from B to A; + 2() from A to B; + } +} +//*/ + + +/** + * Orphans + */ + +/* +global protocol Proto(role A, role B) +{ + choice at A + { + 1() from A to B; + } + or + { + 1() from A to B; + 2() from A to B; + } +} +//*/ + + +/** + * "Role liveness" + */ + +/* +global protocol Proto(role A, role B, role C) +{ + choice at B + { + rec X + { + 1() from B to C; + continue X; + } + } + or + { + 2() from B to C; + //3() from C to A; + } + 3() from C to A; +} +//*/ + + +/** + * "Message liveness" + */ + +/* +global protocol Proto(role A, role B, role C) +{ + choice at B + { + rec X + { + 1() from B to C; + continue X; + } + } + or + { + 2() from B to C; + } + 3() from A to C; + //3() from A to C; // WF_1 will raise an "incorrect" role-progress violation for A (but safely conservative? i.e. just incompleteness of WF?) + //... // Dragons: won't be visited via 1() ...but will be visited via 2()? is that enough? +} +//*/ + + +/** + * + */ + +/* +global protocol Proto(role A, role B, role C) +{ + 1() from A to B; + do ProtoAux1(A, B, C); +} + +aux global protocol ProtoAux1(role A, role B, role C) +{ + choice at A + { + 2() from A to B; + 2() from B to C; + do ProtoAux2(A, B, C); + } + or + { + 3() from A to B; + 3() from B to C; + } +} + +aux global protocol ProtoAux2(role A, role B, role C) +{ + choice at A + { + 4() from A to B; + do ProtoAux1(A, B, C); + } + or + { + 5() from A to B; + 5() from B to C; + } +} +//*/ + diff --git a/scribble-test/src/test/scrib/tmp/ExpConn.scr b/scribble-test/src/test/scrib/tmp/ExpConn.scr new file mode 100644 index 000000000..35f310624 --- /dev/null +++ b/scribble-test/src/test/scrib/tmp/ExpConn.scr @@ -0,0 +1,3534 @@ +module ExpConn; + + +/* +global protocol Proto1(role A, role B) +{ + rec X + { + 1() from A to B; + choice at A + { + continue X; + } + or + { + 2() from A to B; + } + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + // CHECKME: orphans currently detected on local termination, not full system termination (same for stuck and deadlock) + choice at A { + 1() from A to B; + 2() from A to C; + 3() from B to C; + 4() from C to A; + } or { + 1b() from A to B; + 3() from B to C; // -nolocalchoicecheck to show orphans + 4() from C to A; + } +} +//*/ + + +/* +global protocol Proto1(role A, role B) +{ + rec X + { + 1() from A to B; + do Proto1Aux(A, B); // Testing recvar name disambiguation + } +} + +global protocol Proto1Aux(role A, role B) +{ + rec X + { + 2() from A to B; + choice at A + { + continue X; + } + or + { + 3() from A to B; + } + } +} +//*/ + + +/* +global protocol Proto1(role A, role B) +{ + rec X + { + 1() from A to B; + rec X + { + choice at A + { + 2() from A to B; + choice at A + { + continue X; + } + or + { + 3() from A to B; + } + } + or + { + //4() from A to B; + continue X; // Testing unguarded shadowed recvars at different nestings + } + or + { + 5() from A to B; + } + } + } +} +//*/ + + +/* +global protocol Proto1(role A, role B) +{ + rec X + { + 1() from A to B; + choice at A + { + rec X + { + 2() from A to B; + continue X; + } + } + or + { + rec X // Testing shadowed unguarded recs + { + 3() from A to B; + continue X; + } + } + or + { + 4() from A to B; + continue X; + } + } +} +//*/ + + +/* +global protocol Proto1(role A, role B) +{ + rec X + { + 1() from A to B; + rec X + { + 2() from A to B; + choice at A + { + continue X; // Testing inlined-unfolding for shadowed recs + } + or + { + 3() from A to B; + } + } + } +} +//*/ + + +/* +global protocol Proto1(role A, role B) +{ + rec X + { + choice at A + { + 1() from A to B; + 2() from B to A; + continue X; + } or { + 1() from A to B; + 3() from B to A; // Testing non-det unfair-transform ("unfairness" has the power to enforce a single case out of non-det options) + continue X; + } + } +} +//*/ + + +/* +global protocol Proto1(role A, role B) +{ + rec X + { + choice at A + { + 1() from A to B; + 2() from B to A; + continue X; // Testing non-det unfair-transform + } or { + 1() from A to B; + 3() from B to A; + } + } +} +//*/ + + +/* +global protocol Proto1(role A, role B) +{ + rec X + { + choice at A + { + 1() from A to B; + continue X; // Testing non-det unfair-transform + } or { + 1() from A to B; + } + } +} +//*/ + + +/* +global protocol Proto1(role A, role B) +{ + disconnect A and B; + do Proto1Aux(A, B); +} + +// Trivial test for "expressiveness" of aux -- but could just make explicit.. // CHECKME example where "aux" is fully needed +aux global protocol Proto1Aux(role A, role B) +{ + connect A to B; +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + rec X + { + choice at A + { + 1() from A to B; + //1() from A to C; + continue X; // Testing fairness + } + or + { + 2() from A to B; + 2() from A to C; + continue X; + } + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + 1() from A to B; + 3() from B to C; + 4() from C to B; + 5() from B to C; + } + or + { + 2() from A to B; + 3() from B to C; // Syntactic merge means: non-det "squashed" so original choice path now ambiguous, so we need to act conservatively -- conservatively means squashed role needs to accept any incoming messages as a branch (to handle ambiguity) while not being allowed to make any output choices (only unary send allowed, so must be identical in all possibilities) + // EFSM transform has to follow this intuition, full continuations after a non-det input choice have to be convservatively squashed (and if not squashable, then check model using unsquashed version) -- or implement as syntactic merge, and use original if not mergeable + 4() from C to B; + 6() from B to C; + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C, role D) +{ + choice at A + { + 1() from A to B; + 3() from B to C; + 3() from B to D; + 4() from C to D; + } + or + { + 2() from A to B; + 3() from B to C; + 3() from B to D; + 5() from C to D; + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C, role D) +{ + choice at A + { + 1() from A to B; + 3() from B to C; + 4() from C to D; + } + or + { + 2() from A to B; + 3() from B to C; + 5() from C to D; // Not mergeable by ICALP13 + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + 1() from A to B; + 3() from B to C; + 4() from C to B; + } + or + { + 2() from A to B; + 3() from B to C; + 4() from C to B; + 5() from C to B; // Tricky to check, e.g., output state sub-EFSMs are the same (cf. syntactic equality) for terminating the merge, maybe need strict isomorphism (without renaming) + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + rec X + { + 0() from B to C; + choice at A + { + 1() from A to B; + 3() from B to C; + 4() from B to C; + } + or + { + 2() from A to B; + 3() from B to C; + 5() from B to C; // Consider EFSM of C for merging -- do non-det input squashing inductively, and only if no recursive edges back to original or preceding state? -- difficult to confirm, e.g., output state sub-EFSMs are the same (cf. syntactic equality) for terminating the merge, maybe need isomorphism + continue X; + } + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + 1() from A to B; + 3() from B to C; + 4() from B to C; + } + or + { + 2() from A to B; + 3() from B to C; + //5() from B to C; // Makes merge easier + rec X + { + 5() from B to C; // Consider EFSM of C for merging + continue X; + } + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + 1() from A to B; + 3() from B to C; + 3() from B to C; + 4() from B to C; + } + or + { + 2() from A to B; + 3() from B to C; // Merging (non-det input state "squashing") first messages only not enough (cf. inductive syntactic merge) + 3() from B to C; + 5() from B to C; + } +} +//*/ + + +/* +global protocol Proto1(role A, role B) +{ + rec X + { + 1() from A to B; + choice at A + //choice at B + { + continue X; + } + or + { + 2() from A to B; + //2() from B to A; + } + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + 1() from A to B; + choice at A + { + 1a() from A to B; + 1a() from A to C; + } + or + { + 1b() from A to B; + 1b() from A to C; + } + } + or + { + 2() from A to B; + choice at A + { + 2a() from A to B; + 2a() from B to C; + } + or + { + 2b() from A to B; + 2b() from B to C; + } + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + rec X + { + 1() from A to B; + continue X; + } + } + or + { + 2() from A to B; + } + 3() from C to A; + 3() from C to A; // Role-progress violation for C under WF_1 + choice at A + { + 4() from A to B; + 5() from B to A; + } + or + { + 4() from A to B; + 6() from B to A; + } +} +//*/ + + +/* +// Counter example to completeness of safety for current WF +global protocol Proto1(role A, role B, role C) { + choice at A { + 1() from A to B; + 3() from B to C; + 4() from A to C; + } or { + 2() from A to B; + 3() from B to C; + 5() from A to C; // FIXME: should be mergable as a branch at C? (yes, by ICALP13) -- but requires treating non-det as det (i.e. language equiv. vs. bisim? -- local language minimisation wrt. inputs only?) -- in general, consider subsequent B and C interactions; but this exact example should be safe + } +} +//*/ + + +/* +global protocol Proto1(role A, role B) +{ + 1() from A t B; // Testing Antlr error display overriding +} +//*/ + + +/* +type "java.lang.Integer" from "rt.jar" as Int; + +global protocol Proto1(role A, role B) +{ + choice at A + { + 1() from A to B; + } + or + { + 1(Int) from A to B; // Testing bad payloads + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + 1() from A to B; + 2() from B to C; + 3() from C to A; + } + or + { + 4() + from A to B; + 5() from B to C; // "Standard merge" (ICALP13) -- 2/5 cases merged for input choice at C // but is it actually mergable in ICALP13/WADFEST? because only defined on branch, not select as needed for C here -- it's fine, only merging the top level branches (distinct labels) + 6() from C to A; + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + 1() from A to B; + 2() from B to C; + 3() from C to A; + } + or + { + 4() from A to B; + 2() from B to C; + 3() from C to A; // Not mergeable by WADFEST, because continuations of C to be merged are not input-branches (but WAFDEST could probably be extended easily -- most simply by just allowing TmergeT for any T, not just branch -- more generally, would have to inductively coerce non-branches into branches, which is what the below example (i.e. WADFEST) is a special case of) + // However, mergeable by ICALP13 (just a typo by WADFEST) + // (WADFEST merges also only defined on branches, not receives, but receive can be easily converted to singleton branches? -- a point of directed branches is that they have no payloads, and receives have no labels, which Scribble needs to consider) + } +} +//*/ + + +/* +// Counter example to completeness of safety for current WF -- this notion of completeness is wrt. a global semantics, but not wrt. specific definition of Scribble projection/EFSM? (i.e. if we project/build a subsequent input choice at C from A, not just the initial one from B -- this is essentially mixing a ``non-choice'' (pre-determined flow) at A with an external choice at C -- i.e. ICALP13/WADFEST merge: convert non-det external choice into det non-choice followed by inductively merged (external choice) continuations) -- actually not necessarily, can consider still non-det, but just that the continuation branches are safe (but this view is more like inferring non-directly specified cases for nested branches) +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + 1() from A to B; + 2() from B to C; + //choice at A { // better for merging? + 3() from A to C; + //} + } + or + { + 1b() from A to B; + 2() from B to C; + 4() from A to C; // FIXME: "merge/coerce" branches for C -- implement as some king of variant of "determinisation"? i.e. 2.3+2.4 -> 2.(3+4) (issue is it's not bisim preserving -- is local language minimisation a sound general principle? well, not for the minimal non-det branch example (or actually, yes? see below), but somehow only for "nested" external choices? i.e. same-label mergability?) + } +} +//*/ + + +/* +global protocol Proto1(role A, role B) +{ + choice at A + { + 1() from A to B; + 2() from B to A; // FIXME: should we just language-equiv minimise endpoints? implicitly take that as the CFSM meaning of this global protocol? depends on global semantics -- but would make general projection/graphbuilding and mergability more uniform? -- uniformity should be the aim, see below -- no: not just independent EFSM minimisation, but should consider the whole CFSM system, see below + } + or + { + 1() from A to B; + 3() from B to A; + } +} +//*/ + + +/* +global protocol Proto1(role A, role B) +{ + choice at A + { + 1() from A to B; + 3() from B to C; + 4() from C to A; + } + or + { + 2() from A to B; + 3() from B to C; + 5() from C to A; // FIXME: language minimising at C will determinise, but minimising at A has no effect: minimising makes (non-det) external choice at C into internal choice, which is incompatible with original internal choice at A -- so independent language minimising is not sound -- basically syntactic branch-only merging restricts "determinising" to external choices only -- so do independent EFSM language-minimisation applied to inputs only? (but sometimes non-det outputs can be safely minimised -- but just leave them as is for global model checking?) + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + 1() from A to B; + } + or + { + 1() from A to B; // Simply syntactically not representable with directed choice, but safe under the same intuition as mergability -- in this case, independent endpoint minimisation modifies both A and B consistently + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + 1() from A to B; + 2() from B to C; + //choice at A + //{ + // 4() from A to C; + //} + //or + //{ + // 3() from A to C; + //} + do Proto1Aux(A, C); // WADFEST merge -- morally: WADFEST merge "infers" safe branche cases for nested branches -- can factor out by subprotos + // NO: WADFEST prevents internal choice 4/5 by A, only allows external choice by C + } + or + { + 1b() from A to B; + 2() from B to C; + //choice at A + //{ + // 4() from A to C; + //} + //or + //{ + // 3() from A to C; + //} + do Proto1Aux(A, C); + } +} + +// Makes clear that TmergeT for any T should be OK +aux global protocol Proto1Aux(role A, role C) +{ + choice at A + { + 3() from A to C; + } + or + { + 4() from A to C; + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + 1() from A to B; + 2() from B to C; + 3() from C to A; + } + or + { + 4() from A to B; + 2() from B to C; + 5() from C to A; // TODO: most general merge: coerce an external choice for A here -- less morally clear than, e.g., WADFEST restriction to branch-only merge though + } +} +//*/ + + +/* +type "java.lang.Integer" from "rt.jar" as Int; + +global protocol Proto1(role A, role B, role C) +{ + choice at A { + buyer1(Int) from A to B; // Total + (Int) from B to A; // B will pay this much + buyer2(Int) from A to C; // C will pay remainder + } or { + buyer1(Int) from A to C; // Total + (Int) from C to A; // C will pay this much + buyer2(Int) from A to B; // B will pay remainder + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C, role D) +{ + ..(syntactic) reachability tests +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + 1() from A to B; + 1() from A to C; + } + or + { + 2() from A to B; + } + 3() from A to C; // TODO: "optional": needs empty actions and "empty-removal" transformation +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + rec X + { + choice at A + { + 1() from A to B; + 1() from B to A; + 3() from A to C; // Trying to find an unfair-transformation problem wrt. not visiting "2" case after "1" transitions + continue X; + } + or + { + 2() from A to B; + 2() from B to A; + 3() from A to C; + } + } +} +//*/ + + +/* +global protocol Proto1(role A, role B) +{ + 1() from A to B; + 2() from B to C; // Testing CommandLine with, e.g., -fsm(dot) arg (disamb error before projection passes means graph cannot be built) +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + rec X + { + choice at A // -oldwf, default, -fair + { + 1() from A to B; + continue X; + } + or + { + 2() from A to B; + //2() from A to C; + 2() from B to C; + } + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + rec X + { + 1() from A to B; + continue X; + } + } + or + { + 2() from A to B; + } + 3() from B to C; +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + 1() from A to B; + () from B to C; + 1() from B to A; + } + or + { + 2() from A to B; + () from B to C; // Classic mergeability (no "equiv." protocol by sequencing -- unless maybe a generous async. equiv.) + 2() from B to A; + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + 1() from A to B; + 2() from B to C; + //3() from C to A; + 3() from C to B; + } + or + { + 1() from A to B; + 5() from B to C; + //6() from C to A; + 5() from C to B; // Mergeable -- A not involved downstream + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + rec X + { + 1() from A to B; + 1() from B to C; + continue X; + } + } + or + { + 2() from A to B; + 2() from B to C; + } + 3() from A to B; // Sequencing after recursive-choice + 3() from B to C; +} +//*/ + + +/* +global protocol Proto1(role A, role B) +{ + 1(Proto2@A) from A to B; // Testing delegation payload projection +} + +global protocol Proto2(role A, role B) +{ + 2() from A to B; +} +//*/ + + +/* +global protocol Proto1(role A, role B) +{ + (Proto1@A) from A to B; // Testing recursive protocoldecls +} +//*/ + + +/* +global protocol Proto1(role A, role B) +{ + (Proto2@A) from A to B; // Testing recursive protocoldecls +} + +global protocol Proto2(role A, role B) +{ + //(Proto1@A) from A to B; + (Proto3@A) from A to B; + //do Proto3(A, B); +} + +global protocol Proto3(role A, role B) +{ + 1() from A to B; + //(Proto1@A) from A to B; + //(Proto2@A) from A to B; + //do Proto1(A, B); +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + 1() from A to B; + 4() from B to C; + } + or + { + 2() from A to B; + 5() from B to C; // Mergeable subset of choice cases (cf. syntactic merge? + 5() from C to B; + } + or + { + 3() from A to B; + 5() from B to C; + 5() from C to B; + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + 1() from A to B; + do Game(A, B, C); + } + or + { + 2() from A to B; + 2() from B to C; + } +} + +aux global protocol Game(role A, role B, role C) +{ + () from A to B; + () from B to C; +} +//*/ + + +/* +global protocol Proto1(role A, role B) +{ + rec X + { + 1() from A to B; + rec X + { + 2() from A to B; + //do Proto1Aux(A, B); + } + } +} + +aux global protocol Proto1Aux(role A, role B) +{ + continue X; // Still checked for aux +} +//*/ + + +/* +global protocol Proto1(role A, role B) +{ + do Proto1Aux(A, B); +} + +aux global protocol Proto1Aux(role A, role B) +{ + M from A to B; +} +//*/ + + +/* +global protocol Proto1(role A, role B) +{ + (Test.Foo) from A to B; // Testing DataType disamb +} +//*/ + + +/* +type "java.lang.Integer" from "rt.jar" as Int; + +global protocol Proto1(role A, role B) +{ + Int from A to B; // Testing disamb (and AST visitChild) +} +//*/ + + +/* +sig "..." from "..." as M; + +global protocol Proto1(role A, role B) +{ + (M) from A to B; // Testing disamb (and AST visitChild) +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B, role C) +{ + connect A to B; + connect A to C; + rec X + { + choice at A + { + 1() from A to B; // Testing "fair"/"unfair" liveness -- issue of global liveness vs. local subtyping) -- generating "unfair output subtyped" global model (can it be done simply by terminal set role check?) + continue X; + } + or + { + 2() from A to B; + } + } + 3() from A to C; +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + rec X + { + choice at A + { + 1() from A to B; + continue X; + } + or + { + 1() from A to B; // Testing non-det unfairClone -- uninteresting test because non-det single-action-edge choice-merges get implicitly minimised (by graph building) + continue X; + } + or + { + 2() from A to B; + 2() from B to C; + } + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + rec X + { + choice at A + { + 1() from A to B; + 3() from B to A; + continue X; + } + or + { + 1() from A to B; // Testing non-det unfairClone + 3() from B to A; + //4() from B to A; + continue X; + } + or + { + 2() from A to B; + 2() from B to C; + } + } +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B, role C) +{ + connect A to B; + connect B to C; + connect A to C; // How does C "correlate" A/B connections to sessions -- introduces? -- need to study real examples +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B, role C) +{ + connect A to B; + rec X + { + 1() from A to B; + connect B to C; // C doesn't care whether each connection is new or old session? + 2() from B to C; + disconnect B and C; + continue X; + } +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B) +{ + connect A to B; + disconnect A and B; + connect A to B; // What does it mean for B to leave the session and rejoin? Need some condition like if fully leave, then rejoining should be same as new session? (i.e. this case bad) -- Consider implementability + disconnect A and B; +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B, role C) +{ + connect A to B; + rec X + { + choice at A + { + 1() from A to B; + 1() connect A to C; + disconnect A and C; + continue X; + } + or + { + 2() from A to B; + 2() connect A to C; + disconnect A and C; + continue X + } + } + connect A to C; // Good until here, now bad because C already fully left? + 3() from A to C; +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B) +{ + rec X + { + connect A to B; // What does this mean in terms of a "session"? (should consider the implementation, session id, ...) -- distinction between initial accept and in-session accepts? + //1() from A to B; + //1() from B to A; + disconnect A and B; // Shouldn't allow continuation after a certain point? no session structure left? + continue X; + } +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B, role C) +{ + connect A to B; + choice at A + { + 1() from A to B; + connect B to C; + connect A to C; + 1() from A to C; + } + or + { + 2() from A to B; + connect A to C; // Inconsistent choice connect subjects + } +} +//*/ + +//*** + + + +/* +explicit global protocol Proto1(role A, role B) +{ + connect A to B; + choice at A + { + 1() from A to B; + } + or + { + disconnect A and B; // CHECKME: disconnect shouldn't have asymmetric src/dest -- check enabling conditions wrt. choices, projection, etc + } +} +//*/ + + +/* +type "java.lang.Integer" from "rt.jar" as Int; + +explicit global protocol Proto1(role A, role B) +{ + choice at A + { + 1(Int) connect A to B; // Testing non-det payloads for message-connects + } + or + { + 1() connect A to B; + } +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B, role C) +{ + connect A to B; + rec X + { + choice at A + { + 1() from A to B; + } + or + { + 2() from A to B; + 2() connect B to C; + 2() from B to C; + disconnect B and C; + } + or + { + 3() from A to B; + 3() connect B to C; // Cf. PartnershipSupplier filter subproto + 3() from B to C; + disconnect B and C; + } + continue X; + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + rec X + { + choice at A + { + 1() from A to B; + 1() from B to C; + rec Y + { + choice at B + { + 3() from B to A; + continue X; + } + or + { + 4() from B to A; + continue Y; // Needs fairness + } + } + } + or + { + 2() from A to B; + 2() from B to C; + } + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + rec X + { + choice at A + { + 1() from A to B; + 1() from B to C; + choice at B // C not involved, but still live (without fairness) + { + 3() from B to A; + continue X; + } + or + { + 4() from B to A; + continue X; + } + } + or + { + 2() from A to B; + 2() from B to C; + } + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + rec X + { + choice at A + { + 1() from A to B; + 1() from B to C; + choice at B + { + 3() from B to A; + continue X; + } + or + { + rec Y // Bad (fair or not) + { + 4() from B to A; + continue Y; + } + } + } + or + { + 2() from A to B; + 2() from B to C; + } + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + rec X + { + choice at A + { + 1() from A to B; + 1() from B to C; // Live, without fairness + continue X; + } + or + { + 2() from A to B; + 2() from B to C; + } + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + rec X + { + 1() from A to B; + 1() from B to C; + continue X; + } + } + or + { + 2() from A to B; + 2() from B to C; // CHECKME: bad sequence if commented, correct? -- bad sequence because C not in block so projection pruned, then only rec-block left -- is this satisfactory? (consider standalone global semantics vs. global as syntactic sugar for locals) -- however, "bad sequence" restriction probably does not hurt expressiveness + } + 3() from B to C; +} +//*/ + + +/* +global protocol Proto1(role A, role B) +{ + choice at A + { + 1() from A to B; + } + or + { + 2() from A to B; + } + rec X // Testing non-fair EFSM generation + { + choice at B + { + 3() from B to A; + continue X; + } + or + { + 4() from B to A; + } + } +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B) +{ + connect A to B; + choice at A + { + 1() from A to B; + wrap B to A; + } + or + { + wrap A to B; + } +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B) +{ + connect A to B; + choice at A + { + 1() from A to B; + } + or + { + 2() from A to B; + disconnect A and B; // Testing unfairClone terminal state reconcilliation -- FIXME: this example doesn't actually test this, cf. SupplierInfoExplicit for requestor + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + rec X + { + choice at A + { + 1() from A to B; + continue X; + } + or + { + 2() from A to B; + } + } + //3() from A to C; // Testing fair/unfair liveness for C + 3() from C to A; // Message liveness also subject to fair/unfair +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + 1() from A to B; + () from B to C; + 3() from B to A; + } + or + { + 2() from A to B; + () from B to C; // choice + sequencing not the same as just syntactic sugar for factoring out a common branch continuation, i.e. cannot factor out "() from B" as a continuation without either losing causality for output to A or changing output order at B -- arguable that changing order at B is equivalent (for some equivalence), but not equivalent under basic bisimilarity + 4() from B to A; + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + 1() from A to B; // CHECKME: empty case for C discarded by projection, but do we need tau for correctness? this example works because it ends up as stuck error -- a point is generating tau and then bisim-minimising doesn't remove the tau, whereas the current projection does remove the tau (so current projection is not equiv to bisim-minimisation intuition) + // should be OK: intiution: an input-state endpoint cannot choose to not receive a message, i.e. input states should never have tau -- so whole system must satisfy properties when modelling "partial" local branches as a "complete" branch for just the involved choice cases (i.e. ignore any non-involved cases) + } + or + { + 2() from A to B; + 2() from A to C; + } + 3() from A to C; +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + rec X + { + choice at A + { + 1() from A to B; + continue X; + } + or + { + 2() from A to B; + } + } + 3() from A to C; // Not "strongly" live for C -- by subtyping, an implementation of A may never terminate -- strongly live probably means all roles have to be involved in every choice path -- not quite: it all depends on definition of subtyping, could make a "live" notion of subtyping that doesn't allow a non-live subset of choices -- this also depends on the select primitives and typing rules (it could come down to decidability of if-conditions...) -- problem is, even without subtyping, select primitive is always about selecting just one case, can't really make a "live" typing on top of that... -- could be positioned as basic session typing needs strong liveness, while weak liveness can be aimed at assuming a more general program verification -- or maybe a more powerful "imperative style" typing system could work, e.g. while (...) { ..non-live choice on s..} ..live choice on s.., i.e. it is ok to select a non-live case if the while will terminate to eventually lead us to a live case.. -- this fairness/liveness issue is another "bondary" issue between modelling/types/practice, bit like linearity +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B, role C) +//explicit global protocol Proto1(role A, role B) +{ + connect A to B; + choice at A + { + 1() from A to B; + } + or + { + 1() from A to B; + connect A to C; // Testing API gen (without I/O i/f gen) + } +} +//*/ + + +/* +global protocol Proto1(role A, role B) +{ + choice at A // Testing minfsm + { + 1() from A to B; + 2() from B to A; + } + or + { + 1() from A to B; + 2() from B to A; + } +} +//*/ + + +/* +global protocol Proto1(role A, role B) +{ + 2() from A to B; + rec X + { + choice at A + { + 1() from A to B; + 1() from A to B; + } + or + { + 1() from A to B; // Testing minfsm + 1() from A to B; + } + continue X; +} +//*/ + + +/* +global protocol Proto1(role A, role B) +{ + 2() from A to B; + rec X + { + choice at A + { + 1() from A to B; // Testing minfsm + } + or + { + 1() from A to B; + 1() from A to B; + } + continue X; +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B, role C) +{ + connect A to B; + connect A to C; // Bad + disconnect A and C; + choice at A + { + 1() from A to B; + } + or + { + 1() from A to B; + connect B to C; + } +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B, role C) +{ + connect A to B; + connect A to C; + choice at A + { + 1() from A to B; + 1() from A to C; + connect B to C; + 2() from A to B; + } + or + { + 1() from A to B; + 1() from A to C; + connect B to C; // Good: mergeable + 2() from A to B; + } +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B, role C) +{ + connect A to B; + connect A to C; + choice at A + { + 1() from A to B; + 1() from A to C; + connect B to C; + 2() from A to B; + } + or + { + 1() from A to B; + 1() from A to C; + connect C to B; // If A and C are in above, 2() can be stuck at B's connect/accept here -- but stuck error not directly detected, error manifests as B/C deadlock + 2() from A to B; // Mergeable if B/C connection not deadlocked + } +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B, role C) +{ + connect A to B; + choice at A + { + 1() from A to B; + connect B to C; + } + or + { + 1() from A to B; + } + 2() from B to C; // Trying to make an unconnected orphan from B to C, but currently will always get a connectedness error first -- model building semantics shouldn't/won't allow explicit unnconnected orphans, message cannot be sent if not connected +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B, role C) +{ + connect A to C; + connect C to B; + choice at A + { + 1() from A to C; + connect A to B; + } + or + { + 2() from A to C; + 2() from C to B; // Bad: connect and msg from different choice subjects + } +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B) +{ + rec X + { + choice at A + { + connect A to B; // Good: tests recursion pruning for connection actions + } + } +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B) +{ + rec X + { + choice at A // ** using old WF, this breaks connectedness checking -- WFChoiceChecker is an UnfoldingVisitor, but it is prunes the visit on entering the unfolded choice + { + connect A to B; + continue X; // Bad + } + } +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B, role C) +{ + connect A to B; + rec X + { + choice at A + { + 1() from A to B; + connect B to C; + disconnect B and C; // Comment is bad + continue X; + } + or + { + 2() from A to B; + } + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + rec X + { + choice at A + { + 2() from A to C; + 1() from A to B; + } + or + { + 2() from A to C; + 2() from C to A; + 2() from A to B; + } + continue X; + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + // Disable local choice subject inference + rec X + { + // Testing getTrace? + choice at A + { + 1() from A to B; + //1() from A to B; + 1() from A to C; + 3() from B to C; + continue X; + } + or + { + 1() from A to B; + 2() from B to C; + 3() from C to B; + continue X; + } + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + // Disable local choice subject inference + rec X + { + // Testing getTrace? + choice at A + { + 1() from A to B; + continue X; + } + or + { + 1() from A to B; + 1() from A to C; + 2() from C to B; + continue X; + } + or + { + 3() from A to C; + 3() from C to B; + continue X; + } + } +} +//*/ + + +/* +global protocol Proto1(role A, role B) +{ + rec X + { + choice at A + { + 1() from A to B; // Testing graph building + } + or + { + 1() from A to B; + } + continue X; + } +} +//*/ + + +/* +global protocol Partners( + role LOGINsvc, + role REQUESTOR, + role AUTHsvc, + role FILTERsvc, + role SUPPLIERsvc, + role CONTRACTsvc) +{ + login() from REQUESTOR to LOGINsvc; + choice at LOGINsvc + { + loginfailure() from LOGINsvc to REQUESTOR; + 0() from REQUESTOR to AUTHsvc; + 0() from AUTHsvc to FILTERsvc; + 0() from AUTHsvc to SUPPLIERsvc; + 0() from AUTHsvc to CONTRACTsvc; + } or { + loginsuccess() from LOGINsvc to REQUESTOR; + rec MAIN + { + choice at REQUESTOR + { + getsuppliers() from REQUESTOR to AUTHsvc; + choice at AUTHsvc + { + getsuppliers() from AUTHsvc to SUPPLIERsvc; // Bad: testing getTrace performance + deny() from AUTHsvc to REQUESTOR; + } or { + getsuppliers() from AUTHsvc to SUPPLIERsvc; + suppliers() from SUPPLIERsvc to AUTHsvc; + filterSuppliers() from AUTHsvc to FILTERsvc; + filtered() from FILTERsvc to AUTHsvc; + suppliers() from AUTHsvc to REQUESTOR; + } + } or { + getcontracts() from REQUESTOR to AUTHsvc; + choice at AUTHsvc + { + deny() from AUTHsvc to REQUESTOR; + } or { + getcontracts() from AUTHsvc to CONTRACTsvc; + contracts() from CONTRACTsvc to AUTHsvc; + filterContracts() from AUTHsvc to FILTERsvc; + filtered() from FILTERsvc to AUTHsvc; + contracts() from AUTHsvc to REQUESTOR; + } + } + continue MAIN; + } + } +} +//*/ + + +/* +global protocol Proto1 +( + role REQuestor, + role AUTHsvc, + role SUPPLIERsvc, + role CONTRACTsvc) +{ + rec MAIN + { + choice at REQuestor + { + getsuppliers() from REQuestor to AUTHsvc; + choice at AUTHsvc + { + getsuppliers() from AUTHsvc to SUPPLIERsvc; // Bad: testing getTrace + deny() from AUTHsvc to REQuestor; + } or { + getsuppliers() from AUTHsvc to SUPPLIERsvc; + suppliers() from SUPPLIERsvc to AUTHsvc; + suppliers() from AUTHsvc to REQuestor; + } + } or { + getcontracts() from REQuestor to AUTHsvc; + choice at AUTHsvc + { + deny() from AUTHsvc to REQuestor; + } or { + getcontracts() from AUTHsvc to CONTRACTsvc; + contracts() from CONTRACTsvc to AUTHsvc; + contracts() from AUTHsvc to REQuestor; + } + } + continue MAIN; + } +} +//*/ + + + +/* +global protocol Proto(role A, role B) +{ + choice at A + { + 1() from A to B; + disconnect A and B; + } + or + { + 1() from A to B; + 2() from B to A; // B can still send even if A disconnects (async) -- so not wait-for from that situation + } +} +//*/ + + +/*/ +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + 1() from A to B; + + 1() from A to C; + 1() from A to C; + + 3() from C to B; + } + or + { + 1() from A to B; + + () from B to C; // Trying to get A into above block while C is in here, such that WF1 forces C also into the above -- so that WF1 becomes unsound + 2() from A to C; + + 4() from C to B; + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + choice at C + { + 1() from C to B; + 1() from C to A; + } + or + { + 1() from C to B; + 2() from C to A; + + 2() from A to B; + 2() from A to B; + + 2() from A to C; + + 2() from C to B; + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + rec X + { + choice at A + { + 1() from A to B; + continue X; + } + } + } + or + { + 2() from A to B; + } + + 2() from C to B; // TODO: investigate: WF_1 won't get past here, is it OK? + 2() from C to B; // ..becomes "fake" role liveness problem because of WF1 -- not live even assuming fairness + // ..dragons + + // TODO: investigate reachability of local states in global model +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + choice at B + { + 0() from B to C; + 0() from B to A; + 2() from C to B; + choice at A + { + rec X + { + choice at A + { + 1() from A to B; + continue X; + } + } + } + or + { + 2() from A to B; + } + } + or + { + 0() from B to C; + 1() from B to A; + 2() from C to B; // Good + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + choice at B + { + 0() from B to C; + 0() from B to A; + + //2() from C to B; + //2() from C to B; + + choice at A + { + rec X + { + choice at A + { + 1() from A to B; + //2() from C to B; + continue X; + } + } + } + or + { + 2() from A to B; + } + } + or + { + 0() from B to C; + 1() from B to A; + } + + 2() from C to B; // TODO: investigate: WF_1 won't get past here, is it OK? + 2() from C to B; // ..becomes "fake" role liveness problem because of WF1 + // ... + + // TODO: investigate reachability of local states in global model +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + // Trying to construct a counterexample for WF1 soundness.. + // ..need to find an error state that is unreachable by WF1 but reachable by e.g. WF2 + // Try to find a choice where B is falsely committed to a branch due to WF1 (so state space of model is unsoundly restricted) + choice at A + { + 1() from A to B; + 1() from A to B; + 2() from A to C; // A cannot do this in WF1 unless B receives a 1() first + } + or + { + 3() from A to C; + //2() from A to B; + // Local choice subjects require B to also receive from A in this block + // Two cases: same or different label + // If different label, then no possibility of false branch commitment + // If same label, then non-det always allows B to enter this block, even under WF1 + // Therefore: false choice commitment not possible + 1() from A to B; + 1() from A to B; + } +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B, role C) +{ + connect A to B; + choice at A + { + 1() from A to B // Good non-det EFSM for A (including minimisation) + connect A to C; + } + or + { + 1() from A to B; + //connect A to C; // Tests -minfsm + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + // Needs local choice subject disabled, though the point is it's still bad + choice at A + { + a() from A to B; + //d() from C to B; // Moved down to make C enabled + cprime() from A to C; + d() from C to B; + b() from B to A; + y() from A to B; // Orphan + } + or + { + c() from A to C; + d() from C to B; // ..point is B could get in this case, while A (and C) are in the other + b() from B to A; + a() from A to B; // (..not stuck msg error because the a() from above is consumed here) + x() from B to A; // Orphan + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + // Counterexample for WF1 if local choice subject disabled + choice at A + { + a() from A to B; + a() from A to B; // WF1 unnaturally resolves the non-det choice at B by forcing B to commit to this branch before C is enabled + cprime() from A to C; + d() from C to B; + b() from B to A; + + //y() from A to B; // Potential orphan + } + or + { + c() from A to C; + d() from C to B; + b() from B to A; // Must come before a's, to prevent reverse choice race + a() from A to B; + a() from A to B; + + //x() from B to A; // Potential orphan + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + // Disable local choice subject inference -- mergeable + choice at A + { + 1() from A to B; + 1() from A to B; + 1() from A to C; + 2() from C to B; + } + or + { + 2() from A to C; + 2() from C to B; + 1() from A to B; + 1() from A to B; + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + 1() from A to B; + 1() from A to B; + 1() from A to C; + 2() from C to B; + + 3() from B to C; + } + or + { + 2() from A to C; + 2() from C to B; + 1() from A to B; + 1() from A to B; + + //3() from B to C; + 4() from B to C; // Bad + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + 1() from A to B; + 1() from A to B; + 1() from A to C; + 2() from C to B; + 2() from C to B; + + 3() from B to C; // Should be potential stuck + } + or + { + 2() from A to C; + 2() from C to B; + 2() from C to B; + () from C to A; // Another counterexample to WF1 (B falsely committed to here when A/C are) + 1() from A to B; + 1() from A to B; + + 4() from B to C; // Should be potential stuck + } +} +//*/ + + +/* +global protocol Proto1(role A, role B) +{ + rec X + { + 1() from A to B; + continue X; // Test graph building: EndpointGraph null exit + } +} +*/ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +/* +explicit global protocol Proto1(role A, role B, role C) +{ + connect A to B; + choice at A + { + 1() from A to B; + connect from B to C; + 1() from B to C; + } + or + { + 2() from A to B; + connect from B to C; + 2() from B to C; // Not mergeable (connect/accept is unit message) + } +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B, role C) +{ + // Good + connect A to B; + connect A to C; + connect B to C; // Test wait-for error detection: C is non-initial accept, but B is a corresponding connect +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B, role C) +{ + // Bad + connect A to B; + connect A to C; + 0() from A to C; + choice at A + { + 1() from A to B; + } + or + { + 2() from A to B; + connect B to C; // Test safe termination check for non-initial accept states + 3() from B to C; + } +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B, role C) +{ + // Good + connect A to B; + connect A to C; + 0() from A to C; + choice at A + { + 1() from A to B; + } + or + { + 2() from A to B; + } + connect B to C; + 3() from B to C; +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B, role C) +{ + connect A to B; + connect A to C; + 0() from A to C; + choice at A + { + rec X + { + 1() from A to B; + continue X; + } + } + or + { + 2() from A to B; + } + connect B to C; // Tests role liveness check for non-terminal (accept) states + 3() from B to C; +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B) +{ + connect A to B; // Basic test for connection deadlock detection + 1() from A to B; +} +//*/ + + + +/* +explicit global protocol Proto1(role A, role B, role C) +{ + connect A to B; + choice at A + { + 1() from A to B; + } + or + { + 2() from A to B; + connect B to C; // Good because C is initial + 2() from B to C; + } +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B, role C) +{ + connect A to B; + connect A to C; + choice at A + { + 1() from A to B; + 1() from A to C; + connect B to C; + } + or + { + 1() from A to B; + 1() from A to C; + connect C to B; // Deadlock + } +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B, role C) +{ + connect A to B; + connect A to C; + choice at A + { + 1() from A to B; + 1() from A to C; + connect B to C; + 2() from B to C; + } + or + { + 1() from A to B; + 1() from A to C; + connect B to C; // Good + 2() from B to C; + } +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B, role C, role D) +{ + connect A to B; + connect A to C; + connect A to D; + choice at A + { + 1() from A to B; + 1() from A to C; + 1() from A to D; + connect B to C; + } + or + { + 1() from A to B; + 1() from A to C; + 1() from A to D; + connect C to D; + } + or + { + 1() from A to B; + 1() from A to C; + 1() from A to D; + connect D to B; + } +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B, role C, role D) +{ + connect A to B; + connect A to C; + connect A to D; + // Good + choice at A + { + 1() from A to B; + 1() from A to C; + 1() from A to D; + connect B to C; + connect C to D; + connect D to B; + } + or + { + 1() from A to B; + 1() from A to C; + 1() from A to D; + connect B to C; + connect C to D; + connect D to B; + } + or + { + 1() from A to B; + 1() from A to C; + 1() from A to D; + connect B to C; + connect C to D; + connect D to B; + } +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B, role C) +{ + connect A to B; + choice at A + { + 1() from A to B; + connect A to C; + 3() from A to C; + } + or + { + connect A to C; // Mixed send/connect state at A + 2() from A to B; + 3() from A to C; + } +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B, role C) +{ + connect from A to B; + choice at A + { + rec X + { + choice at A + { + 1() from A to B; + continue X; + } + or + { + //3() from A to B; // Uncomment is fix + } + } + } + or + { + 2() from A to B; + } + connect from C to B; // Not role live: connect is a sync action + 3() from C to B; +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B, role C) +{ + connect from A to B; + choice at A + { + rec X + { + choice at A + { + 1() from A to B; + continue X; + } + } + } + or + { + 2() from A to B; + } + connect from B to C; // Good: connect is a sync action, but "asymmetric" + 3() from C to B; +} +//*/ + + +/* // disconnect +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + 1() from A to B; + 1() from B to C; + disconnect B and C; + rec X + { + 1() from A to B; + continue X; + } + } + or + { + 2() from A to B; + 2() from B to C; + } + 3() from A to B; + //3() from B to C; // Uncomment is bad +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B, role C) +{ + // Good + connect A to B; + connect A to C; + choice at A + { + 1() from A to B; + 1() from A to C; + } + or + { + 2() from A to B; + 2() from A to C; + connect B to C; + disconnect B and C; + } + connect B to C; + 2() from B to C; +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B) +{ + connect A to B; + 1() from A to B; + choice at A + { + 1() from A to B; + disconnect A and B; + } + or + { + 2() from A to B; + disconnect A and B; + } + 3() from A to B; +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B) +{ + connect A to B; + 1() from A to B; + choice at A + { + 1() from A to B; + disconnect A and B; + } + or + { + 2() from A to B; + } + 3() from A to B; +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B, role C) +{ + connect A to B; + do Proto1Aux(A, B, C); +} + +aux global protocol Proto1Aux(role A, role B, role C) +{ + choice at A + { + 1() from A to B; + //connect B to C; // Bad if non-det + 1() connect B to C; + 1() from B to C; + disconnect B and C; + do Proto1Aux(A, B, C); // FIXME: guarded do has same subprotsig has an unguarded one (and ProjectedSubprotPruner is using subprotsigs...) -- but current problem is actually ambiguous connect enabling of C by B -- anyway to have explicit protocol with multiple instances of the same do-subprotsig with and without choice-guards? + // TODO: this doesn't just break subprot pruning, but affects whole subprot visiting framework because using current subprot "cycles" may not provide coverage of all "full recursive loops" (cf. unfolding/unrolling all rec/continues) -- current framework gives coverage only if recursive subprots are only called from a single "location" -- maybe fixable by generalising subprotsigs record more than just the immediate proto+args context -- luckily some analyses like enabling check are OK despite this + // basically: current subprotocolsigs do identify a common "state" entry, but cannot be used to identify "specific" cycle paths or "maximal recursion paths" + } + or + { + 4() from A to B; + do Proto1Aux(A, B, C); + } + or + { + 2() from A to B; + //connect B to C; // Bad if non-det + 2() connect B to C; + 2() from B to C; + } +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B, role C) +{ + // Good + connect A to B; + connect B to C; + 1() from A to B; + do Proto1Aux1(A, B, C); +} + +aux global protocol Proto1Aux1(role A, role B, role C) +{ + choice at A + { + 3() from A to B; + 3() from B to C; + do Proto1Aux2(A, B, C); + } + or + { + 4() from A to B; + 4() from B to C; + //do Proto1Aux2(A, B, C); + } +} + +aux global protocol Proto1Aux2(role A, role B, role C) +{ + choice at A + { + 5() from A to B; + do Proto1Aux1(A, B, C); // Testing graph building (C vs. A/B) + //do Proto1Aux2(A, B, C); + } + or + { + 6() from A to B; + //connect B to C; + 6() from B to C; + } +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B, role C) +{ + connect A to B; + connect B to C; + 1() from A to B; + do Proto1Aux1(A, B, C); +} + +aux global protocol Proto1Aux1(role A, role B, role C) +{ + choice at A + { + 3() from A to B; + //3() from B to C; + do Proto1Aux2(A, B, C); // Testing mutually choice-unguarded "prunable" do's + } +} + +aux global protocol Proto1Aux2(role A, role B, role C) +{ + choice at A + { + 5() from A to B; + do Proto1Aux1(A, B, C); + //do Proto1Aux2(A, B, C); + } + or + { + 6() from A to B; + //connect B to C; + 6() from B to C; + } +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B, role C) +{ + connect A to B; + 1() from A to B; + do Proto1Aux1(A, B, C); +} + +aux global protocol Proto1Aux1(role A, role B, role C) +{ + do Proto1Aux2(A, B, C); +} + +aux global protocol Proto1Aux2(role A, role B, role C) +{ + choice at A + { + 2() from A to B; + do Proto1Aux1(A, B, C); + } + or + { + 3() from A to B; + connect B to C; + 4() from B to C; + } +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B, role C) +{ + connect A to B; + connect B to C; + 1() from A to B; + //1() from B to C; + do Proto1Aux1(A, B, C); +} + +aux global protocol Proto1Aux1(role A, role B, role C) +{ + () from A to B; + //() from B to C; + do Proto1Aux2(A, B, C); +} + +aux global protocol Proto1Aux2(role A, role B, role C) +{ + choice at A + { + 2() from A to B; + do Proto1Aux1(A, B, C); + //do Proto1Aux2(A, B, C); + } + or + { + 3() from A to B; + //connect B to C; + 4() from B to C; + } +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B, role C) +{ + connect A to B; + do Proto1Aux(A, B, C); +} + +aux global protocol Proto1Aux(role A, role B, role C) +{ + choice at A + { + 1() from A to B; + do Proto1Aux(A, B, C); // ProjectedSubprotocolPruner + } + or + { + 2() from A to B; + connect B to C; + 3() from B to C; + } +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B, role C) +{ + connect A to B; + choice at A + { + rec X + { + 2() from A to B; + continue X; + } + } + or + { + 3() from A to B; + } + connect A to C; // Good + 4() from A to C; +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B, role C) +{ + connect A to B; + connect B to C; + 1() from A to B; + choice at B + { + rec X + { + 2() from B to C; + continue X; + } + } + or + { + 3() from B to C; + } + connect A to C; // Bad: role liveness + 4() from A to C; +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B, role C) +{ + connect A to B; + choice at A + { + 1() from A to B; + //2() from A to B; // Uncomment bad + } + or + { + 1() from A to B; + rec X + { + connect B to C; + 4() from B to C; + 5() from C to B; + disconnect B and C; + continue X; + } + } +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B, role C, role D) +{ + connect A to B; + choice at A + { + 1() from A to B; + 1() from B to A; + connect B to C; + connect C to D; + } + or + { + 1() from A to B; + 1() from B to A; + connect B to D; + connect D to C; + } +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B, role C) +{ + choice at A + { + connect A to B; + //connect B to C; // Uncomment bad + } + or + { + connect A to C; + } +} +//*/ + + +/* +type "java.lang.Integer" from "rt.jar" as Int1; +type "java.lang.Integer" from "rt.jar" as Int2; + +explicit global protocol Proto1(role A, role B, role C) +{ + connect A to B; + do Proto1Aux1(A, B, C); +} + +aux global protocol Proto1Aux1(role A, role B, role C) +{ + choice at B + { + 1() from B to A; + do Proto1Aux2(A, C); + } + or + { + 2() from B to A; + do Proto1Aux2(A, C); + } + do Proto1Aux1(A, B, C); +} + +aux global protocol Proto1Aux2(role A, role C) +{ + // Bad: non-det connect followed by distinct payloads + connect A to C; + 3(T) from A to C; + 4() from C to A; + disconnect A and C; +} +//*/ + + +/* +type "java.lang.Integer" from "rt.jar" as Int1; +type "java.lang.Integer" from "rt.jar" as Int2; + +explicit global protocol Proto1(role A, role B, role C) +{ + // Good by basic model checking, but.. + connect A to B; + connect A to C; + do Proto1Aux1(A, B, C); +} + +aux global protocol Proto1Aux1(role A, role B, role C) +{ + choice at B + { + 1() from B to A; + do Proto1Aux2(A, C); + } + or + { + 2() from B to A; + do Proto1Aux2(A, C); // Bad: payload + } + do Proto1Aux1(A, B, C); +} + +aux global protocol Proto1Aux2(role A, role C) +{ + 3(T) from A to C; + 4() from C to A; +} +//*/ + + +/* +// Good: same payload +type "java.lang.Integer" from "rt.jar" as Int1; + +explicit global protocol Proto1(role A, role B, role C) +{ + // Good + connect A to B; + do Proto1Aux1(A, B, C); +} + +aux global protocol Proto1Aux1(role A, role B, role C) +{ + choice at B + { + 1() from B to A; + do Proto1Aux2(A, C); + } + or + { + 2() from B to A; + do Proto1Aux2(A, C); + } + do Proto1Aux1(A, B, C); +} + +aux global protocol Proto1Aux2(role A, role C) +{ + connect A to C; + 3(T) from A to C; + 4() from C to A; + disconnect A and C; +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B) +{ + connect from A to B; + do Proto1Aux(A, B); +} + +aux explicit global protocol Proto1Aux(role A, role B) +{ + 1() from A to B; +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B) +{ + // Basic connectedness tests + connect A to B; + //connect B to A; + disconnect A and B; + //1() from A to B; + //disconnect A and B; +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B, role C) +{ + connect A to B; + rec X + { + choice at A + { + 1() from A to B; + connect B to C; + 2() from B to C; + connect C to A; + 3() from C to A; + //3() from A to B; // Uncomment OK + disconnect B and C; + disconnect C and A; // Comment bad + continue X; + } + or + { + 4() from A to B; + } + } + //disconnect A and C; // Uncomment bad + disconnect A and B; +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B, role C) +{ + connect A to B; + rec X + { + choice at B + { + // Good, even though A not involved here + connect B to C + 2() from B to C; + 3() from C to B; + disconnect B and C; + continue X; + } + or + { + 4() from B to A; + } + } +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B) +{ + rec X + { + connect A to B + 1() from A to B; + 2() from B to A; + disconnect A and B; + connect B to A + 3() from A to B; + 4() from B to A; + disconnect B and A; + continue X; + } +} +//*/ + + +/* +global protocol Proto1(role A, role B) +{ + disconnect A and B; +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B) +{ + rec X + { + connect A to B; + choice at A + { + 1() from A to B; + //continue X; // Uncomment bad + } + or + { + 2() from A to B; + } + } +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B, role C) +{ + connect A to B; + choice at A + { + 1() from A to B; + rec X + { + connect B to C; + 1() from B to C; + //continue X; // Uncomment bad + } + } + or + { + 2() from A to B; + } +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B, role C, role D) +{ + connect A to B; + 1() from A to B; + //connect D to C; // Uncomment OK + 1() from C to D; +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B) +{ + connect A to B; // Comment bad + 1() from A to B; +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B) +{ + choice at A + { + connect A to B; + 1() from A to B; + } + or + { + 2() from A to B; // Bad: caught syntactically -- this blocked choice case won't manifest as an error state in the presence of a non-blocked co-case + // FIXME: could add implicit error actions (e.g. unconncted message passing) to model building, to make error states explicit + } +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B) +{ + choice at A + { + connect A to B; + 1() from A to B; + } + or + { + connect A to B; + 2() from A to B; + } +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B) +{ + // Good + connect A to B; + choice at B + { + 1() from B to A; + } + or + { + 2() from B to A; + } +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B) +{ + choice at B + { + connect A to B; // Bad + 1() from B to A; + } +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B) +{ + choice at A + { + connect A to B; + 1() from B to A; // Good + } +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B) +{ + connect A to B; + choice at B // Good + { + 1() from B to A; + } +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B, role C) +{ + connect A to B; + choice at A + { + 1() from A to B; + rec X + { + connect B to C; + 1() from B to C; + //continue X; // Uncomment bad + } + } + or + { + 2() from A to B; + } +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B) +{ + connect A to B; + //connect A to B; // Uncomment bad + //connect B to A; // Uncomment bad +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B, role C) +{ + connect A to B; + 1() from A to B; + //connect A to C; // Uncomment OK + 2() from A to C; +} +//*/ + diff --git a/scribble-test/src/test/scrib/tmp/Fixme.scr b/scribble-test/src/test/scrib/tmp/Fixme.scr new file mode 100644 index 000000000..53f6bea62 --- /dev/null +++ b/scribble-test/src/test/scrib/tmp/Fixme.scr @@ -0,0 +1,137 @@ +//$ bin/scribblec.sh modules/core/src/test/scrib/Fixme.scr -ip modules/core/src/test/scrib/ -d modules/core/src/test/scrib/ + +//http://sandbox.kidstrythisathome.com/erdos/ + + +module Fixme; + + + // TODO: (re)connect/wrap, e.g. SMTP + + // TODO: "introduces" well-formedness? + // e.g. "A from B to C;" + // e.g. "a from A to B; A[a] from B to C;" + // e.g. connect A to B; connect B to C; connect C to A; // connect A to C would be bad + //.. expliconn+introduces vs. delegation -- MPST with explicit (shared/sess) channels + + // TODO: API gen + // - connect/disconnect -- need to make backwards compatible with non-explicit + // -- non-explicit just has implicit initial connects -- just need to make sure no deadlock + // -- consider accept for callbacks? + // - factor out Scribble abstract transport wrappers with language-specific plugins; take as parameter for "wrap" action + // - non-det EFSMs -- minimisation will remove all mergeable non-det actions, but non-mergeable non-det actions can exist due to explicit connect + + +//.. output and connect can be mixed in a state... check where getStateKind used for any problems +// -- getTakeable in WFConfig for model building (but maybe ends up OK, just treat connect/accept the same way?) +// -- main approach should be generally consier mixed send/connect states, but differentiate connect for input blocking detection +//.. check orphan messages wrt connect/accept states -- maybe OK, orphan check does consider connectedness + + +// - scrib assertions for model checker -- check state visited? +// - parameterise subprotos on protos? + + +// FIXME: .. refactor interfaces for model building/checking/minimising/etc into state classes (make subclasses of Model/EndpointState -- cf. ast/del) + + +// ..is branching on accept+message more expressive than accept followed by branch? i.e. can connect always be "factored up" before the choice? -- maybe depends on interplay with select fairness (want to use connect to nest role scope inside choice case to avoid assuming fairness, but this can conflict with non-det accept?) + +//*** TODO introduces -- or explicit shared channel/port creation and passing ("open") + +// DONE: delete noLive or add to fair check +// DONE: decouple branch API gen from I/O i/f's -- duplicate enum in concrrete states? -- removed dependencies on I/O i/f's for Branch APIs where I/O i/f generation is disabled +// DONE: I/O i/f name max length -- 255 Linux/Windows/etc max file name length + +// CHECKME: check for (not yet supported) deleg actions in API gen +// CHECKME: delegation type payload projection +// CHECKME: '.' in Name constructor args -- no: rename constructor arg to simpname (cf SessionTypeFactory) +// MainContext.newJob -- move MainContext to core? + +// FIXME: Module.getGlobal/LocalProtocolDecl + + +// TODO: test API gen for (fair) SupplierInfo +// TODO: test connect/wrap API gen for SMTP +// TODO: MT/EDP server examples + + + +/* +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + 1() from A to B; + 3() from B to C; + 4() from A to C; // TODO: standard syntactic merge + } + or + { + 2() from A to B; + 3() from B to C; + 5() from A to C; + } +} +//*/ + + +/* +global protocol Proto1(role A, role B) +{ + (Proto2@C) from A to B; // FIXME: should not be aux? (or if aux should check WF as root?) +} + +aux global protocol Proto2(role C, role D) +{ + 1() from C to D; +} +//*/ + + +/* +explicit global protocol Proto(role A, role B, role C, role D) +{ + connect A to B; + connect C to D; + //... A, B // FIXME: investigate + //... C, D +} +//*/ + + +/* +explicit global protocol Proto(role A, role B, role C, role D) +{ + connect A to B; + connect A to C; + connect A to D; + connect C to D; + disconnect A and C; // FIXME: investigate + disconnect A and D; +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C, role D) +{ + rec X + { + choice at A + { + m1(Int) from A to B; + continue X; + //m4(int) from A to B; + } + or + { + m2(Int) from A to B; + //m3(int) from A to B; + } + 1() from C to D; // FIXME: wrong enabled check result -- maybe not? under unfolding it is captured inside the choice + } + //* / +} +//*/ + diff --git a/scribble-test/src/test/scrib/tmp/Quirk.scr b/scribble-test/src/test/scrib/tmp/Quirk.scr new file mode 100644 index 000000000..0e6d04e75 --- /dev/null +++ b/scribble-test/src/test/scrib/tmp/Quirk.scr @@ -0,0 +1,143 @@ +module Quirk; + + +/* +global protocol Proto1(role A, role B, role C, role D) +{ + rec X + { + 1() from C to D; // Enabling violation once unfolded + choice at A + { + 1() from A to B; + continue X; + } + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C, role D) +{ + choice at A + { + 1() from A to B; + 3() from B to C; // Not standard mergeable -- and cannot factor out syntactically + 4() from C to D; + 5() from B to A; + } + or + { + 2() from A to B; + 3() from B to C; + 6() from C to D; + 7() from B to A; + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + rec X + { + choice at A + { + 1() from A to B; + choice at B + { + 1() from B to C; + //continue X; // Non-enabled A under this choice at B + } + or + { + 3() from B to C; + //continue X; + } + continue X; // Scribble needs "sequencing" + } + or + { + 2() from A to B; + 2() from B to C; + } + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + rec X + { + 1() from A to B; + 2() from B to C; + 3() from B to C; + choice at A // Not mergeable by, e.g., ICALP13 + { + 4() from A to B; + continue X; + } + or + { + 5() from A to B; + 2() from B to C; // An "extra iteration" between B-C (but not A-B), but fine // Generates non-det B?2's for C to different states, but OK + 3() from B to C; + continue X; + } + } +} +//*/ + + +/* +type "java.lang.Integer" from "rt.jar" as Int1; +type "java.lang.Integer" from "rt.jar" as Int2; + + +global protocol Proto1(role A, role B) +{ + choice at A + { + //1() from A to B; // Uncomment still bad + 1(Int1) from A to B; + 2() from B to A; + } + or + { + 1(Int2) from A to B; // here, payloads aren't considered as distinguishing for labels + // error is the special case of actions that are non-deterministic labels up to payloads + // (Syntactic MPST merge not defined for repeat labels, Cf. -oldwf) + 3() from B to A; + } +} +//*/ + + +/* +type "java.lang.Integer" from "rt.jar" as Int1; +type "java.lang.Integer" from "rt.jar" as Int2; + + +// Cf. bad.safety.stuckmsg.payloads.Test01b +global protocol Proto1(role A, role B) +{ + choice at A + { + 1() from A to B; + 2(Int1) from B to A; + } + or + { + 1() from A to B; + 2(Int2) from B to A; // (Syntactic MPST merge not defined for repeat labels) + // here, payloads are considered as distinguishing (as default) -- whole I/O action used as label + // Cf.\ Test01b, non-deterministic actions of the same state + // here, actions on different states -- error manifests as regular stuck + } +} +//*/ + diff --git a/scribble-test/src/test/scrib/tmp/Test.scr b/scribble-test/src/test/scrib/tmp/Test.scr new file mode 100644 index 000000000..667109c1a --- /dev/null +++ b/scribble-test/src/test/scrib/tmp/Test.scr @@ -0,0 +1,4561 @@ +//Raymond@HZHL3 ~/code/scribble-java/scribble-java +//$ bin/scribblec.sh -ip scribble-test/src/test/scrib/ -d scribble-test/src/test/scrib/tmp/ scribble-test/src/test/scrib/tmp/Test.scr +//$ bin/scribblec.sh -ip scribble-test/src/test/scrib/ -d scribble-test/src/test/scrib/tmp/ scribble-test/src/test/scrib/tmp/Test.scr -api Proto1 B + +// OLD: +//$ java -cp modules/cli/target/classes/';'modules/core/target/classes';'modules/trace/target/classes';'modules/parser/target/classes';c:\Users\Raymond\.m2\repository\org\antlr\antlr-runtime\3.2\antlr-runtime-3.2.jar;'modules/validation/target/classes/';'modules/projection/target/classes/';C:\Users\Raymond\.m2\repository\org\codehaus\jackson\jackson-mapper-asl\1.9.9\jackson-mapper-asl-1.9.9.jar;C:\Users\Raymond\.m2\repository\org\codehaus\jackson\jackson-core-asl\1.9.9\jackson-core-asl-1.9.9.jar' org.scribble.cli.CommandLine -path modules/core/src/test/scrib/ modules/core/src/test/scrib/Test.scr +//$ java -cp modules/cli/target/classes/';'modules/core/target/classes';'modules/trace/target/classes';'modules/parser/target/classes';c:\Users\Raymond\.m2\repository\org\antlr\antlr-runtime\3.2\antlr-runtime-3.2.jar;'modules/validation/target/classes/';'modules/projection/target/classes/';C:\Users\Raymond\.m2\repository\org\codehaus\jackson\jackson-mapper-asl\1.9.9\jackson-mapper-asl-1.9.9.jar;C:\Users\Raymond\.m2\repository\org\codehaus\jackson\jackson-core-asl\1.9.9\jackson-core-asl-1.9.9.jar' org.scribble2.cli.CommandLine -path modules/validation/src/test/scrib/src modules/validation/src/test/scrib/src/Test.scr + + +//http://sandbox.kidstrythisathome.com/erdos/ + + +module tmp.Test; + +// TODO: replace a lot of FACTORY name calls by clone +// FIXME: -minlts states IDs don't match validation output + +// CHECKME: playing multiple roles in the same session instance (but what is the concrete notion of "process id"? -- if actually try to use, e.g., ThreadID, then have to track ownership of endpoints) + +// - API gen for connection-with-message +// - API gen for wrap (SMTP) +// - API gen for shared channel passing +// - callback API needs generic session-state arg + +// - Redo HTTP/SMTP message deserialization (and maybe ScribMsgFormatter i/f) -- deserialization routines should be per-message + +// Job modes (full/default, fase17, oldscrib, MPST, etc.) -- factor out GMConfig interface + +// FIXME: demo.bettybook.math.MathC cancelledkey exception + +// Add a unit test for validation to bypass aux + + +// TODO: port forwarding version of P2 -- funny case of "session" persisting over full disconnect, should/how to correlate? +// FIXME: good.liveness.Test02, reachability check (empty rec projection) + + + + + + + +//------------- +//- drop unused recs -- partly done by inlining, but not done yet for subprotos + +//- projection dependencies (projections as modules?) +//- check projected role/choice/do pruning/fixing? -- applies only to above proj? (i.e., proto decls) -- CHECKME: can do role fixing by getting roles from iproj? similarly do-pruning? + +//- connections +//- refactor ast to parser, refactor lang to type? -- separate protocol classes? +//- or: ast/del to new lang -- core lang to type, except protocol +//- remove unused visitors and del code -- move new visitors there? +//- shorten class names (e.g., Protocol->Proto), rename parser constants, revise ScribTreeAdaptor and DelDecorator +//- refactor model building +//- refactor do param/arg ast classes -- generally clean up AST class hierarchy +//- refactor parsing and CL +//- check demos + + // TODO make test framework to check proj->inline matches inline->proj + // TODO make test framework to check global-"proj"-via-taus matches actual proj -- matches mean language acceptance? + // could also test once-unfold-all against model + + +// Done: -- parser/ast refactoring + // change parsed to in jobcontext to record original roledecls (for GDo::project) -- and change getInlined on proto to prune (via getRoles on def) + // separate Job into core and lang parts (mainly parsed Module) + // move ast/del, old visit and new frontend to lang + // integrate new frontend with MainContext? + // move lang types to type.sess, and move new visit + // try modulecontextvisitor by "static lookup" + // try move antlrwrapper to parser again + //for isSingleConts (and project, buildGraph), make T visitWith(STypeReducer v) ? -- roleenabling and extchoicecons are more like reducers? + // refactor scribble.g, simplify ast/del/etc class names and deprecated class code + //...remove Token args from af constructors -- removed, and re-added + //refactor reconstructs to use af? -- refactored af and reconstruct to use addChildren1 -- FIXME + //...fix simp node constructors and af (no IdNode child) --- fix ambignodel to use af -- separate af methods +// done: For model build/check refactoring: + // add exp conn checks to model validation, maybe just as estatevisitor? (cf. prev syntactic connection checks) -- now done as global syntax visitor + // ...refactor -spin as an ext -- dropped -spin from master + +// parser/ast re-refactoring + // split mf to global/local subcomps, make protected constrs -- done + // check G/LType casts vs. SType (favour latter) -- done: simplified Seq elems, removed Do.proto N param + // ...store unfoldings in Context -- done + // use stypefactory in core -- also make visitorfactorys (both core and ast) -- done + // factor out all config factory methods more centrally? -- done a bit: mainly general factory method refactoring above + // rename addChildren1 -- done: addScribChildren + // ...make ad hoc ScribNode constructions go through af properly -- done + // rename ProtoMod, ProtocolMod -- rename core Protocol? -- done: ast renamed ProtoModNode + // explicit self roles/decls (core and ast) -- currently, self decls in protocols (in core) are purely cosmetic in toString -- done: just lselfdecl, basically for printing + // fix *imed*-projection (Job) choice subjects -- inlined-projection is a single proto with all roles -- done in core for now (and needs tidying) + // refactor doarg pruning, do pruning and extchoicesubj-fixing vistor passes (cf., entry methods into LProjection) -- done: for current uniformity, but TODO: actually should do the opposite + // fix self in ast locals, astfactory -- done: "self" rolenode is just a constant instance, only LSelfDecl is a special subclass + // wrap base class, more global base classes (maybe in del's) -- done: just wrap base classes -- TODO: further factoring, e.g., LDirectedInteraction getSelf/Peer + // Job Module projection, projected imports/nonprotodecls -- locals import globals for nonprotos? (better for "projects" clause?) -- done: basic, but nonprotos "copied" from globals -- TODO: import global? + + // Outstanding: + // refactor Core pass printing on pass entry + // test self comm + // ...disallow/check for reserved __ -- do in gtype translation? is mainly for codegen though? maybe also inlining? + // FIXME: qualifed sig name as non-role do-arg + // CHECKME: duplicate proto mods (unit tests) + + // refactor Set to Map -- Map to Set (HashSet is just a HashMap anyway) + // fully refactor imed/module projection to Job: old style subproto visitor for imed-projection do-pruning -- move imed-projs from Core to Job ? + // refactor imed projection role pruning? currently done once for globals, which is done for locals once and then pruning done again for do-args + // no? now only pruned? + // CHECKME: TODO: proto-param and do-nonrole-arg pruning? + +// Job/codegen refactoring: + // refactor G/LProtocol visitor entry methods back into visitors + // Check (minimise) Maven deps + // choice-specific fairness annotations + // fix codegen when -fair + // CHECKME: accept branching on messages (and safety properties) -- connection should not be established if message stuck? (cf. reception error) -- issue is implementation: what is a realistic semantics for sync-connect-branching (i.e., prevent client from async progressing after messaging) -- consider reversing client/server branching side? i.e. client requests, but then receives? (and consider serverside-branching a sugar?) + // fix state numbering? also numbering mismatch between outputs, e.g., minlts + // wrap API gen (and refactor wrap AST hierarchy, e.g., base classes) + // CHECKME: req/accept API with message -- accept branch API? + +// Later: + // re-check disamb pass -- e.g., do-target disamb done by translation (CHECKME: DoDel disamb -- should use af?) -- check, e.g., message transfer message disamb (signames, payloads) + // sort out full name expansion between disamb and translation -- fix modulecontextcollector for imported module member fullnames + // refactor additional disamb syntactic checks into core? e.g., do-calls, distinct roledecls, protodecls, etc. + // -- otoh, ast errors give source feedback -- maybe implement both + // Refactor PayElemNameNode + +// Test refactoring: + // refactor test to use main instead of cli + // add checking between projected-inlined against inlined-projected-imeds, graph building, etc. + // add finer-grained result verification + +// Multisend -- inference of multisend -- per-choice projection? + + + + + +data "..." from "..." as T; + + +//* +global protocol Proto1(role A, role B) +{ + 1(T) from A to B; +} +//*/ + + +/* +global protocol Proto1(role A, role B) +{ + do Proto1Aux(A, B); +} + +aux global protocol Proto1Aux(role C, role D) +{ + 2() from C to D; // Testing LDoArgPruner, do role pruning + //do Proto1(C, D); + do Proto1(D, C); // Testing -project output, proto deps +} +//*/ + + +/* +global protocol Proto1(role A, role B) +{ + 1() from A to B; + do Proto1Aux(B, A); +} + +aux global protocol Proto1Aux(role A, role B) +{ + 2() from A to B; + do Proto1(B, A); // Testing LDoArgPruner, this.self vs. target.self + //do Proto1(A, B); +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + do Proto1Aux(A, B); + } + or + { + 2() from A to B; + } + 4() from A to C; +} + +aux global protocol Proto1Aux(role A, role B) +{ + 3() from A to B; +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + 1() from A to B; + 1() from B to C; + choice at A + { + 2() from A to B; + 2() from B to C; + } + or + { + do Proto1Aux(A, B, C); // Testing SubprotoExtChoiceSubjFixer, both "forwards" and "reverse" do-refs + } +} + +aux global protocol Proto1Aux(role A, role B, role C) +{ + do Proto1(A, B, C); +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + 1() from A to B; + 1() from B to C; + } + or + { + do Proto1Aux(A, B, C); // Testing SubprotoExtChoiceSubjFixer, "forward" do-ref + } +} + +aux global protocol Proto1Aux(role A, role B, role C) +{ + do Proto1Aux1(A, B, C); +} + +aux global protocol Proto1Aux1(role A, role B, role C) +{ + 2() from A to B; + 2() from B to C; +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + 1() from A to B; + 1() from B to C; + } + or + { + do Proto1(A, B, C); // Testing SubprotoExtChoiceSubjFixer, need do-pruning as pre-req -- TODO: add unit test (cf. bad.liveness.roleprog.unfair.Test06) + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + 1() from A to B; + 1() from B to C; + choice at A + { + 2() from A to B; + 2() from B to C; + } + or + { + do Proto1(A, B, C); // Testing SubprotoExtChoiceSubjFixer, "reverse" do-ref + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C, role D) +{ + rec X + { + 5() from C to D; + continue X; + } + + choice at A + { + 1() from A to B; + 2() from A to B; + } + or + { + 1() from A to B; + 3() from B to A; // Testing wait-for cycle detection // Also tests eventual reception + } +} +//*/ + + +/* +global protocol Proto1(role A, role B) +{ + choice at A + { + 1() from A to B; // Testing global model building, non-det edges (identical configs collapsed) + 2() from A to B; // Un/comment, test combinations + } + or + { + 1() from A to B; + //3() from B to A; + } +} +//*/ + + +/* +global protocol Proto1(role A, role B) +{ + connect A to B; // Testing SGraph.getTraceFromInit, error in init state (empty trace) +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + 1() from A to B; + } + or + { + 1() from A to C; // Same message OK + } + do Proto1(A, B, C); +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B, role C) +{ + choice at A + { + connect A to B; + 1() from A to B; + disconnect A and B; + } + or + { + connect A to C; + 1() from A to C; // Same message OK + disconnect A and C; + } + do Proto1(A, B, C); +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B, role C) +{ + connect A to B; // TODO: junit tests for explicit + rec X + { + choice at A + { + 1() from A to B; + continue X; + } + or + { + 2() from A to B; + connect A to C; + 3() from A to C; + } + } +} +//*/ + + +/* +global protocol Proto1(role A, role B) +{ + rec X + { + choice at A + { + 1() from A to B; + continue X; + } + or + { + 3() from A to B; + } + } + choice at B // Testing this.collections remove in EGraphBuilderUtil + { + 2() from B to A; + } +} +//*/ + +/* +global protocol Proto1(role A, role B, role C) +{ + rec X + { + 1() from A to B; + 2() from B to C; + choice at A + { + continue X; // TODO: add junit test, testing inlined choice subj fixing + } + or + { + continue X; + } + } +} +//*/ + +/* +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + rec X + { + 1() from A to B; + } + } + or + { + 2() from A to B; + 3() from A to C; + } +} +//*/ + +/* +global protocol Proto1(role A, role B, role C) +{ + choice at A // TODO: add junit test, testing core inlined projection choice subjects (for C) -- test already exists? // Also testing imed projections + { + 1() from A to B; + 1() from B to C; + } + or + { + 2() from A to B; + 2() from B to C; + } +} +//*/ + +/* +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + 1() from A to B; // TODO: add junit, testing -project C [-fair] -- basically, Travel Agent + do Proto1(A, B, C); + } + or + { + 2() from A to B; + 2() from A to C; + } +} +//*/ + + +/* +global protocol Proto1(role A, role B) +{ + choice at A + { + 1() from A to B; + //2() from A to B; + } + or + { + 1() from A to B; + //3() from A to B; + } + //4() from B to A; + do Proto1(A, B); +} +//*/ + + +/* +global protocol Proto1(role A, role B) +{ + choice at A + { + 1() from A to B; + } + or + { + 1() from A to B; + } // CHECKME: gives a non-det global model, correct/intended? + //4() from B to A; + do Proto1(A, B); +} +//*/ + + +/* +global protocol Proto1<>(role A, role B) // TODO: add unit test, testing empty paramdecls +{ + () from A to B; + do Proto1<>(A, B); // TODO: add unit test, testing empty nonroleargs +} +//*/ + +/* +sig "..." from "..." as M; + +global protocol Proto1(role A, role B) +{ + MM from A to B; + do Proto1(A, B); // TODO: add unit test, testing qualified sig name as nonrole arg +} +//*/ + + +/* +explicit global protocol Proto1(role A__, role B) +{ + () connect A__ to B; + rec X + { + () from A__ to B; // TODO: add double underscore check (e.g., translation) + continue X; + } +} +//*/ + + +/* +global protocol Proto1(role A, role B) +{ + rec X { + //1() from A to B; + //1(Test.T) from A to B; + 1(T) from A to B; + M from B to A; + //do Proto1(A, B); + continue X; + } +} +//*/ + + +/* +explicit global protocol Foo(role A, role B, role C) +{ + connect A to B; + do FooAux(A, B, C); +} + +aux explicit global protocol FooAux(role A, role B, role C) +{ + choice at A + { + 1() from A to B; + do FooAux(A, B, C); + } + or + { + 2() from A to B; + connect A to C; + 3() from A to C; + } +} +//*/ + + +/* +explicit global protocol Foo(role A, role B, role C) +{ + connect A to B; + choice at A + { + 1() from A to B; + } + or + { + 2() from A to B; + connect A to C; + 3() from A to C; + } +} +//*/ + + +/* +explicit global protocol Foo(role A, role B) +{ + //connect A to B; + 1() from A to B; + disconnect A and B; + connect A to B; + 1() from A to B; +} +//*/ + + +/* +global protocol Foo(role A, role B, role C) +{ + 1() from A to B; // Testing LProjectionTranslator, onto B + do Bar(A, C); +} + +aux global protocol Bar(role D, role E) +{ + 2() from D to E; +} +//*/ + + +/* +explicit global protocol Foo(role A, role B, role C) +{ + 0() connect A to B; + choice at A + { + 1() from A to B; + //disconnect A and B; + do Foo(A, B, C); + } + or + { + 2() from A to B; + foo() connect A to C; + 3() from A to C; + } +} +//*/ + + + +/*// Add unit test -- testing: inlining of shadowed recvars +global protocol Foo(role A, role B) +{ + rec X + { + rec X + { + 1() from A to B; + continue X; + } + } +} +//*/ + + +/* // Add unit test -- testing: repeat rec sigs in inlining due to multilple do's, w.r.t. unfolding +global protocol Foo(role A, role B) +{ + do Bar(A, B); + do Bar(A, B); +} + +aux global protocol Bar(role A, role B) +{ + 1() from A to B; +} +//*/ + + +/* // Add unit test -- testing: repeat rec sigs in inlining due to multilple do's, w.r.t. unfolding +global protocol Foo(role A, role B) +{ + choice at A + { + do Bar(A, B); + } + or + { + do Bar(A, B); + } +} + +aux global protocol Bar(role C, role D) +{ + 3() from C to D; + do Bar(C, D); +} + + +/* +global protocol Proto1(role A, role B) +{ + rec X + { + 1() from A to B; + choice at A + { + continue X; + } + or + { + 2() from A to B; + continue X; + } + } +} +//*/ + + +/* +global protocol Proto1(role A, role B) +{ + rec X + { + 1() from A to B; + choice at A + { + rec Y + { + 0() from A to B; + //do Proto1(A, B); + continue X; + } + } + } +} +//*/ + + + +/* +global protocol Proto1(role A, role B) +{ + choice at A + { + rec X + { + 1() from A to B; + continue X; + } + } +} +//*/ + + +/* +global protocol Proto1(role A, role B) +{ + 1() from A to B; + choice at A + { + do Proto1Aux(A, B); + //do Proto1(A, B); + } + or + { + do Proto1Aux2(A, B); + } + or + { + 2() from A to B; + } +} + +aux global protocol Proto1Aux(role A, role B) +{ + 0() from A to B; + do Proto1(A, B); + //do Proto1Aux(A, B); +} + +global protocol Proto1Aux2(role A, role B) +{ + 3() from A to B; + do Proto1Aux2(A, B); +} +//*/ + + +/* +global protocol Proto1(role A, role B) +{ + rec X + { + 0() from A to B; + choice at A + { + 1() from A to B; + //do Proto1(A, B); + continue X; + //3() from A to B; + } + or + { + 2() from A to B; + } + //4() from A to B; + } + 5() from A to B; +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + //1() from A to B; + 1() from A to C; + } + or + { + //2() from C to A; + //2() from A to B; + 2() from A to C; + //2() from B to C; + } +} +//*/ + + +/* +global protocol Proto1(role A, role B) +{ + do Proto1Aux(A, B); +} + +global protocol Proto1Aux(role AA, role BB) +{ + () from AA to BB; +} +//*/ + + +/* +global protocol Proto1(role A, role B) +{ + 0() from A to B; + choice at A + { + 1() from A to B; + do Proto1(A, B); + } + or + { + 2() from A to B; + 3() from A to B; + } + 4() from A to B; +} +//*/ + + +/* +global protocol Proto1(role A, role B) +{ + choice at A + { + rec X + { + 1() from A to B; + continue X; + } + } + or + { + 2() from A to B; + } +} +//*/ + +/* +global protocol Proto1(role A, role B) +{ + 1() from A to B; + choice at A + { + do Proto1(A, B); + } + or + { + 2() from A to B; + } +} +//*/ + +/* +global protocol Proto1(role A, role B) +{ + rec X + { + choice at A + { + 1() from A to B; + } + or + { + 2() from A to B; + 3() from B to A; + //do Proto1(A, B); + //continue X; + do Proto1(B, A); + } + } +} +//*/ + + +/* +//type "System.UInt32" from "..." as int; + +global protocol Proto1(role A, role B) +{ + Foo() from A to B; + /*choice at A + { + 1() from A to B; + } + or + { + 2() from A to B; + }* / +} +//*/ + + + + + +/* +type "System.UInt32" from "..." as int; + +global protocol SH(role P, role R, role C) +{ + plane(int, int, int, int) from P to R; + do Loop(P, R, C); +} + +aux global protocol Loop(role P, role R, role C) +{ + choice at P + { + Above(int) from P to R; + Res(int) from R to P; + Above(int) from P to R; + Res(int) from R to P; + choice at P + { + BothIn() from P to R; + BothIn(int) from P to C; + do Loop(P, R, C); + } + or + { + BothOut() from P to R; + BothOut() from P to C; + do Loop(P, R, C); + } + or + { + Intersect() from P to R; + Res(int) from R to P; + choice at P + { + One(int) from P to C; + do Loop(P, R, C); + } + or + { + Two(int, int) from P to C; + do Loop(P, R, C); + } + } + //do Loop(P, R, C); // FIXME: -spin fail if commented + } + or + { + Close() from P to R; + Close() from P to C; + } +} +//*/ + +/* +global protocol SH2(role P, role R, role C) +{ + plane(x1:int, x2:int, x3:int, x4:int) from P to R; + do Loop2(P, R, C); +} + +aux global protocol Loop2(role P, role R, role C) +{ + choice at P + { + Above(v1:int) from P to R; + Res(b1:int) from R to P; + Above(v2:int) from P to R; + Res(b2:int) from R to P; + choice at P + { + BothIn() from P to R; + BothIn(r1:int) from P to C; + do Loop2(P, R, C); + } + or + { + BothOut() from P to R; + BothOut() from P to C; + do Loop2(P, R, C); + } + or + { + Intersect() from P to R; + Res(i:int) from R to P; + choice at P + { + One(r2:int) from P to C; + do Loop2(P, R, C); + } + or + { + Two(r3:int, r4:int) from P to C; + do Loop2(P, R, C); + } + } + } + or + { + Close() from P to R; + Close() from P to C; + } +} +//*/ + + + + + + + + +/* +global protocol Proto1(role A, role B, role C) +{ + rec X { + choice at A { + a() from A to B; + b() from B to C; + continue X; + } or { + c() from A to B; + d() from B to C; + } + } +} +//*/ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +/* +explicit global protocol Proto1(role A, role B) +{ + choice at A + { + 1() connect A to B; + } + or + { + 2() connect A to B; + } + 2() connect A to B; +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B, role C) +{ + connect A to B; + rec X + { + connect B to C; + choice at B + { + 1() from B to C; + disconnect B and C; + continue X; + } + or + { + 2() from B to C; + 3() from C to B; + } + } + //3() from C to B; // Testing unconnected errors -- error by syntactic check; but should *not* by -f17 if seq comp supported + 4() from B to A; +} +//*/ + + +/* +global protocol Proto1(role A, role B) +{ + 1() from A to B; + 1() from A to B; + choice at A + { + 1() from A to B; + choice at A + { + 1() from A to B; + } + } + or + { + 2() from A to B; + rec X + { + rec Y + { + 2() from A to B; + continue X; + } + } + } +} +//*/ + + + +/* +global protocol Proto1(role A, role B, role C) +{ + 1() from A to B; + rec X // Testing: projecting-pruning (for B) -- cf., syntactic merge (cannot merge X and end) + { + choice at A + { + 2() from A to C; + continue X; + } + or + { + 3() from A to C; + } + } +} +//*/ + +/* +global protocol Proto1(role A, role B, role C) +{ + rec X // Testing: projecting-pruning (for B) -- X not pruned (becomes single "unguarded" X case) with safety errors + { + 1() from A to B; + choice at A + { + 2() from A to C; + continue X; + } + or + { + 3() from A to C; + //continue X; // OK if uncommented + } + } +} +//*/ + +/* +global protocol Proto1(role A, role B, role C) +{ + 1() from A to B; + rec X // Testing: projecting-pruning (for B) + { + choice at A + { + 2() from A to C; + continue X; + } + or + { + 3() from A to C; + continue X; + } + } +} +//*/ + +/* +global protocol Proto1(role A, role B, role C) +{ + rec Y + { + 1() from A to B; + rec X + { + choice at A + { + 2() from A to C; + continue Y; + } + or + { + 3() from A to C; + continue X; // Testing: projecting-pruning (for B) -- role progress violation for B + } + } + } +} +//*/ + +/* +global protocol Proto1(role A, role B, role C) +{ + 1() from A to B; + rec Y // Testing: projecting-pruning (for B) + { + rec X + { + choice at A + { + 2() from A to C; + continue Y; + } + or + { + 3() from A to C; + continue X; + } + } + } +} +//*/ + +/* +global protocol Proto1(role A, role B, role C) +{ + rec X + { + 1() from A to B; + rec Y + { + 2() from A to C; + continue X; // Testing projection-pruning (for B) -- not pruned + } + } +} +//*/ + +/* +global protocol Proto1(role A, role B, role C) +{ + 1() from A to B; + rec X + { + rec Y + { + 2() from A to C; + continue X; // Testing projection-pruning (for B) -- pruned + } + } +} +//*/ + + + +/* +global protocol Proto1(role A, role B, role C) +{ + rec X + { + choice at A + { + 1() from A to B; + 1() from A to C; + } + or + { + 2() from A to C; + continue X; + } + or + { + 2() from A to B; // Bad: C may be stuck waiting for 1/2 + } + } + 3() from A to C; +} +//*/ + +/* +global protocol Proto1(role A, role B, role C) +{ + rec X + { + choice at A + { + 1() from A to B; + 1() from B to C; + } + or + { + 4() from A to B; + continue X; + } + or + { + 2() from A to B; // Bad: C stuck waiting for 1 + } + } + 3() from A to C; +} +//*/ + +/* +global protocol Proto1(role A, role B, role C) +{ + rec X + { + choice at A + { + 1() from A to B; + 1() from B to C; + } + or + { + 2() from A to B; + continue X; + } + } + 3() from A to C; // Testing -fair and sequencing +} +//*/ + +/* +global protocol Proto1(role A, role B, role C) +{ + rec X + { + choice at A + { + 1() from A to B; + 1() from B to C; + } + or + { + 2() from A to B; + } + 3() from A to C; + // TESTING: from some global perspectives, this could be seen as a mixed-role choice for C between B and A + // Any way to create an unsound mixed-role choice using sequencing? And taking the mixed-role choice view + // What fixes this may be that Scribble actually projects this as sequencing, not choice? + // -- N.B. comes out as unfinished error, not deadlock (A is in output state) + // -- In this way, bounded channels actually helpful for detecting stuck messages? -- or would just come out as role-progress violation, in the worse case? + // -- As opposed to "inlining the continuation" (or projecting a tau?) + // At least, not having sequencing probably safe backup? + continue X; + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + rec X + { + 1() from B to A; + choice at B // Testing projection, A not syntactically in this choice but cannot discard the X -- handled by UnfoldingVisitor(?) + { + 2() from B to C; + continue X; + } +// or // Testing +// { +// 3() from B to C; +// } + } +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B, role C) +{ + 1() connect A to B; + 1() connect B to C; + 1() connect C to A; // Testing accept-correlation check +} +//*/ + + +/* +global protocol Proto1(role A, role B) +{ + rec X + { + choice at A + { + continue X; + } + or + { + 2() from A to B; + } + } +// rec X +// { +// 1() from A to B; +// 1() from B to C; +// choice at A +// { +// 2() from A to B; // Testing projection -- just X for C, but under a non-empty recursive prefix +// continue X; +// } +// or +// { +// 3() from A to B; +// 3() from B to C; +// } +// } +} +//*/ + + +/* +global protocol Proto1(role A, role B) +{ + // Testing unfair transform + rec X + { + choice at A + { + 1() from A to B; + choice at A + { + 1a() from A to B; + } + or + { + 1b() from A to B; + continue X; + } + } + or + { + 1c() from A to B; + continue X; + } + or + { + 2() from A to B; + choice at A + { + 2a() from A to B; + continue X; + } + or + { + 2b() from A to B; + continue X; + } + } + or + { + choice at A + { + 3() from A to B; + } + or + { + 4() from A to B; + } + } + } +} +//*/ + + +/* +global protocol Proto1(role A, role B) +{ + rec X + { + choice at A // Testing unfair transform of recursive non-det choice + { + 1() from A to B; + choice at A + { + 2() from A to B; + } + or + { + 3() from A to B; + } + } + or + { + 1() from A to B; + 4() from A to B; + } + continue X; + } +} +//*/ + + +/* // TODO: more unfinished (and accept-correlation) role tests +global protocol Proto1(role A, role B) +{ + choice at A + { + 1() from A to B; + 1() from A to B; // FIXME unfinished term not reported -- FIXME: still need to check good terms (taking accept-guarded states into account) + 1() from A to B; + 2() from B to A; + } + or + { + 1() from A to B; + 1() from B to A; + 1() from B to A; + 2() from A to B; + } +} +//*/ + + +/* Testing aux protocol as CommandLine root protocol +aux global protocol Proto1(role A, role B) +{ + 1() from A to B; +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + 1() from A to B; + 5() from A to C; // A "non-det merge" that cannot be refactored by prefixing/sequencing + 3() from B to A; + } + or + { + 2() from A to B; + 5() from A to C; + 4() from B to A; + } +} +//*/ + + +//--- correlation + +/* +explicit global protocol Proto1(role A, role B) +//explicit global protocol Proto1(role A, role B, role C) +{ +// 1() connect A to B; // Bad +// disconnect A and B; +// 1() connect A to B; +// 2() from A to B; +// disconnect A and B; + +// 1() connect A to B; // Bad +// disconnect A and B; +// 2() connect A to B; +// disconnect A and B; + +// 1() connect A to B; // OK: this is what theabove should be intuitively +// disconnect A and B; +// 2() connect A to C; +// disconnect A and C; + +// 1() connect A to B; // Morally OK -- but conservatively rule out by syntactic condition -- do via modelling? endpoint transformations? (B should actually be a branch 1 or 2) -- or global model based on two concurent instances of each endpoint? (two enough?) -- mergeability of all accepts +// disconnect A and B; +// 1() connect A to B; +// disconnect A and B; +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B, role C) +{ + 1() connect A to B; // FIXME: correlation + 2() connect A to C; + 3() connect B to C; +} +//*/ + + +/*/ +explicit global protocol Proto1(role A, role B, role C) +{ + // OK + choice at A + { + 1() connect A to C; + choice at A + { + 1() connect A to B; + } + } + or + { + 2() connect A to C; + choice at A + { + 2() connect A to B; + } + } +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B) +{ + 1() connect A to B; + disconnect A and B; + 1() connect A to B; +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B) +{ + choice at A + { + 1() connect A to B; + disconnect A and B; + } + or + { + 2() connect A to B; + disconnect A and B; + } + 3() connect A to B; +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B) +{ + connect A to B; + do Proto1Aux(A, B); +} + +aux global protocol Proto1Aux(role A, role B) +{ + disconnect A and B; + //connect A to B; // Bad +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B) +{ + 1() connect A to B; + disconnect A and B; + 1() connect A to B; +} +//*/ + +//---correlation + + +/* +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + 1() from A to B; + 1() from A to C; + } + or // Not OK: projection treats C?A:1 as single-case choice + { + 2() from A to B; + } + 3() from A to C; +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + // CHECKME: orphans currently detected on local termination, not full system termination (same for stuck and deadlock) + choice at A { + 1() from A to B; + 2() from A to C; + 3() from B to C; + 4() from C to A; + } or { + 1b() from A to B; + 3() from B to C; // -nolocalchoicecheck to show orphans + 4() from C to A; + } +} +//*/ + + +/* +global protocol Proto1(role A, role B) +{ + rec X + { + 1() from A to B; + do Proto1Aux(A, B); // Testing recvar name disambiguation + } +} + + +global protocol Proto1Aux(role A, role B) +{ + rec X + { + 2() from A to B; + choice at A + { + continue X; + } + or + { + 3() from A to B; + } + } +} +//*/ + + +/* +global protocol Proto1(role A, role B) +{ + rec X + { + 1() from A to B; + rec X + { + choice at A + { + 2() from A to B; + choice at A + { + continue X; + } + or + { + 3() from A to B; + } + } + or + { + //4() from A to B; + continue X; // Testing unguarded shadowed recvars at different nestings + } + or + { + 5() from A to B; + } + } + } +} +//*/ + + +/* +global protocol Proto1(role A, role B) +{ + rec X + { + 1() from A to B; + choice at A + { + rec X + { + 2() from A to B; + continue X; + } + } + or + { + rec X // Testing shadowed unguarded recs + { + 3() from A to B; + continue X; + } + } + or + { + 4() from A to B; + continue X; + } + } +} +//*/ + + +/* +global protocol Proto1(role A, role B) +{ + rec X + { + 1() from A to B; + rec X + { + 2() from A to B; + choice at A + { + continue X; // Testing inlined-unfolding for shadowed recs + } + or + { + 3() from A to B; + } + } + } +} +//*/ + + +/* +global protocol Proto1(role A, role B) +{ + rec X + { + choice at A + { + 1() from A to B; + 2() from B to A; + continue X; + } or { + 1() from A to B; + 3() from B to A; // Testing non-det unfair-transform ("unfairness" has the power to enforce a single case out of non-det options) + continue X; + } + } +} +//*/ + + +/* +global protocol Proto1(role A, role B) +{ + rec X + { + choice at A + { + 1() from A to B; + 2() from B to A; + continue X; // Testing non-det unfair-transform + } or { + 1() from A to B; + 3() from B to A; + } + } +} +//*/ + + +/* +global protocol Proto1(role A, role B) +{ + rec X + { + choice at A + { + 1() from A to B; + continue X; // Testing non-det unfair-transform + } or { + 1() from A to B; + } + } +} +//*/ + + +/* +global protocol Proto1(role A, role B) +{ + disconnect A and B; + do Proto1Aux(A, B); +} + +// Trivial test for "expressiveness" of aux -- but could just make explicit.. // CHECKME example where "aux" is fully needed +aux global protocol Proto1Aux(role A, role B) +{ + connect A to B; +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + rec X + { + choice at A + { + 1() from A to B; + //1() from A to C; + continue X; // Testing fairness + } + or + { + 2() from A to B; + 2() from A to C; + continue X; + } + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + 1() from A to B; + 3() from B to C; + 4() from C to B; + 5() from B to C; + } + or + { + 2() from A to B; + 3() from B to C; // Syntactic merge means: non-det "squashed" so original choice path now ambiguous, so we need to act conservatively -- conservatively means squashed role needs to accept any incoming messages as a branch (to handle ambiguity) while not being allowed to make any output choices (only unary send allowed, so must be identical in all possibilities) + // EFSM transform has to follow this intuition, full continuations after a non-det input choice have to be convservatively squashed (and if not squashable, then check model using unsquashed version) -- or implement as syntactic merge, and use original if not mergeable + 4() from C to B; + 6() from B to C; + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C, role D) +{ + choice at A + { + 1() from A to B; + 3() from B to C; + 3() from B to D; + 4() from C to D; + } + or + { + 2() from A to B; + 3() from B to C; + 3() from B to D; + 5() from C to D; + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C, role D) +{ + choice at A + { + 1() from A to B; + 3() from B to C; + 4() from C to D; + } + or + { + 2() from A to B; + 3() from B to C; + 5() from C to D; // Not mergeable by ICALP13 + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + 1() from A to B; + 3() from B to C; + 4() from C to B; + } + or + { + 2() from A to B; + 3() from B to C; + 4() from C to B; + 5() from C to B; // Tricky to check, e.g., output state sub-EFSMs are the same (cf. syntactic equality) for terminating the merge, maybe need strict isomorphism (without renaming) + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + rec X + { + 0() from B to C; + choice at A + { + 1() from A to B; + 3() from B to C; + 4() from B to C; + } + or + { + 2() from A to B; + 3() from B to C; + 5() from B to C; // Consider EFSM of C for merging -- do non-det input squashing inductively, and only if no recursive edges back to original or preceding state? -- difficult to confirm, e.g., output state sub-EFSMs are the same (cf. syntactic equality) for terminating the merge, maybe need isomorphism + continue X; + } + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + 1() from A to B; + 3() from B to C; + 4() from B to C; + } + or + { + 2() from A to B; + 3() from B to C; + //5() from B to C; // Makes merge easier + rec X + { + 5() from B to C; // Consider EFSM of C for merging + continue X; + } + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + 1() from A to B; + 3() from B to C; + 3() from B to C; + 4() from B to C; + } + or + { + 2() from A to B; + 3() from B to C; // Merging (non-det input state "squashing") first messages only not enough (cf. inductive syntactic merge) + 3() from B to C; + 5() from B to C; + } +} +//*/ + + +/* +global protocol Proto1(role A, role B) +{ + rec X + { + 1() from A to B; + choice at A + //choice at B + { + continue X; + } + or + { + 2() from A to B; + //2() from B to A; + } + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + 1() from A to B; + choice at A + { + 1a() from A to B; + 1a() from A to C; + } + or + { + 1b() from A to B; + 1b() from A to C; + } + } + or + { + 2() from A to B; + choice at A + { + 2a() from A to B; + 2a() from B to C; + } + or + { + 2b() from A to B; + 2b() from B to C; + } + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + rec X + { + 1() from A to B; + continue X; + } + } + or + { + 2() from A to B; + } + 3() from C to A; + 3() from C to A; // Role-progress violation for C under WF_1 + choice at A + { + 4() from A to B; + 5() from B to A; + } + or + { + 4() from A to B; + 6() from B to A; + } +} +//*/ + + +/* +// Counter example to completeness of safety for current WF +global protocol Proto1(role A, role B, role C) { + choice at A { + 1() from A to B; + 3() from B to C; + 4() from A to C; + } or { + 2() from A to B; + 3() from B to C; + 5() from A to C; // FIXME: should be mergable as a branch at C? (yes, by ICALP13) -- but requires treating non-det as det (i.e. language equiv. vs. bisim? -- local language minimisation wrt. inputs only?) -- in general, consider subsequent B and C interactions; but this exact example should be safe + } +} +//*/ + + +/* +global protocol Proto1(role A, role B) +{ + 1() from A t B; // Testing Antlr error display overriding +} +//*/ + + +/* +type "java.lang.Integer" from "rt.jar" as Int; + +global protocol Proto1(role A, role B) +{ + choice at A + { + 1() from A to B; + } + or + { + 1(Int) from A to B; // Testing bad payloads + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + 1() from A to B; + 2() from B to C; + 3() from C to A; + } + or + { + 4() + from A to B; + 5() from B to C; // "Standard merge" (ICALP13) -- 2/5 cases merged for input choice at C // but is it actually mergable in ICALP13/WADFEST? because only defined on branch, not select as needed for C here -- it's fine, only merging the top level branches (distinct labels) + 6() from C to A; + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + 1() from A to B; + 2() from B to C; + 3() from C to A; + } + or + { + 4() from A to B; + 2() from B to C; + 3() from C to A; // Not mergeable by WADFEST, because continuations of C to be merged are not input-branches (but WAFDEST could probably be extended easily -- most simply by just allowing TmergeT for any T, not just branch -- more generally, would have to inductively coerce non-branches into branches, which is what the below example (i.e. WADFEST) is a special case of) + // However, mergeable by ICALP13 (just a typo by WADFEST) + // (WADFEST merges also only defined on branches, not receives, but receive can be easily converted to singleton branches? -- a point of directed branches is that they have no payloads, and receives have no labels, which Scribble needs to consider) + } +} +//*/ + + +/* +// Counter example to completeness of safety for current WF -- this notion of completeness is wrt. a global semantics, but not wrt. specific definition of Scribble projection/EFSM? (i.e. if we project/build a subsequent input choice at C from A, not just the initial one from B -- this is essentially mixing a ``non-choice'' (pre-determined flow) at A with an external choice at C -- i.e. ICALP13/WADFEST merge: convert non-det external choice into det non-choice followed by inductively merged (external choice) continuations) -- actually not necessarily, can consider still non-det, but just that the continuation branches are safe (but this view is more like inferring non-directly specified cases for nested branches) +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + 1() from A to B; + 2() from B to C; + //choice at A { // better for merging? + 3() from A to C; + //} + } + or + { + 1b() from A to B; + 2() from B to C; + 4() from A to C; // FIXME: "merge/coerce" branches for C -- implement as some king of variant of "determinisation"? i.e. 2.3+2.4 -> 2.(3+4) (issue is it's not bisim preserving -- is local language minimisation a sound general principle? well, not for the minimal non-det branch example (or actually, yes? see below), but somehow only for "nested" external choices? i.e. same-label mergability?) + } +} +//*/ + + +/* +global protocol Proto1(role A, role B) +{ + choice at A + { + 1() from A to B; + 2() from B to A; // FIXME: should we just language-equiv minimise endpoints? implicitly take that as the CFSM meaning of this global protocol? depends on global semantics -- but would make general projection/graphbuilding and mergability more uniform? -- uniformity should be the aim, see below -- no: not just independent EFSM minimisation, but should consider the whole CFSM system, see below + } + or + { + 1() from A to B; + 3() from B to A; + } +} +//*/ + + +/* +global protocol Proto1(role A, role B) +{ + choice at A + { + 1() from A to B; + 3() from B to C; + 4() from C to A; + } + or + { + 2() from A to B; + 3() from B to C; + 5() from C to A; // FIXME: language minimising at C will determinise, but minimising at A has no effect: minimising makes (non-det) external choice at C into internal choice, which is incompatible with original internal choice at A -- so independent language minimising is not sound -- basically syntactic branch-only merging restricts "determinising" to external choices only -- so do independent EFSM language-minimisation applied to inputs only? (but sometimes non-det outputs can be safely minimised -- but just leave them as is for global model checking?) + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + 1() from A to B; + } + or + { + 1() from A to B; // Simply syntactically not representable with directed choice, but safe under the same intuition as mergability -- in this case, independent endpoint minimisation modifies both A and B consistently + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + 1() from A to B; + 2() from B to C; + //choice at A + //{ + // 4() from A to C; + //} + //or + //{ + // 3() from A to C; + //} + do Proto1Aux(A, C); // WADFEST merge -- morally: WADFEST merge "infers" safe branche cases for nested branches -- can factor out by subprotos + // NO: WADFEST prevents internal choice 4/5 by A, only allows external choice by C + } + or + { + 1b() from A to B; + 2() from B to C; + //choice at A + //{ + // 4() from A to C; + //} + //or + //{ + // 3() from A to C; + //} + do Proto1Aux(A, C); + } +} + +// Makes clear that TmergeT for any T should be OK +aux global protocol Proto1Aux(role A, role C) +{ + choice at A + { + 3() from A to C; + } + or + { + 4() from A to C; + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + 1() from A to B; + 2() from B to C; + 3() from C to A; + } + or + { + 4() from A to B; + 2() from B to C; + 5() from C to A; // TODO: most general merge: coerce an external choice for A here -- less morally clear than, e.g., WADFEST restriction to branch-only merge though + } +} +//*/ + + +/* +type "java.lang.Integer" from "rt.jar" as Int; + +global protocol Proto1(role A, role B, role C) +{ + choice at A { + buyer1(Int) from A to B; // Total + (Int) from B to A; // B will pay this much + buyer2(Int) from A to C; // C will pay remainder + } or { + buyer1(Int) from A to C; // Total + (Int) from C to A; // C will pay this much + buyer2(Int) from A to B; // B will pay remainder + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C, role D) +{ + ..(syntactic) reachability tests +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + 1() from A to B; + 1() from A to C; + } + or + { + 2() from A to B; + } + 3() from A to C; // TODO: "optional": needs empty actions and "empty-removal" transformation +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + rec X + { + choice at A + { + 1() from A to B; + 1() from B to A; + 3() from A to C; // Trying to find an unfair-transformation problem wrt. not visiting "2" case after "1" transitions + continue X; + } + or + { + 2() from A to B; + 2() from B to A; + 3() from A to C; + } + } +} +//*/ + + +/* +global protocol Proto1(role A, role B) +{ + 1() from A to B; + 2() from B to C; // Testing CommandLine with, e.g., -fsm(dot) arg (disamb error before projection passes means graph cannot be built) +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + rec X + { + choice at A // -oldwf, default, -fair + { + 1() from A to B; + continue X; + } + or + { + 2() from A to B; + //2() from A to C; + 2() from B to C; + } + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + rec X + { + 1() from A to B; + continue X; + } + } + or + { + 2() from A to B; + } + 3() from B to C; +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + 1() from A to B; + () from B to C; + 1() from B to A; + } + or + { + 2() from A to B; + () from B to C; // Classic mergeability (no "equiv." protocol by sequencing -- unless maybe a generous async. equiv.) + 2() from B to A; + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + 1() from A to B; + 2() from B to C; + //3() from C to A; + 3() from C to B; + } + or + { + 1() from A to B; + 5() from B to C; + //6() from C to A; + 5() from C to B; // Mergeable -- A not involved downstream + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + rec X + { + 1() from A to B; + 1() from B to C; + continue X; + } + } + or + { + 2() from A to B; + 2() from B to C; + } + 3() from A to B; // Sequencing after recursive-choice + 3() from B to C; +} +//*/ + + +/* +global protocol Proto1(role A, role B) +{ + 1(Proto2@A) from A to B; // Testing delegation payload projection +} + +global protocol Proto2(role A, role B) +{ + 2() from A to B; +} +//*/ + + +/* +global protocol Proto1(role A, role B) +{ + (Proto1@A) from A to B; // Testing recursive protocoldecls +} +//*/ + + +/* +global protocol Proto1(role A, role B) +{ + (Proto2@A) from A to B; // Testing recursive protocoldecls +} + +global protocol Proto2(role A, role B) +{ + //(Proto1@A) from A to B; + (Proto3@A) from A to B; + //do Proto3(A, B); +} + +global protocol Proto3(role A, role B) +{ + 1() from A to B; + //(Proto1@A) from A to B; + //(Proto2@A) from A to B; + //do Proto1(A, B); +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + 1() from A to B; + 4() from B to C; + } + or + { + 2() from A to B; + 5() from B to C; // Mergeable subset of choice cases (cf. syntactic merge? + 5() from C to B; + } + or + { + 3() from A to B; + 5() from B to C; + 5() from C to B; + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + 1() from A to B; + do Game(A, B, C); + } + or + { + 2() from A to B; + 2() from B to C; + } +} + +aux global protocol Game(role A, role B, role C) +{ + () from A to B; + () from B to C; +} +//*/ + + +/* +global protocol Proto1(role A, role B) +{ + rec X + { + 1() from A to B; + rec X + { + 2() from A to B; + //do Proto1Aux(A, B); + } + } +} + +aux global protocol Proto1Aux(role A, role B) +{ + continue X; // Still checked for aux +} +//*/ + + +/* +global protocol Proto1(role A, role B) +{ + do Proto1Aux(A, B); +} + +aux global protocol Proto1Aux(role A, role B) +{ + M from A to B; +} +//*/ + + +/* +global protocol Proto1(role A, role B) +{ + (Test.Foo) from A to B; // Testing DataType disamb +} +//*/ + + +/* +type "java.lang.Integer" from "rt.jar" as Int; + +global protocol Proto1(role A, role B) +{ + Int from A to B; // Testing disamb (and AST visitChild) +} +//*/ + + +/* +sig "..." from "..." as M; + +global protocol Proto1(role A, role B) +{ + (M) from A to B; // Testing disamb (and AST visitChild) +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B, role C) +{ + connect A to B; + connect A to C; + rec X + { + choice at A + { + 1() from A to B; // Testing "fair"/"unfair" liveness -- issue of global liveness vs. local subtyping) -- generating "unfair output subtyped" global model (can it be done simply by terminal set role check?) + continue X; + } + or + { + 2() from A to B; + } + } + 3() from A to C; +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + rec X + { + choice at A + { + 1() from A to B; + continue X; + } + or + { + 1() from A to B; // Testing non-det unfairClone -- uninteresting test because non-det single-action-edge choice-merges get implicitly minimised (by graph building) + continue X; + } + or + { + 2() from A to B; + 2() from B to C; + } + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + rec X + { + choice at A + { + 1() from A to B; + 3() from B to A; + continue X; + } + or + { + 1() from A to B; // Testing non-det unfairClone + 3() from B to A; + //4() from B to A; + continue X; + } + or + { + 2() from A to B; + 2() from B to C; + } + } +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B, role C) +{ + connect A to B; + connect B to C; + connect A to C; // How does C "correlate" A/B connections to sessions -- introduces? -- need to study real examples +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B, role C) +{ + connect A to B; + rec X + { + 1() from A to B; + connect B to C; // C doesn't care whether each connection is new or old session? + 2() from B to C; + disconnect B and C; + continue X; + } +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B) +{ + connect A to B; + disconnect A and B; + connect A to B; // What does it mean for B to leave the session and rejoin? Need some condition like if fully leave, then rejoining should be same as new session? (i.e. this case bad) -- Consider implementability + disconnect A and B; +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B, role C) +{ + connect A to B; + rec X + { + choice at A + { + 1() from A to B; + 1() connect A to C; + disconnect A and C; + continue X; + } + or + { + 2() from A to B; + 2() connect A to C; + disconnect A and C; + continue X + } + } + connect A to C; // Good until here, now bad because C already fully left? + 3() from A to C; +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B) +{ + rec X + { + connect A to B; // What does this mean in terms of a "session"? (should consider the implementation, session id, ...) -- distinction between initial accept and in-session accepts? + //1() from A to B; + //1() from B to A; + disconnect A and B; // Shouldn't allow continuation after a certain point? no session structure left? + continue X; + } +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B, role C) +{ + connect A to B; + choice at A + { + 1() from A to B; + connect B to C; + connect A to C; + 1() from A to C; + } + or + { + 2() from A to B; + connect A to C; // Inconsistent choice connect subjects + } +} +//*/ + +//*** + + + +/* +explicit global protocol Proto1(role A, role B) +{ + connect A to B; + choice at A + { + 1() from A to B; + } + or + { + disconnect A and B; // CHECKME: disconnect shouldn't have asymmetric src/dest -- check enabling conditions wrt. choices, projection, etc + } +} +//*/ + + +/* +type "java.lang.Integer" from "rt.jar" as Int; + +explicit global protocol Proto1(role A, role B) +{ + choice at A + { + 1(Int) connect A to B; // Testing non-det payloads for message-connects + } + or + { + 1() connect A to B; + } +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B, role C) +{ + connect A to B; + rec X + { + choice at A + { + 1() from A to B; + } + or + { + 2() from A to B; + 2() connect B to C; + 2() from B to C; + disconnect B and C; + } + or + { + 3() from A to B; + 3() connect B to C; // Cf. PartnershipSupplier filter subproto + 3() from B to C; + disconnect B and C; + } + continue X; + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + rec X + { + choice at A + { + 1() from A to B; + 1() from B to C; + rec Y + { + choice at B + { + 3() from B to A; + continue X; + } + or + { + 4() from B to A; + continue Y; // Needs fairness + } + } + } + or + { + 2() from A to B; + 2() from B to C; + } + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + rec X + { + choice at A + { + 1() from A to B; + 1() from B to C; + choice at B // C not involved, but still live (without fairness) + { + 3() from B to A; + continue X; + } + or + { + 4() from B to A; + continue X; + } + } + or + { + 2() from A to B; + 2() from B to C; + } + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + rec X + { + choice at A + { + 1() from A to B; + 1() from B to C; + choice at B + { + 3() from B to A; + continue X; + } + or + { + rec Y // Bad (fair or not) + { + 4() from B to A; + continue Y; + } + } + } + or + { + 2() from A to B; + 2() from B to C; + } + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + rec X + { + choice at A + { + 1() from A to B; + 1() from B to C; // Live, without fairness + continue X; + } + or + { + 2() from A to B; + 2() from B to C; + } + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + rec X + { + 1() from A to B; + 1() from B to C; + continue X; + } + } + or + { + 2() from A to B; + 2() from B to C; // CHECKME: bad sequence if commented, correct? -- bad sequence because C not in block so projection pruned, then only rec-block left -- is this satisfactory? (consider standalone global semantics vs. global as syntactic sugar for locals) -- however, "bad sequence" restriction probably does not hurt expressiveness + } + 3() from B to C; +} +//*/ + + +/* +global protocol Proto1(role A, role B) +{ + choice at A + { + 1() from A to B; + } + or + { + 2() from A to B; + } + rec X // Testing non-fair EFSM generation + { + choice at B + { + 3() from B to A; + continue X; + } + or + { + 4() from B to A; + } + } +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B) +{ + connect A to B; + choice at A + { + 1() from A to B; + wrap B to A; + } + or + { + wrap A to B; + } +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B) +{ + connect A to B; + choice at A + { + 1() from A to B; + } + or + { + 2() from A to B; + disconnect A and B; // Testing unfairClone terminal state reconcilliation -- FIXME: this example doesn't actually test this, cf. SupplierInfoExplicit for requestor + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + rec X + { + choice at A + { + 1() from A to B; + continue X; + } + or + { + 2() from A to B; + } + } + //3() from A to C; // Testing fair/unfair liveness for C + 3() from C to A; // Message liveness also subject to fair/unfair +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + 1() from A to B; + () from B to C; + 3() from B to A; + } + or + { + 2() from A to B; + () from B to C; // choice + sequencing not the same as just syntactic sugar for factoring out a common branch continuation, i.e. cannot factor out "() from B" as a continuation without either losing causality for output to A or changing output order at B -- arguable that changing order at B is equivalent (for some equivalence), but not equivalent under basic bisimilarity + 4() from B to A; + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + 1() from A to B; // CHECKME: empty case for C discarded by projection, but do we need tau for correctness? this example works because it ends up as stuck error -- a point is generating tau and then bisim-minimising doesn't remove the tau, whereas the current projection does remove the tau (so current projection is not equiv to bisim-minimisation intuition) + // should be OK: intiution: an input-state endpoint cannot choose to not receive a message, i.e. input states should never have tau -- so whole system must satisfy properties when modelling "partial" local branches as a "complete" branch for just the involved choice cases (i.e. ignore any non-involved cases) + } + or + { + 2() from A to B; + 2() from A to C; + } + 3() from A to C; +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + rec X + { + choice at A + { + 1() from A to B; + continue X; + } + or + { + 2() from A to B; + } + } + 3() from A to C; // Not "strongly" live for C -- by subtyping, an implementation of A may never terminate -- strongly live probably means all roles have to be involved in every choice path -- not quite: it all depends on definition of subtyping, could make a "live" notion of subtyping that doesn't allow a non-live subset of choices -- this also depends on the select primitives and typing rules (it could come down to decidability of if-conditions...) -- problem is, even without subtyping, select primitive is always about selecting just one case, can't really make a "live" typing on top of that... -- could be positioned as basic session typing needs strong liveness, while weak liveness can be aimed at assuming a more general program verification -- or maybe a more powerful "imperative style" typing system could work, e.g. while (...) { ..non-live choice on s..} ..live choice on s.., i.e. it is ok to select a non-live case if the while will terminate to eventually lead us to a live case.. -- this fairness/liveness issue is another "bondary" issue between modelling/types/practice, bit like linearity +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B, role C) +//explicit global protocol Proto1(role A, role B) +{ + connect A to B; + choice at A + { + 1() from A to B; + } + or + { + 1() from A to B; + connect A to C; // Testing API gen (without I/O i/f gen) + } +} +//*/ + + +/* +global protocol Proto1(role A, role B) +{ + choice at A // Testing minfsm + { + 1() from A to B; + 2() from B to A; + } + or + { + 1() from A to B; + 2() from B to A; + } +} +//*/ + + +/* +global protocol Proto1(role A, role B) +{ + 2() from A to B; + rec X + { + choice at A + { + 1() from A to B; + 1() from A to B; + } + or + { + 1() from A to B; // Testing minfsm + 1() from A to B; + } + continue X; +} +//*/ + + +/* +global protocol Proto1(role A, role B) +{ + 2() from A to B; + rec X + { + choice at A + { + 1() from A to B; // Testing minfsm + } + or + { + 1() from A to B; + 1() from A to B; + } + continue X; +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B, role C) +{ + connect A to B; + connect A to C; // Bad + disconnect A and C; + choice at A + { + 1() from A to B; + } + or + { + 1() from A to B; + connect B to C; + } +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B, role C) +{ + connect A to B; + connect A to C; + choice at A + { + 1() from A to B; + 1() from A to C; + connect B to C; + 2() from A to B; + } + or + { + 1() from A to B; + 1() from A to C; + connect B to C; // Good: mergeable + 2() from A to B; + } +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B, role C) +{ + connect A to B; + connect A to C; + choice at A + { + 1() from A to B; + 1() from A to C; + connect B to C; + 2() from A to B; + } + or + { + 1() from A to B; + 1() from A to C; + connect C to B; // If A and C are in above, 2() can be stuck at B's connect/accept here -- but stuck error not directly detected, error manifests as B/C deadlock + 2() from A to B; // Mergeable if B/C connection not deadlocked + } +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B, role C) +{ + connect A to B; + choice at A + { + 1() from A to B; + connect B to C; + } + or + { + 1() from A to B; + } + 2() from B to C; // Trying to make an unconnected orphan from B to C, but currently will always get a connectedness error first -- model building semantics shouldn't/won't allow explicit unnconnected orphans, message cannot be sent if not connected +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B, role C) +{ + connect A to C; + connect C to B; + choice at A + { + 1() from A to C; + connect A to B; + } + or + { + 2() from A to C; + 2() from C to B; // Bad: connect and msg from different choice subjects + } +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B) +{ + rec X + { + choice at A + { + connect A to B; // Good: tests recursion pruning for connection actions + } + } +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B) +{ + rec X + { + choice at A // ** using old WF, this breaks connectedness checking -- WFChoiceChecker is an UnfoldingVisitor, but it is prunes the visit on entering the unfolded choice + { + connect A to B; + continue X; // Bad + } + } +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B, role C) +{ + connect A to B; + rec X + { + choice at A + { + 1() from A to B; + connect B to C; + disconnect B and C; // Comment is bad + continue X; + } + or + { + 2() from A to B; + } + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + rec X + { + choice at A + { + 2() from A to C; + 1() from A to B; + } + or + { + 2() from A to C; + 2() from C to A; + 2() from A to B; + } + continue X; + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + // Disable local choice subject inference + rec X + { + // Testing getTrace? + choice at A + { + 1() from A to B; + //1() from A to B; + 1() from A to C; + 3() from B to C; + continue X; + } + or + { + 1() from A to B; + 2() from B to C; + 3() from C to B; + continue X; + } + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + // Disable local choice subject inference + rec X + { + // Testing getTrace? + choice at A + { + 1() from A to B; + continue X; + } + or + { + 1() from A to B; + 1() from A to C; + 2() from C to B; + continue X; + } + or + { + 3() from A to C; + 3() from C to B; + continue X; + } + } +} +//*/ + + +/* +global protocol Proto1(role A, role B) +{ + rec X + { + choice at A + { + 1() from A to B; // Testing graph building + } + or + { + 1() from A to B; + } + continue X; + } +} +//*/ + + +/* +global protocol Partners( + role LOGINsvc, + role REQUESTOR, + role AUTHsvc, + role FILTERsvc, + role SUPPLIERsvc, + role CONTRACTsvc) +{ + login() from REQUESTOR to LOGINsvc; + choice at LOGINsvc + { + loginfailure() from LOGINsvc to REQUESTOR; + 0() from REQUESTOR to AUTHsvc; + 0() from AUTHsvc to FILTERsvc; + 0() from AUTHsvc to SUPPLIERsvc; + 0() from AUTHsvc to CONTRACTsvc; + } or { + loginsuccess() from LOGINsvc to REQUESTOR; + rec MAIN + { + choice at REQUESTOR + { + getsuppliers() from REQUESTOR to AUTHsvc; + choice at AUTHsvc + { + getsuppliers() from AUTHsvc to SUPPLIERsvc; // Bad: testing getTrace performance + deny() from AUTHsvc to REQUESTOR; + } or { + getsuppliers() from AUTHsvc to SUPPLIERsvc; + suppliers() from SUPPLIERsvc to AUTHsvc; + filterSuppliers() from AUTHsvc to FILTERsvc; + filtered() from FILTERsvc to AUTHsvc; + suppliers() from AUTHsvc to REQUESTOR; + } + } or { + getcontracts() from REQUESTOR to AUTHsvc; + choice at AUTHsvc + { + deny() from AUTHsvc to REQUESTOR; + } or { + getcontracts() from AUTHsvc to CONTRACTsvc; + contracts() from CONTRACTsvc to AUTHsvc; + filterContracts() from AUTHsvc to FILTERsvc; + filtered() from FILTERsvc to AUTHsvc; + contracts() from AUTHsvc to REQUESTOR; + } + } + continue MAIN; + } + } +} +//*/ + + +/* +global protocol Proto1 +( + role REQuestor, + role AUTHsvc, + role SUPPLIERsvc, + role CONTRACTsvc) +{ + rec MAIN + { + choice at REQuestor + { + getsuppliers() from REQuestor to AUTHsvc; + choice at AUTHsvc + { + getsuppliers() from AUTHsvc to SUPPLIERsvc; // Bad: testing getTrace + deny() from AUTHsvc to REQuestor; + } or { + getsuppliers() from AUTHsvc to SUPPLIERsvc; + suppliers() from SUPPLIERsvc to AUTHsvc; + suppliers() from AUTHsvc to REQuestor; + } + } or { + getcontracts() from REQuestor to AUTHsvc; + choice at AUTHsvc + { + deny() from AUTHsvc to REQuestor; + } or { + getcontracts() from AUTHsvc to CONTRACTsvc; + contracts() from CONTRACTsvc to AUTHsvc; + contracts() from AUTHsvc to REQuestor; + } + } + continue MAIN; + } +} +//*/ + + + +/* +global protocol Proto(role A, role B) +{ + choice at A + { + 1() from A to B; + disconnect A and B; + } + or + { + 1() from A to B; + 2() from B to A; // B can still send even if A disconnects (async) -- so not wait-for from that situation + } +} +//*/ + + +/*/ +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + 1() from A to B; + + 1() from A to C; + 1() from A to C; + + 3() from C to B; + } + or + { + 1() from A to B; + + () from B to C; // Trying to get A into above block while C is in here, such that WF1 forces C also into the above -- so that WF1 becomes unsound + 2() from A to C; + + 4() from C to B; + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + choice at C + { + 1() from C to B; + 1() from C to A; + } + or + { + 1() from C to B; + 2() from C to A; + + 2() from A to B; + 2() from A to B; + + 2() from A to C; + + 2() from C to B; + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + rec X + { + choice at A + { + 1() from A to B; + continue X; + } + } + } + or + { + 2() from A to B; + } + + 2() from C to B; // TODO: investigate: WF_1 won't get past here, is it OK? + 2() from C to B; // ..becomes "fake" role liveness problem because of WF1 -- not live even assuming fairness + // ..dragons + + // TODO: investigate reachability of local states in global model +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + choice at B + { + 0() from B to C; + 0() from B to A; + 2() from C to B; + choice at A + { + rec X + { + choice at A + { + 1() from A to B; + continue X; + } + } + } + or + { + 2() from A to B; + } + } + or + { + 0() from B to C; + 1() from B to A; + 2() from C to B; // Good + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + choice at B + { + 0() from B to C; + 0() from B to A; + + //2() from C to B; + //2() from C to B; + + choice at A + { + rec X + { + choice at A + { + 1() from A to B; + //2() from C to B; + continue X; + } + } + } + or + { + 2() from A to B; + } + } + or + { + 0() from B to C; + 1() from B to A; + } + + 2() from C to B; // TODO: investigate: WF_1 won't get past here, is it OK? + 2() from C to B; // ..becomes "fake" role liveness problem because of WF1 + // ... + + // TODO: investigate reachability of local states in global model +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + // Trying to construct a counterexample for WF1 soundness.. + // ..need to find an error state that is unreachable by WF1 but reachable by e.g. WF2 + // Try to find a choice where B is falsely committed to a branch due to WF1 (so state space of model is unsoundly restricted) + choice at A + { + 1() from A to B; + 1() from A to B; + 2() from A to C; // A cannot do this in WF1 unless B receives a 1() first + } + or + { + 3() from A to C; + //2() from A to B; + // Local choice subjects require B to also receive from A in this block + // Two cases: same or different label + // If different label, then no possibility of false branch commitment + // If same label, then non-det always allows B to enter this block, even under WF1 + // Therefore: false choice commitment not possible + 1() from A to B; + 1() from A to B; + } +} +//*/ + + +/* +explicit global protocol Proto1(role A, role B, role C) +{ + connect A to B; + choice at A + { + 1() from A to B // Good non-det EFSM for A (including minimisation) + connect A to C; + } + or + { + 1() from A to B; + //connect A to C; // Tests -minfsm + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + // Needs local choice subject disabled, though the point is it's still bad + choice at A + { + a() from A to B; + //d() from C to B; // Moved down to make C enabled + cprime() from A to C; + d() from C to B; + b() from B to A; + y() from A to B; // Orphan + } + or + { + c() from A to C; + d() from C to B; // ..point is B could get in this case, while A (and C) are in the other + b() from B to A; + a() from A to B; // (..not stuck msg error because the a() from above is consumed here) + x() from B to A; // Orphan + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + // Counterexample for WF1 if local choice subject disabled + choice at A + { + a() from A to B; + a() from A to B; // WF1 unnaturally resolves the non-det choice at B by forcing B to commit to this branch before C is enabled + cprime() from A to C; + d() from C to B; + b() from B to A; + + //y() from A to B; // Potential orphan + } + or + { + c() from A to C; + d() from C to B; + b() from B to A; // Must come before a's, to prevent reverse choice race + a() from A to B; + a() from A to B; + + //x() from B to A; // Potential orphan + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + // Disable local choice subject inference -- mergeable + choice at A + { + 1() from A to B; + 1() from A to B; + 1() from A to C; + 2() from C to B; + } + or + { + 2() from A to C; + 2() from C to B; + 1() from A to B; + 1() from A to B; + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + 1() from A to B; + 1() from A to B; + 1() from A to C; + 2() from C to B; + + 3() from B to C; + } + or + { + 2() from A to C; + 2() from C to B; + 1() from A to B; + 1() from A to B; + + //3() from B to C; + 4() from B to C; // Bad + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + 1() from A to B; + 1() from A to B; + 1() from A to C; + 2() from C to B; + 2() from C to B; + + 3() from B to C; // Should be potential stuck + } + or + { + 2() from A to C; + 2() from C to B; + 2() from C to B; + () from C to A; // Another counterexample to WF1 (B falsely committed to here when A/C are) + 1() from A to B; + 1() from A to B; + + 4() from B to C; // Should be potential stuck + } +} +//*/ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +/* +global protocol Proto1(role A, role B, role C) +{ + choice at A + { + 1() from A to B; + 1() from B to C; + } + or + { + 2() from A to B; // TODO: link model check errors to source code? -- though this protocol is syntactically bad... + } + or + { + 1() from B to C; + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + // Testing one-slot asynchrony + rec X + { + choice at A + { + 1() from A to B; + 1() from A to C; + 1() from C to B; // Bad... but the point is one-slot asynchrony prevents exploring the global state where A!B:1 done twice without B?A:1 at least once, i.e. A cannot loop round first block twice without B also following into the first block... can something like this make WF unsound? -- is recursive mixed-role poly-inputs the only context for this problem? + } + or + { + 2() from A to C; + 2() from C to B; + } + continue X; + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C, role D) +{ + rec X + { + 1() from A to B; + continue X; // Checking safety in non-terminating global model + } + choice at C + { + 2() from C to D; + 3() from D to C; // Stuck messages also manifest as message liveness violations (CHECKME: subsumed? so unnecessary to check safety except for actual terminations? -- but morally, they are local safety errors for the roles, as opposed to global liveness errors for the system) + } + or + { + 2() from C to D; + 4() from D to C; + } +} +//*/ + + +/* +global protocol Proto1(role A, role B, role C) +{ + rec X + { + choice at A + { + 1() from A to B; + choice at A + { + 1() from A to C; + continue X; // ** CHECKME: badly formed (for B) -- empty block bvelow is pruned leaving only the continue case, which leads to deadlock in global model, is this OK as WF algorithm? (any way to be unsound?) or should explicitly detect inconsistent choice block projections? + } + or + { + 3() from A to C; + } + } + or + { + 2() from A to C; + 2() from A to B; + } + } +} +//*/ + + +/* // TODO: test "transitive" intermediate continue-edge fixing? +global protocol Proto1(role A, role B) +{ + rec Y + { + 0() from A to B; + rec X + { + 1() from A to B; + choice at A + { + continue X; + } + or + { + continue Y; + } + } + } +} +//*/ + + +/* // Cf. -oldwf (non disjoint enabling) +global protocol Proto1(role A, role B) +{ + rec X + { + rec Y + { + choice at A + { + 1() from A to B; + } + or + { + 2() from A to B; + } + choice at A // EFSM state blowup -- FIXME: syntactic unfolding still necessary with global model checking? (for enabling?) or minimise before model checking? + { + continue X; + } + or + { + //2() from A to B; + //continue X; + continue Y; + } + } + } +} +//*/ + + +/* +global protocol Proto1(role A, role B) +{ + rec Y + { + rec X + { + 1() from A to B; + choice at A + { + continue X; // FIXME: non-fair is just slow, or non-terminating? + } + or + { + continue X; + } + or + { + continue Y; + } + or + { + 2() from A to B; + } + } + } +} +//*/ + + +/* // ?? +import Test2; + +type "java.lang.String" from "rt.jar" as String; +//*/ + + +/* // Simple name coincides with full name + // Some corner cases related to simple/full name overlap for default pa +module Test; + +import Test; +//*/ + +/* +module Test; + +import Test as Test; +//*/ + +/* +module Test; + +import Test2 as Test; // Good or bad? + +global protocol Proto(role A, role B) +{ + 1() from A to B; + do Test.Proto(A, B); +} +//*/ + + +/* // Some corner cases related to simple/full name overlap for default package Modules not tested in test suite (all Modules packaged) +import Test2; +import Test3 as Test3; // The name Test3 is test3.Test3 in Test2 +import test3.Test3 as Test4; // The name Test4 is actually Test4 in Test2 +//import test3.Test3 as Test3; + +global protocol Proto1(role A, role B) +{ + 1() from A to B; + do Test2.Proto2(A, B); + do Test3.Foo3(A, B); + do Test4.Bar3(A, B); +} +//*/ + + +/* +global protocol Foo(role A, role B) +{ + 1() from A to B; + do Bar(A, B); + 2() from A to B; +} + +aux global protocol Bar(role A, role B) // Testing bad unused role decls (wrt. subprotocol collected role occurrences) -- allow as aux? +{ + +} +//*/ + + +/* +global protocol Foo(role A, role B) // Project for A +{ + do Bar1<1(), 2()>(A, B); + do Bar1<3(), 4()>(A, B); +} + +global protocol Bar1(role A, role B) +{ + do Bar2(A, B, A); // TODO: duplicate role args +} + +global protocol Bar2(role A, role B, role C) +{ + M1 from A to B; + M2 from B to C; +} +//*/ + + diff --git a/scribble-test/src/test/scrib/tmp/Test2.scr b/scribble-test/src/test/scrib/tmp/Test2.scr new file mode 100644 index 000000000..17b1ec2e9 --- /dev/null +++ b/scribble-test/src/test/scrib/tmp/Test2.scr @@ -0,0 +1,78 @@ +//Raymond@HZHL3 ~/code/scribble-java/scribble-java +//$ java -cp modules/cli/target/classes/';'modules/core/target/classes';'modules/trace/target/classes';'modules/parser/target/classes';c:\Users\Raymond\.m2\repository\org\antlr\antlr-runtime\3.2\antlr-runtime-3.2.jar;'modules/validation/target/classes/';'modules/projection/target/classes/';C:\Users\Raymond\.m2\repository\org\codehaus\jackson\jackson-mapper-asl\1.9.9\jackson-mapper-asl-1.9.9.jar;C:\Users\Raymond\.m2\repository\org\codehaus\jackson\jackson-core-asl\1.9.9\jackson-core-asl-1.9.9.jar' org.scribble.cli.CommandLine -path modules/validation/src/test/scrib/src/ -validate Test + +module Test2; + + +import Test; + + +/*global protocol Proto(role C, role D) +{ + 2() from C to D; +}*/ + + +/*type "java.lang.String" from "rt.jar" as String2; + +//* +global protocol Proto2(role C, role D) +{ + Test2() from C to D; +} +//*/ + + +//* +import test3.Test3 as Test3; // The name Test3 is Test3 in Test1 +import Test4; // The name Test4 is test3.Test3 in Test1 +import Test4 as T4; + +global protocol Proto2(role C, role D) +{ + 2(Test3.TTT) from C to D; + do Test3.Bar3(C, D); + do Test4.Proto4(C, D); + do T4.Proto4(C, D); +} +//*/ + + +/*/ +global protocol Foo(role A, role B, role C) +{ + choice at A + { + 1() from A to B; + //do Bar(A, B); + choice at A + { + 3() from A to C; + } + } + or + { + 2() from A to B; + choice at A + { + 4() from A to C; + } + } +} +//*/ + + +/* +global protocol Bar(role C, role D) +{ + 3() from C to D; + do Test.Foo(C, D); +} + +//global protocol Foo2(role A, role B) +global protocol Foo(role A, role B) +{ + 4() from A to B; +} +//*/ + diff --git a/scripts/chversion.sh b/scripts/chversion.sh deleted file mode 100755 index d61cc1478..000000000 --- a/scripts/chversion.sh +++ /dev/null @@ -1,20 +0,0 @@ -#!/bin/bash -# Takes two parameters, the 'from' and 'to' versions - -FROMVER=$1 -TESTFROMVER=`echo $FROMVER | egrep '*-SNAPSHOT'` -TOVER=$2 -TESTTOVER=`echo $TOVER | egrep '*-SNAPSHOT'` - -perl -pi -e "s/$FROMVER/$TOVER/g" `find . -name pom.xml` - -if [ "$TESTFROMVER" == "$FROMVER" ]; then - FROMVER=`echo $FROMVER | sed 's/-SNAPSHOT/.SNAPSHOT/g'` -fi - -if [ "$TESTTOVER" == "$TOVER" ]; then - TOVER=`echo $TOVER | sed 's/-SNAPSHOT/.SNAPSHOT/g'` -fi - -perl -pi -e "s/$FROMVER/$TOVER/g" `find . -name MANIFEST.MF` - diff --git a/scripts/publish.sh b/scripts/publish.sh deleted file mode 100755 index 13a78d19a..000000000 --- a/scripts/publish.sh +++ /dev/null @@ -1,6 +0,0 @@ -#!/bin/bash -# Publish the bundles to nexus - -if [ "$RELEASE" == "No" ]; then - mvn clean deploy -fi diff --git a/travis/publish.sh b/travis/publish.sh new file mode 100755 index 000000000..c4f841d1f --- /dev/null +++ b/travis/publish.sh @@ -0,0 +1,117 @@ +set -euo pipefail +set -x + +build_started_by_tag() { + if [ "${TRAVIS_TAG}" == "" ]; then + echo "[Publishing] This build was not started by a tag, publishing snapshot" + return 1 + else + echo "[Publishing] This build was started by the tag ${TRAVIS_TAG}, publishing release" + return 0 + fi +} + +is_pull_request() { + if [ "${TRAVIS_PULL_REQUEST}" != "false" ]; then + echo "[Not Publishing] This is a Pull Request" + return 0 + else + echo "[Publishing] This is not a Pull Request" + return 1 + fi +} + +is_travis_branch_master() { + if [ "${TRAVIS_BRANCH}" = master ]; then + echo "[Publishing] Travis branch is master" + return 0 + else + echo "[Not Publishing] Travis branch is not master" + return 1 + fi +} + +check_travis_branch_equals_travis_tag() { + #Weird comparison comparing branch to tag because when you 'git push --tags' + #the branch somehow becomes the tag value + #github issue: https://github.com/travis-ci/travis-ci/issues/1675 + if [ "${TRAVIS_BRANCH}" != "${TRAVIS_TAG}" ]; then + echo "Travis branch does not equal Travis tag, which it should, bailing out." + echo " github issue: https://github.com/travis-ci/travis-ci/issues/1675" + exit 1 + else + echo "[Publishing] Branch (${TRAVIS_BRANCH}) same as Tag (${TRAVIS_TAG})" + fi +} + +check_release_tag() { + tag="${TRAVIS_TAG}" + if [[ "$tag" =~ ^[[:digit:]]+\.[[:digit:]]+\.[[:digit:]]+$ ]]; then + echo "Build started by version tag $tag. During the release process tags like this" + echo "are created by the 'release' Maven plugin. Nothing to do here." + exit 0 + elif [[ ! "$tag" =~ ^release-[[:digit:]]+\.[[:digit:]]+\.[[:digit:]]+$ ]]; then + echo "You must specify a tag of the format 'release-0.0.0' to release this project." + echo "The provided tag ${tag} doesn't match that. Aborting." + exit 1 + fi +} + +is_release_commit() { + project_version=$(./mvnw help:evaluate -N -Dexpression=project.version | grep -v '\[') + if [[ "$project_version" =~ ^[[:digit:]]+\.[[:digit:]]+\.[[:digit:]]+$ ]]; then + echo "Build started by release commit $project_version. Will synchronize to maven central." + return 0 + else + return 1 + fi +} + +release_version() { + echo "${TRAVIS_TAG}" | sed 's/^release-//' +} + +safe_checkout_master() { + # We need to be on a branch for release:perform to be able to create commits, and we want that branch to be master. + # But we also want to make sure that we build and release exactly the tagged version, so we verify that the remote + # master is where our tag is. + git checkout -B master + git fetch origin master:origin/master + commit_local_master="$(git show --pretty='format:%H' master)" + commit_remote_master="$(git show --pretty='format:%H' origin/master)" + if [ "$commit_local_master" != "$commit_remote_master" ]; then + echo "Master on remote 'origin' has commits since the version under release, aborting" + exit 1 + fi +} + +#---------------------- +# MAIN +#---------------------- + +if ! is_pull_request && build_started_by_tag; then + check_travis_branch_equals_travis_tag + check_release_tag +fi + +./mvnw --batch-mode install -nsu + +# If we are on a pull request, our only job is to run tests, which happened above via ./mvnw install +if is_pull_request; then + true +# If we are on master, we will deploy the latest snapshot or release version +# - If a release commit fails to deploy for a transient reason, delete the broken version from bintray and click rebuild +elif is_travis_branch_master; then + #./mvnw --batch-mode -s ./.settings.xml -Prelease -nsu -DskipTests deploy + # + ## If the deployment succeeded, sync it to Maven Central. Note: this needs to be done once per project, not module, hence -N + #if is_release_commit; then + # ./mvnw --batch-mode -s ./.settings.xml -nsu -N io.zipkin.centralsync-maven-plugin:centralsync-maven-plugin:sync + #fi + true + +# If we are on a release tag, the following will update any version references and push a version tag for deployment. +elif build_started_by_tag; then + safe_checkout_master + ./mvnw --batch-mode -s ./.settings.xml -Prelease -nsu -DreleaseVersion="$(release_version)" -Darguments="-DskipTests" release:prepare +fi